#import <Foundation/Foundation.h>
#import "EXPAssemblerConstants.h"
#import "EXPStackMachine.h"
#import "EXPAssembler.h"

int main (int argc, const char * argv[]) 
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//	printf("%d %d %d\n",  sizeof(int), sizeof(unsigned short int), sizeof(double));

	NSProcessInfo *processInfo = [NSProcessInfo processInfo];
	NSArray *arguments = [processInfo arguments];
	NSString *path;
/*	if ([arguments count]>1) {
		path = [arguments objectAtIndex:1];
	} else {
		path = @"/Users/ashley/Projects/Objective-C/TestProgs/StackMachine2/test.asm";
	} */
	path = @"/Users/ashley/Projects/Objective-C/TestProgs/StackMachine2/test.asm";
	BOOL echo = NO;
	
	int narg;
	for (narg = 1; narg<[arguments count]; narg++) {
		NSString *arg = [arguments objectAtIndex:narg];
		if ([arg characterAtIndex:0]=='-') {
			if ([arg isEqualToString:@"-v"]) {
				echo = YES;
			} else if ([arg isEqualToString:@"-q"]) {
				echo = NO;
			} else {
			}
		} else {
			path = arg;
		}
	}
	
//	NSString *path = @"/Users/ashley/Projects/Objective-C/TestProgs/StackMachine2/test.asm";
	NSString *sourceFileContents = [[NSString alloc] initWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];

	if (sourceFileContents==nil) {
		printf("Cannot open input file\n");
		exit(-1);
	}

	NSArray *source = [sourceFileContents componentsSeparatedByString:@"\n"];
	[sourceFileContents release];
	
	unsigned int memorySize = 65536;
	EXPStackMachine *machine = [[EXPStackMachine alloc] initWithMemory:memorySize];
	
	EXPAssembler *assembler = [[EXPAssembler alloc] init];
	[assembler setMachine:machine];
	
	[machine setPtr:0];
	BOOL success = [assembler assemble:source echo:echo];
	if (!success) {
		exit(-1);
	}
	
	if (echo) {
		[assembler dumpSymboltable];
	}
	

//	[machine dump:0 to:[machine pc]];

	NSDictionary *symboltable = [assembler symbolTable];
	
	[machine setSp:[machine ptr] + 32];
	[machine setPc:0];
	[machine setGp:[machine ptr]];
	[machine runFromPc];
	unsigned short int *memory = [machine memory];
/*	printf("%g\n", *(double *)memory); */
	printf("Accumulator = %g\n", [machine acc_fp]);
	int i;
	for(i=[[symboltable objectForKey:@"DATA"] intValue];i<[[symboltable objectForKey:@"STACK"] intValue];i+=4) {
		printf("%04x: %g\n", i, *(double *)(&memory[i]));
	}
	
	[machine release];
	
    [pool release];
    return 0;
}
