#import <Foundation/Foundation.h>
#import "EXPModel.h"
#import "EXPExpression.h"
#import "DDESolver.h"
#import "DDEHistory.h"
#import "DDEIStepper.h"
#import "EXPStackMachine.h"
#import "PLTMatrix.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	NSProcessInfo *processInfo = [NSProcessInfo processInfo];
	NSArray *arguments = [processInfo arguments];
	NSString *filename = nil;
	
	int i;
	for(i=1; i<[arguments count]; i++) {
		filename = [[arguments objectAtIndex:i] stringByExpandingTildeInPath];
	}
	
	if (filename==nil) {
		filename = @"/Users/ashley/Projects/Objective-C/TestProgs/XMLTest/test.dde";
	}
	NSString *ext = [filename pathExtension];

	EXPModel *doc = [[EXPModel alloc] init];
//	[doc loadFromXMLFile:@"/Users/ashley/Projects/Objective-C/TestProgs/XMLTest/test.xml"];

	BOOL success = YES;
	NSData *data = [[NSData alloc] initWithContentsOfFile:filename];
	if ([ext isEqualToString:@"dde"]) {
		 success = [doc loadFromDDEData:data encoding:NSUTF8StringEncoding];
	} else if ([ext isEqualToString:@"xml"]) {
	} else {
		 success = NO;
	}
	[data release];
	
	if (!success) {
		[doc release];
		exit(-1);
	}
	
	NSArray *sheets = [doc sheets];
	if ([sheets count]==0) {
		[doc release];
		exit(-1);
	}
	
	printf("\n\n");
	[doc compile];

	[doc initConstants];
	
	DDEIStepper *stepper = [[DDEIStepper alloc] initWithRhs:doc];
	DDESolver *solver = [[DDESolver alloc] initWithRhs:doc stepper:stepper];
	[stepper release];
	
	EXPStackMachine *machine = [doc machine];
	[machine setHistory:[solver history]];
	
	[solver solve];
	
	[doc print];
	[doc plot];
	
	[machine setHistory:nil];
	[solver release];
	[doc release];
	
    [pool release];

	[EXPElement reportElementCount];
	printf("\nnumEXPExpressionsInited = %d\n", [EXPExpression numEXPExpressionsInited]);
	printf("numEXPExpressionsDealloced = %d\n", [EXPExpression numEXPExpressionsDealloced]);

    return 0;
}
