
#include "yodl.h"

void
gram_INCLUDEFILE ()
{
  static int
    include_level;		/* how many files */
  char
   *name, *realname, *old_lexbuf, *old_cur_input_file;
  int
    old_cur_lineno;
  FILE
    * old_inf;
  TOKEN
    old_lextok;

  /* jcn-hsearch?? */
  char *old_lexer_pushed;
  char *old_lexer_pushedp;

  include_level++;
  if (include_level > maxpass)	/* recursive? */
    error_gram ("%s", "nesting depth exceeds %d",
		builtin_get (idx_INCLUDEFILE), maxpass);

  name = gram_parlist (builtin_get (idx_INCLUDEFILE), 0);
  gram_onename (builtin_get (idx_INCLUDEFILE), name);
  realname = file_expandname (name);
  message (2, "including file: %s\n", realname);
  free (name);

  old_cur_input_file = cur_input_file;
  cur_input_file = realname;

  old_cur_lineno = cur_lineno;
  cur_lineno = 0;

  old_inf = inf;
  inf = open_file (realname, "r");

  old_lexbuf = lexbuf;
  lexbuf = 0;

  old_lextok = lextok;

  /* jcn-hsearch?? */
  old_lexer_pushed = lexer_pushed;
  lexer_pushed = 0;

  old_lexer_pushedp = lexer_pushedp;
  lexer_pushedp = 0;

  parse ();

  /* jcn-hsearch?? */
  lexer_pushed = old_lexer_pushed;
  lexer_pushedp = old_lexer_pushedp;

  lextok = old_lextok;

  free (lexbuf);
  lexbuf = old_lexbuf;

  close_file (inf);
  inf = old_inf;

  cur_lineno = old_cur_lineno;

  cur_input_file = old_cur_input_file;

  message (2, "done with included file: %s\n", realname);

  free (realname);

  include_level--;
}
