/* dBoxTools.c.mapping */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "window.h"

#include "clibExtra.h"
#include "error.h"

#include "dboxtools.h"
#include "find.h"
#include "main.h"
#include "mapping.h"
#include "read.h"
#include "strbuild.h"

static int depth = 0;

_kernel_oserror *mapping_lookup
( Action *target, char *text, int space )
{ _kernel_oserror *er = NULL;
  Action *a;
  unsigned flags;
  char *in;

  er = gadget_get_flags( 0, target->object, target->component, &flags );
  if( er ) return er;
  if( flags >> 31 )
    a = find_action( firstFadedMapping, target );
  else
    a = find_action( firstMapping, target );
  
  if( a )
  { if( a->arg[0] )
    { if( space > strlen( a->arg[0] ))
      { if( debug )
          fprintf( debug, "  %x:%x mapping %s to %s\n",
                   a->object, a->component, target->value, a->arg[0] );
        strcpy( text, a->arg[0] );
      }  
      else
      { error_block.errnum = ERROR_BUFFER_OVERFLOW;
        sprintf( error_block.errmess,
                 "Line %i: Buffer full while mapping", target->line );
        er = &error_block;
      }
      if( depth++ > 100 ) error( "Probable infinite loop in mapping" );
      in = myStrdup( text );
      NER( strbuild_build( in, text, space, NULL, -1, NULL, NULL, NULL, 0 ));
      free( in );
      depth--;
    }
    else
      *text = 0;  
  }    
  return er; 
}

/* end of c.mapping */
