
/* start of programs */
#include <stdio.h>

#ifdef YYDEBUG
extern void* er_yy_current_buffer;
#endif

typedef struct yy_buffer_state *YY_BUFFER_STATE;
YY_BUFFER_STATE er_yy_scan_string (const char *yy_str);

/* parse a specification.

   returns 0 on success, non-0 on error.
   always creates a response string which must be freed after use.
*/
int ER_parse_spec(char *buf, char **ert) 
{
  lexerr_t  erst;
  int res;

  /* mutex lock call to prevent side-effects with globals in the Yacc code */
  static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

#if YYDEBUG != 0
  extern int yydebug;
  yydebug = 1;
#endif 

  pthread_mutex_lock(&mutex);

  memset(&erst,  0, sizeof(erst));

  er_yy_switch_to_buffer( er_yy_scan_string(buf) );
  res =  er_yyparse(&erst);
  
  lexcleancurbuf();	

  if( res != 0 ) {
    int i;

    /*		wr_clean_list(erst.filtlist);*/
	
    *ert = UT_malloc(strlen(buf) + strlen(erst.errtxt) 
		  + erst.errpos + 12 /* for \n^\nERROR: \n" */ );

    strcpy(*ert,buf);	
    strcat(*ert,"\n");
    for(i=1;i<erst.errpos;i++){strcat(*ert," ");}
    strcat(*ert,"^\n");
    strcat(*ert,"ERROR: ");
    strcat(*ert,erst.errtxt);
    strcat(*ert,"\n");
  }
  else {
    *ert = UT_malloc(strlen(erst.errtxt)+5);
    strcpy(*ert, "OK ");
    strcat(*ert,erst.errtxt);
    strcat(*ert,"\n");
  }

  mycleanup( &erst );

  pthread_mutex_unlock(&mutex);

  return res;
}


void
myerror(void *ypar, char *s)
{
  lexerr_t *erst = ypar;
  adderr(erst, s);
}



er_ret_t
mysetsev(lexerr_t *erst, int ismax, char *spec)
{
  er_ret_t es = er_getsevval(spec); /* 0 means not found */

  er_ret_t *sevptr = ismax ? &( erst->curfilt.sev_max )
    : &( erst->curfilt.sev_min );
  if( es ) {
    *sevptr = es;
  }
  else {
    adderr(erst, "incorrect sev specification: ");
    adderr(erst, spec);	
  }
  er_yy_tracelog("sev%s = %s (%x)\n", ismax ? "max" : "min" , spec, es);

mycleanup(erst);
return es;
}


void mycleanup(void *ypar)
{ 
  lexerr_t *erst = ypar;

  if(erst->token) {
    er_yy_tracelog("string :  %s cleanup after strdup\n", erst->token); 
    UT_free(erst->token); 
    erst->token = NULL;
  }
}


void
er_yy_tracelog(char *fmt, ...)
{
#if 0
  va_list   ap;

  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
#endif 
}
