#import "BWMainObject.h"
#import "BWOverWorld.h"
#import "BWGameData.h"

@implementation BWMainObject

- (void)awakeFromNib
{
	path = nil;
	romData = nil;
}

- (IBAction)open:(id)sender
{
	int r;
	NSOpenPanel *op = [NSOpenPanel openPanel];
	r = [op runModalForTypes:nil];
	if (r == NSOKButton) {
		
		if (path) [path release];
		path = [[NSString alloc] initWithString:[[op filenames] lastObject]];
		NSLog(@"Path : %@",path);
		
		if (romData) [romData release];
		romData = [[NSMutableData alloc] initWithContentsOfFile:path];
		NSLog(@"romData length : %X",[romData length]);
		NSLog(@"--------");
		// Eventually check if the file is good, even if we don't really care...
		// But if the file is less than a normal ROM's, bad access could happen...
		
		[objOverWorld open:romData];
		[objGameData open:romData];
		
		NSLog(@"ROM loaded");
		NSLog(@"--------");
	}
}

- (IBAction)save:(id)sender
{
	[objOverWorld save];
	[objGameData save];
	
	if ([romData writeToFile:path atomically:YES])
		NSLog(@"Save - OK");
	else
		NSLog(@"Save - Error");
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
	int i;
	if (romData) {
		i = NSRunAlertPanel(@"Do you want to save before quitting ?",@"",@"Save",@"Cancel",@"Don't Save");
		if (i == NSAlertAlternateReturn) return NO;
		else if (i == NSAlertOtherReturn) return YES;
		else { [self save:nil]; return YES; }
	} else {
		return YES;
	}
}

@end

