#include "stdafx.h"
#include "FrotzCE.h"
#include "FrotzCEDoc.h"
#include "ZThread.h"

extern "C"
{
	#include "Frotz\Frotz.h"

	// Z machine values
	extern int locked;
	extern int z_finished;

	// Default file names
	extern char script_name[];
	extern char command_name[];
	extern char save_name[];
	extern char auxilary_name[];
}

UINT ZMachineThreadFunction( LPVOID pParam )
{
	// Flag that Z machine is running
	FROTZCEAPP->m_bZmachineRunning = TRUE;

	// Initialise Frotz globals
	FrotzGlobalInit();

	// Set name of story file
	story_name = FROTZCEAPP->m_achStoryFile;

	// Create temp file name and make sure it's got a '.'
	char *temp_name = new char[strlen( story_name )+2];
	strcpy( temp_name, story_name );
	if (strchr( temp_name, '.' ) == NULL)
		strcat( temp_name, "." );
	else *(strchr( temp_name, '.' ) + 1) = '\0';

	// Set up default file names
	strcpy( script_name, temp_name );
	strcat( script_name, "scr");
	strcpy (command_name, temp_name );
	strcat( command_name, "rec");
	strcpy (save_name, temp_name );
	strcat( save_name, "sav");
	strcpy (auxilary_name, temp_name );
	strcat( auxilary_name, "aux");
	
	// Free temp file name
	delete [] temp_name;

	// Initialise Z machine values
	locked = 0;
	z_finished = 0;

	// Initialise Z machine
    init_memory ();

	// Initialise screen
    os_init_screen ();

	// Initialised OK?
	if (FROTZCEAPP->m_bInitialised)
	{
		// Initialise Z machine
		init_undo ();
		z_restart ();

		// Z machine main loop
		interpret ();

		// Reset memory
		reset_memory ();

		// Wait for user
		os_more_prompt();
	}
	else
	{
		// Reset memory
		reset_memory ();
	}

	// Flag that Z machine is no longer running
	FROTZCEAPP->m_bZmachineRunning = FALSE;

	// Reset display
    os_reset_screen ();

    return 0;
}
