#include "masc_dll.h"
#include<windows.h>

int error_count, line_count;
char outfile[256];
int verbose;
int finished = 0;

void freeAll() {

}

FILE *sptr = 0;


void dump_stdout() {
	sptr = freopen("stdout.txt","w",stdout);
	if(!sptr) {
		fprintf(stdout,"Error on reassign!\n");
		return;
	}
}

void close_stdout() {
	fflush(stdout);
	fclose(sptr);
}


struct BackEnd back_end[100];
struct Token *ptr_tok[100];
struct convertHolder hold[100];
int bend_offset = 0;

int __stdcall masc_run(const char *source, struct BackEnd *ptr) {
	struct text_in source_text;
	
	
	dump_stdout();
	ptr = &back_end[bend_offset];
	if(!ptr) {  ptr = 0; return 0; }
	strcpy(outfile,"run.masc");
	printf("Executing file %s \n", source);
	initText_in(source, &source_text);
	parse(&source_text,ptr_tok[bend_offset]);
	freeText_in(&source_text);
	hold[bend_offset]  = convertIcode("run.masc",ptr_tok[bend_offset],&back_end[bend_offset]);
	printDebugInfo("debug_before.html",&back_end[bend_offset],hold[bend_offset].tokens);
	printf("Symbol Table\n");
	symNode_Print(&back_end[bend_offset].g_stable.root);
	printf("Token codes\n");
	printTokens(hold[bend_offset].tokens, back_end[bend_offset].inc_len);
	if(hold[bend_offset].rt_val != 0) 
	executeIcode(back_end[bend_offset].incp,hold[bend_offset].tokens,&back_end[bend_offset]);
	freeIcode(ptr_tok[bend_offset],&back_end[bend_offset]);
	printf("Successfully executed %s\n", source);
	return bend_offset++;
}


int __stdcall masc_callback ( int (__stdcall *cfunc)(const char *_PROC_name, struct BackEnd *bend, struct Token *ptr_tok) ) {
	if(!cfunc)  return 0; 
	callback = cfunc;
	return 1;
}



int __stdcall masc_stop(struct BackEnd *ptr) {
	close_stdout();
	finished = 1;
	return 1;
}

int __stdcall masc_call(int bend_offset, const char *proc_name) {
	struct symNode *node_ptr = Search(&back_end[bend_offset].g_stable.root,proc_name);
	if(node_ptr) {
		char dat[255];
		Push(&back_end[bend_offset].ist,(float)i_p);
		sprintf(dat,"%d\n", node_ptr->line);
		executeIcode(node_ptr->line,hold[bend_offset].tokens,hold[bend_offset].bend);
	}
	return 0;
}

struct BackEnd* __stdcall masc_getbend(int offset) {
	return &back_end[offset];
}