#include <stdio.h>

#include "dummyConfLoader.hh"
#include "ConfParser.hh"

#define CONF_ENV "AUV_CONFIG_DIR"

void ll_reset();
size_t ll_getLine();

int ConfParserparse();

extern FILE *ConfParserin;
extern dummyConfLoader *s_loader;
extern ArgList s_args;
static Symbol s_errorBuff;
static Symbol s_fileName;

void dummyConfLoader::load(Symbol const &fileName) /* throw(ParseError) */ {
  m_parser->parse(fileName, *this);
}

Symbol &parsing_message(Symbol const &type) {
  char lineVal[10];

  if( !s_errorBuff.empty() )
    s_errorBuff += ".\n";
  sprintf(lineVal, "%u", ll_getLine());
  s_errorBuff += s_fileName+":"+lineVal+":"+type+": ";
  return s_errorBuff;
}

/*
 * class ConfParser
 */
void ConfParser::parse(Symbol const &fileName, dummyConfLoader &loader) {
  int ret;
  
  ll_reset();
  s_loader = &loader;
  s_args.clear();
  s_errorBuff.clear();

  ConfParserin = fopen(fileName.c_str(), "r");

  if( NULL==ConfParserin ) {
    char *conf_dir;
    
    if( NULL!=(conf_dir = getenv(CONF_ENV)) ) {
      Symbol confFile(conf_dir);

      confFile += "/"+fileName;
      ConfParserin = fopen(confFile.c_str(), "r");
    } else 
      s_errorBuff += Symbol("warning: $")+CONF_ENV+" is undefined";
  }
  if( NULL==ConfParserin ) {
    s_errorBuff += "Unable to open "+fileName;
    throw ParseError(s_errorBuff);
  }
  s_fileName = fileName;
  ret = ConfParserparse();

  if( 0!=ret ) 
    throw ParseError(s_errorBuff);
  else if( !s_errorBuff.empty() )
    fprintf(stderr, "%s\n", s_errorBuff.c_str());
}
