// FrotzCEDoc.cpp : implementation of the CFrotzCEDoc class
//

#include "stdafx.h"
#include "FrotzCE.h"

#include "FrotzCEDoc.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFrotzCEDoc

IMPLEMENT_DYNCREATE(CFrotzCEDoc, CDocument)

BEGIN_MESSAGE_MAP(CFrotzCEDoc, CDocument)
	//{{AFX_MSG_MAP(CFrotzCEDoc)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFrotzCEDoc construction/destruction

CFrotzCEDoc::CFrotzCEDoc()
{
}

CFrotzCEDoc::~CFrotzCEDoc()
{
}

/////////////////////////////////////////////////////////////////////////////
// CFrotzCEDoc diagnostics

#ifdef _DEBUG
void CFrotzCEDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CFrotzCEDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CFrotzCEDoc commands

BOOL CFrotzCEDoc::OnOpenDocument(LPCTSTR lpszPathName) 
{
CString strStoryFile = lpszPathName;
char *pszStoryFile = FROTZCEAPP->m_achStoryFile;

	// Z machine not running?
	if (!FROTZCEAPP->m_bZmachineRunning)
	{
	LPTSTR pszDefDir;
	int i;

		if (!CDocument::OnOpenDocument(lpszPathName))
			return FALSE;

		// Copy file name
		FROTZCEAPP->m_strDefaultDir = strStoryFile;

		// Get file name buffer
		i = FROTZCEAPP->m_strDefaultDir.GetLength();
		pszDefDir = FROTZCEAPP->m_strDefaultDir.GetBuffer( i + 1 );

		// Go backwards in file name until first '\' is found
		for (; i >= 0; i--)
		{
			// Found a directory specifier?
			if (pszDefDir[i] == _T('\\') || pszDefDir[i] == _T('/'))
			{
				pszDefDir[i] = 0;
				break;
			}
		}
		// Resize string
		FROTZCEAPP->m_strDefaultDir.ReleaseBuffer();

		// Convert wide char file name to single byte chars
		for (i = 0; i < strStoryFile.GetLength(); i++)
		{
			pszStoryFile[i] = (char) strStoryFile[i];
		}
		pszStoryFile[strStoryFile.GetLength()] = '\0';

		// Start Z machine
		FROTZCEAPP->StartZMachine();	
	
		return TRUE;
	}
	else return FALSE;
}
