//
// Copyright(c) 2001 Simon Howard
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License
// as published by the Free Software Foundation.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//--------------------------------------------------------------------------
//
// Main program; command line parsing and execution
//
//--------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>

#include "parser.h"

#define VERSION "1.1.0"

static char *infile = NULL, *outfile = NULL;
static char *exefile = NULL;
static int assemble = 1;

void usage()
{
	printf("bfc " VERSION "\n"
	       "\n"
	       "Usage:\n"
	       "bfc [options] file.bf\n"
	       "  -o file          specify output file\n"
	       "  -S               just output IL source; do not assemble\n"
	       "  -h               display help\n"
	       "  -v               display version\n"
		); 
	exit(-1);
}

int main(int argc, char *argv[])
{
	FILE *in_fs, *out_fs;
	treenode_t *tree;
	int i;

	// check command line
	
	if (argc < 2) {
		usage();
	}

	for (i=1; i<argc; ++i) {
		if (!strcmp(argv[i], "-o")) {
			++i;
			if (i < argc) {
				exefile = argv[i];
			} else {
				usage();
			}
		} else if (!strcmp(argv[i], "-S")) {
			assemble = 0;
 		} else if (!strcmp(argv[i], "-h")) {
			usage();
		} else if (!strcmp(argv[i], "-v")) {
			puts(VERSION);
			exit(-1);
		} else if (argv[i][0] != '-') {
			infile = argv[i];
		} else {
			usage();
		}
	}

	if (!infile)
		usage();

	// default names for output files
	
	if (assemble) {
  		if (!exefile)
			exefile = "a.exe";

		outfile = malloc(strlen(infile) + 6);
		sprintf(outfile, "%s.il", infile);
	} else {
		if (exefile) {
			outfile = exefile;
		} else {
			outfile = malloc(strlen(infile) + 6);
			sprintf(outfile, "%s.il", infile);
		} 
	}

	// compile
	
	in_fs = fopen(infile, "r");

	if (!in_fs) {
		fprintf(stderr, "bfc: %s not found\n", infile);
		exit(-1);
	}

	tree = Parser_ParseFile(in_fs);

	fclose(in_fs);

	out_fs = fopen(outfile, "w");

	if (!out_fs) {
		fprintf(stderr, "bfc: cant open %s for writing\n", outfile);
		exit(-1);
	}
	
	tree->print(tree, out_fs);

	fclose(out_fs);

	// call the assembler if we have to
	
	if (assemble) {
		int ret;
		char *cmd;

		cmd = malloc(strlen(exefile) + strlen(outfile) + 20);
		sprintf(cmd, "ilasm -o %s %s\n", exefile, outfile);

		ret = system(cmd);

		remove(outfile);
		
		exit(ret);
	}
	
	exit(0);
}
