
#include "yodl.h"

/*
  expand a singe macro, e.g.:
      
      DEFINEMACRO(filename(0)(foo)
      TYPEOUT(Writing file: DOEXPAND(filename)

  urg, should lexer get to handle this.
 */

char*
gram_do_expand (char* str)
{
  char expandstring[1024];
  char* p;
  char* q;
  char* expand;
  char* expansion;
  char macro[8192];
  char dir[1024];
  char buf[80];
  int i; 

  expand = strstr (str, "DOEXPAND(");
  while (!dont_do_expand_global && expand && *expand)
    {
      strcpy (macro, expand + strlen ("DOEXPAND("));
      p = strchr (macro, ')'); 
      if (p)
	*p = 0;
#if 0
      this breaks DOEXPAND(Fr\)`ere hack
      gram_onename (builtin[idx_DOEXPAND], macro);
#endif
      expansion = macro;
      if ((i = strtab_find (builtin, nbuiltin, macro)) != -1)
        {
	  /*  lexer_pushed ... ?
	    builtins[i].func();
	    urg urg urg */
	  if (i == idx_FILENAME)
	    expansion = cur_input_file;
	  else if (i == idx_OUTFILENAME)
	    expansion = outfname;
	  else if (i == idx_OUTDIR)
	    {
	      strcpy (dir, outfname);
	      expansion = dirname (dir);
	    }
	  else
	    expansion = macro;
	}
      else if ((i = strtab_find (userdef, nuserdef, macro)) != -1)
	expansion = definition[i];
      else if ((i = strtab_find (countername, ncountername, macro)) != -1)
        {
	  sprintf (buf, "%d", counterval[i]);
	  expansion = buf;
	}
      else
	expansion = macro;

      sprintf (expandstring, "DOEXPAND(%s)", macro);

      message (3, "%s %s %s\n", "do_expand: ", str_short (expansion), str_short (str));
      str = str_replace (str, expandstring, expansion);
      /*
        urg, expand only once
       */
      if (expand && *expand)
	expand = strstr (expand + strlen (expansion), "DOEXPAND(");
    }
  return str;
}

