#include <Script.h>
#include "error.h"
#include "kant load-save.h"
#include "kant main window.h"
#include "kant.h"
#include "file interface.h"
#include "text twiddling.h"
#include "dialogs.h"
#include "environment.h"
#include "util.h"
#include "graphics.h"
#include "window layer.h"
#include "program globals.h"

void LoadSaveDispatch(Boolean isLoad, Boolean useOldFile)
{
	FSSpec			saveFile;
	Boolean			alreadyExists;
	enum ErrorTypes	theError;
	WindowPtr		mainWindowPtr;
	
	if ((!isLoad) && ((mainWindowPtr=GetIndWindowPtr(kMainWindow))==0L))
		return;
	
	if (isLoad)
	{
		if (GetSourceFile(&saveFile, SAVE_TYPE))
		{
			theError=GetTheFile(&saveFile);
			if (theError!=noErr)
				HandleError(theError, FALSE, FALSE);
		}
	}
	else
	{
		saveFile=GetWindowFS(mainWindowPtr);
		useOldFile=useOldFile&&(saveFile.name[0]!=0x00);
		if (!useOldFile)
		{
			if (!GetDestFile(&saveFile, &alreadyExists, "\pSave document as..."))
				return;
		}
		
		theError=SaveTheFile(saveFile, alreadyExists);
		if (theError!=noErr)
			HandleError(theError, FALSE, FALSE);
	}
}

enum ErrorTypes SaveTheFile(FSSpec saveFile, Boolean alreadyExists)
{
	OSErr			theError;
	short			thisFile;
	long			count;
	TEHandle		hTE;
	WindowPtr		theWindow;
	
	theError=noErr;
	
	if (!alreadyExists)
	{
		theError=FSpCreate(&saveFile, CREATOR, SAVE_TYPE, smSystemScript);
		FlushVol(0L, saveFile.vRefNum);
	}
	
	if (theError!=noErr)
		return kCantCreateFile;
	
	FSpCreate(&saveFile, CREATOR, SAVE_TYPE, smSystemScript);
	theError=FSpOpenDF(&saveFile, fsRdWrPerm, &thisFile);
	
	if (theError!=noErr)
		return kCantOpenFileToSave;

	theWindow=GetIndWindowPtr(kMainWindow);
	hTE=GetWindowTE(theWindow);
	count=(**hTE).teLength;
	theError=SetEOF(thisFile, count);
	if (theError!=noErr)
	{
		FSClose(thisFile);
		return kDiskFull;
	}
	
	SetFPos(thisFile, 1, 0L);
	theError=FSWrite(thisFile, &count, *((**hTE).hText));
	
	FSClose(thisFile);
	FlushVol(0L, saveFile.vRefNum);

	if (theError!=noErr)
	{
		saveFile.name[0]=0x00;
		return kCantWriteFile;
	}
	
	SetWTitle(theWindow, saveFile.name);
	SetWindowTitle(theWindow, saveFile.name);
	SetWindowFS(theWindow, saveFile);
	SetWindowIsModified(theWindow, FALSE);
	
	return allsWell;
}

enum ErrorTypes GetTheFile(FSSpec *saveFile)
{
	short			thisFile;
	long			count;
	OSErr			theError;
	Ptr				data;
	WindowPtr		theWindow;
	
	theError=FSpOpenDF(saveFile, fsRdPerm, &thisFile);
	if (theError!=noErr)
		return kCantOpenFileToLoad;
	
	GetEOF(thisFile, &count);
	data=NewPtr(count);
	SetFPos(thisFile, 1, 0L);
	theError=FSRead(thisFile, &count, data);
	FSClose(thisFile);
	
	if (theError!=noErr)
		return kCantLoadFile;
	
	OpenTheIndWindow(kMainWindow);
	theWindow=GetIndWindowPtr(kMainWindow);
	SetWTitle(theWindow, saveFile->name);
	SetWindowTitle(theWindow, saveFile->name);
	SetTheText(theWindow, data, count);
	SetWindowFS(theWindow, *saveFile);
	SetWindowIsModified(theWindow, FALSE);
	DisposePtr(data);
	
	return allsWell;
}
