#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include "consthash.h"
#include "types.h"
#include "funchash.h"
#include "callhash.h"
#include "semchecks.h"
#include "codegen.h"


extern int yyparse( void );
extern int yyerrors;
extern expr prog_expr;


BOOL verbose          = FALSE;
BOOL expand_constants = FALSE;


int main( int argc, char **argv )
{
	int opt;

        while ((opt = getopt(argc, argv, "v")) != -1) {
		switch (opt) {
		case 'v':
			verbose = 1;
			break;
		default: /* '?' */
			fprintf(stderr, "Usage: %s [-v] [arg1 [arg2..]]\n",
				argv[0]);
			fprintf(stderr, "       -v: verbose\n" );
			exit(1);
		}
	}

	int i, j;
	for( i=optind, j=1; i<argc; i++, j++ )
	{
		argv[j] = argv[i];
	}
	argc -= optind-1;

	init_consthash( argc, argv );
	init_funchash( );
	init_callhash( );
	if( verbose )
	{
		fprintf( stderr, "\tStarting parsing\n" );
	}
        if( yyparse() == 0 && yyerrors == 0 )
	{
		if( verbose )
		{
			fprintf( stderr, "Parsing succeeded\n" );
			fprintf( stderr, "\t- " );
			print_callhash( stderr );
		}
		check_calls();
		if( yyerrors > 0 )
		{
			fprintf( stderr, "Semantic checks failed with "
			        "%d errors\n",
				yyerrors );
			exit(1);
		}
		if( verbose )
		{
			fprintf( stderr,
				"Semantic checks succeeded\n" );
		}
		write_dafny_program( stdout, prog_expr );
	} else
	{
		fprintf( stderr, "Parsing failed with %d errors\n", yyerrors );
		exit(1);
	}
	destroy_consthash();
	destroy_funchash();
	destroy_callhash();
	free_expr( prog_expr );
	return 0;
} 
