
/**
 * Package:	UAM Text Tools
 * Component:	dgp (dg parser)
 * Version:	1.0
 * Author:	Tomasz Obrebski
 */

#include "global.hh"
#include "mgraph.hh"
#include "sgraph.hh"
#include "grammar.hh"
#include "dgp0.hh"
#include "../common/common.h"
#include "cmdline.h"

#define MAXSEGMENTS 500

char segment[MAXSEGMENTS][MAXLINE];
int segcount=0;
char seg_mnode[MAXSEGMENTS];
char grammarfile[255];


Grammar grammar;
MGraph mgraph;
SGraph sgraph;

FILE* grammarf;
FILE* debugf=stdout;
unsigned int info=0U;

void output();

main(int argc, char* argv[])
{
  gengetopt_args_info args;

  if(cmdline_parser(argc,argv,&args) != 0)
    exit(1);

  process_config_files(&args,argv[0]);
  process_common_options(&args,argv[0]);

  if(!args.grammar_given)
    fprintf(stderr,"dgp: no grammar given\n");

  expand_path(args.grammar_arg,grammarfile);

  if(!(grammarf=fopen(grammarfile,"r")))
    fprintf(stderr,"dgp: grammar file not found: %s.\n", grammarfile), exit(1);

  if(args.debug_given) debug=true;

  for(char* c=args.info_arg; *c!='\0' ; ++c)
    switch(*c)
    {
    case 'h': info|=SGraph::HEADS; break;
    case 'd': info|=SGraph::DEPS; break;
    case 's': info|=SGraph::SETS; break;
    case 'c': info|=SGraph::CONSTRAINTS; break;
    }

  grammar.read(grammarf);
  fclose(grammarf);

  mgraph.clear();
  sgraph.clear();

  char line[1000];
  while (fgets(line, MAXLINE+1, inputf))
  {
    line[strlen(line)-1] = '\0';
    strcpy(segment[segcount],line);

    char segtype[80];

    seg_mnode[segcount] = process_seg(line, args) ? mgraph.add_node(line) : -1;

    segcount++;

    getfield(line,"3",segtype);
    if(strcmp(segtype,"EOS")==0)
    {
      dgp0(); // parametry!!! MGraph, SGraph, Grammar
      output();
      
      mgraph.clear();
      sgraph.clear();
      segcount=0;
    }
    //    if(args.interactive_flag) { fflush(outputf); fflush(failedf); }
  }
  
  fclose(inputf);
  fclose(outputf);
  cmdline_parser_free(&args);
  exit(0);
}

void output()
{
  for(int si=0; si<segcount; ++si)
  {
    if(seg_mnode[si]>=0)
    {
      MNode& m=mgraph.nodes[seg_mnode[si]];
      for(vector<int>::iterator s=m.snodes.begin(); s!=m.snodes.end(); ++s)
      {
        fputs(segment[si],outputf);
        sgraph.print_node(outputf, *s, info);
        fputc('\n',outputf);
      }
    }
    else
    {
      fputs(segment[si],outputf);
      fputc('\n',outputf);
    }
  }
}
