/*
	Twilight Prophecy 3D/Multimedia SDK
	A multi-platform development system for virtual reality and multimedia.

	Copyright (C) 1997-2001 by Twilight 3D Finland Oy Ltd.
*/
/*
	NEVER include this header manually, included by system when needed.
*/
#include "../string.hpp"
#include "../exception.hpp"


// user entrypoint
extern int prmain(int argc, char** argv);


// system entrypoint
int APIENTRY WinMain(HINSTANCE instance, HINSTANCE previnstance, LPSTR commandline, int show)
{
	// -----------------------------------------------------------
	// original implementation:
	// www.flipcode.com - "Code Of The Day" - by Max McGuire
	// -----------------------------------------------------------

	// count the arguments
	int argc = 1;
	char* arg  = commandline;

	while (arg[0] != 0) 
	{
		while (arg[0] != 0 && arg[0] == ' ') 
		{
			arg++;
		}

		if (arg[0] != 0) 
		{
			argc++;
			while (arg[0] != 0 && arg[0] != ' ') 
			{
				arg++;
			}
		}
	}    

	// tokenize the arguments
	char** argv = new char*[argc];

	arg = commandline;
	int index = 1;

	while (arg[0] != 0) 
	{
		while (arg[0] != 0 && arg[0] == ' ') 
		{
			arg++;
		}

		if (arg[0] != 0) 
		{
			argv[index] = arg;
			index++;

			while (arg[0] != 0 && arg[0] != ' ') 
			{
				arg++;
			}

			if (arg[0] != 0) 
			{
				arg[0] = 0;    
				arg++;
			}
		}
	}    

	// put the program name into argv[0]
	char filename[_MAX_PATH];

	GetModuleFileName(NULL,filename,_MAX_PATH);
	argv[0] = filename;

	int result = 0;

	// exception handling
	try
	{
		// call the user specified main function
		result = prmain(argc,argv);
	}
	catch (prcore::Exception& e)
	{
		e.DrawDialog();
	}

	delete[] argv;
	return result;
}
