/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1987, 1991 by Mike Parker.			    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

#include <varargs.h>

#include "defs.h"
#include "fsm.h"

FSMarg *_TMPFSM_getarg();
static char *instring = 0;

static doInit();
static parse();

static do_cleanup()
{
	IND_CHAIN *in;
	extern IND_CHAIN *tree_match__input;
#define input tree_match__input

	while (input)
	 {
#ifdef VXWORKS_CFG
	   if (! input->noclose) fclose(input->file);
#else
	   if (input->file != stdin) fclose(input->file);
#endif
	   in = input->link;
	   OLD(input);
	   input = in;
	 }
#undef input
#ifdef VXWORKS_CFG
	th_freeall();
	instring = 0;
#endif
}

static int initDone = 0;
#define INIT_CHECK()	(initDone||doInit())
static doInit()
{
 initDone = 1;
 requestFlagInit (&initDone);
 requestExitFxn (do_cleanup, 0);
}

static int parse()
{
 int i;

 _TMP_init_fsmsubs();
 i = _TMPFSM_(instring);
 return(i);
}

#ifdef lint
/* firstarg is because lint doesn't seem to handle VARARGS0 correctly */
/* VARARGS */
char *tree_match_parse(firstarg,va_alist)char*firstarg;
#else
char *tree_match_parse(va_alist)
#endif
va_dcl
{
 va_list ap;
 int l;
 int L;
 int i;
 char num[12];
 char *cp;

 INIT_CHECK();

#ifdef lint
 firstarg = firstarg;
#endif
 tree_match__maybe_init();
 va_start(ap);
 if (instring)
  { free(instring);
  }
 instring = malloc(1);
 L = 0;
 for (i=0;;i++)
  { cp = va_arg(ap,char *);
    if (cp == 0)
     { break;
     }
    if (i&1)
     { sprintf(num,"%u",(unsigned int)cp);
       cp = num;
     }
    l = strlen(cp);
    instring = realloc(instring,L+l+1);
    strcpy(instring+L,cp);
    L += l;
  }
 va_end(ap);
 instring[L] = '\0';
 if (parse())
  { return((char *)_TMP_current_tree);
  }
 return(0);
}

char *tree_match_err_at()
{
 return(_TMPFSM_getarg()->string);
}

_TMP_debug_trace(state,name)
int state;
char *name;
{
#ifdef lint
 state = state;
 name = name;
#endif
#ifdef TRACE_PARSE
 printf("%s (%d) string %s\n",name,state,tree_match_err_at());
#endif
}

_TMP_debug_action(what)
char *what;
{
#ifdef lint
 what = what;
#endif
#ifdef TRACE_PARSE
 printf("Calling %s\n",what);
#endif
}
