
#include <stdio.h>
#import <appkit/Text.h>
#import "Brain.h"

#define MAXPATHLENGTH		300

@implementation Brain

- init
{
	FILE *systemCall;
	char *path = malloc(MAXPATHLENGTH);

	systemCall = popen("pwd", "r");
	fscanf(systemCall, "%s", path);
	pclose(systemCall);

	savePanel = [SavePanel new];
	//[savePanel setDirectory:path];
	openPanel = [OpenPanel new];
	//[openPanel setDirectory:path];
	outputString = (char *)malloc(500);

	free(path);
	return self;
}

- free
{
	[savePanel free];
	[openPanel free];
	free(outputString);
	return [super free];
}

- saveIt:sender
{
	int result;
	char *temp;
	
	result = [savePanel runModal];
	sprintf(outputString, "Result of running SavePanel modal is: %d\nThe"
	" filename is:\n%s\n", result, [savePanel filename]);
	if (result) {
		theFile = fopen([savePanel filename], "r");
		if (!theFile) {
			temp = (char *)malloc([fileText textLength] + 1);
			[fileText getSubstring:temp start:0
				length:[fileText textLength] + 1];
			theFile = fopen([savePanel filename], "w");
			fprintf(theFile, "%s", temp);
			fclose(theFile);
			strcat(outputString, "Wrote TEXT to file.\n");
			free(temp);
		} else {
			strcat(outputString, "File already exists--write aborted\n");
			fclose(theFile);
		}
	}
	[outputText setText:outputString];
    return self;
}

- openIt:sender
{
	int result;
	NXStream *theStream;
	
	result = [openPanel runModal];
	sprintf(outputString, "Result of running OpenPanel modal is: %d\nThe"
	" filename is:\n%s\n", result, [openPanel filename]);
	if (result) {
		theStream = NXMapFile([openPanel filename], NX_READONLY);
		if (!theStream) {
			strcat(outputString, "ERROR!  Could not open file!  Something is"
			" wrong with the OpenPanel.\n");
		} else {
			[fileText readText:theStream];
			NXClose(theStream);
			strcat(outputString, "Writing file's contents to TEXT.\n");			
		}
	}
	[outputText setText:outputString];
    return self;
}

- clearText:sender
{
	[fileText setText:""];
	return self;
}

@end
