#!/usr/local/bin/pike

import Stdio;
#if __VERSION__ >= 0.6
import ".";
#endif /* __VERSION__ >= 0.6 */

#include "types.h"

int main(int argc, string *argv)
{	
  mixed *ER=catch {
    program output=(program)argv[2];
    werror("Reading ");
    string input=Stdio.read_file(argv[1]);
    werror("Lexing ");
    mixed data=Sgml.lex(input,argv[1]);
    werror("Grouping ");
    data=Sgml.group(data);
    werror("Verifying\n");
    Wmml.verify(data,input,argv[1]);
    werror("Concretizing\n");
    WMML wmml=Wmml.make_concrete_wmml(data);
#ifdef WALL
    werror("Undocumented functions: \n%-#75s\n",(indices(all_constants()) - indices(wmml->index_data))*"\n");
#endif
    werror("\nWriting output\n");
    output()->output(argv[3],wmml);
    write("Ok\n");
    exit(0);
  };

  if(ER)
  {
    catch {
      if(arrayp(ER) && sizeof(ER)>1 && arrayp(ER[1]))
      {
	mixed x;
	x=ER[1];
	x=reverse(x);
	foreach(x,x)
	  {
	    for(int e=3;e<sizeof(x);e++)
	    {
	      mixed s=x[e];
	      if(!arrayp(s)) s=({s});
	      foreach(s,s)
		{
		  if(object_program(s)==Sgml.Tag)
		  {
		    if(s->pos)
		    {
		      werror("\nThis error occured close to tag "+s->tag+" near "+s->location()+"\n");
		      throw(0);
		    }
		  }
		}
	    }
	  }
      }
    };
    throw(ER);
  }
}
