// CMainThread.cpp
// Where all the excitement begins
// Casey Fleser
// October 24, 1997

#include <BeHeaders>

#include "CMainThread.h"
#include "CMAMEApp.h"
#include "Defines.h"

extern "C" {
extern int mamemain(int argc,char **argv);
}

int gQuitting;

CMainThread::CMainThread(
	int		argc,
	char		**argv)
{
	int32		i;
	
	gQuitting = 0;
	
	mArgc = argc;
	mArgv = (char **)::malloc(sizeof(char *) * argc);
	for (i=0; i<mArgc; i++) {
		mArgv[i] = (char *)::malloc(strlen(argv[i]) + 1);
		strcpy(mArgv[i], argv[i]);
	}
}

CMainThread::~CMainThread()
{
	status_t		val;
	int32		i;
	
	gQuitting = 1;
	
	wait_for_thread(mID, &val);

	for (i=0; i<mArgc; i++)
		::free(mArgv[i]);
	::free(mArgv);
}

int32
CMainThread::Entry(
	void		*arg)
{
	CMainThread	*obj = (CMainThread *)arg;
	
	return (obj->MainLoop());
}

int32
CMainThread::MainLoop()
{
	int		mameStatus;
		
	mameStatus = mamemain(mArgc, mArgv);
	
	if (!gQuitting) {
		BMessage	statusMessage(eWhat_MAMEStatus);

		statusMessage.AddInt16("status", mameStatus);
		be_app->PostMessage(&statusMessage);
	}
	
	((CMAMEApp *)(be_app))->Main() = NULL;
	
	return mameStatus;
}

int32
CMainThread::Go()
{
	mID = spawn_thread(Entry, mArgc > 1 && mArgv[1][0] != '-' ? mArgv[1] : "MAME", B_DISPLAY_PRIORITY /*+ 1*/, this);
	return (resume_thread(mID));
}

