
#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;

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

  name = gram_parlist (builtin[idx_INCLUDEFILE], 0);
  gram_onename (builtin[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;

  parse ();

  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--;
}
