/*	Author:		Magdin Stoica
	Supervisor: Dr. Ryan Leduc
	
	Project created in conformity with the requirements for the Degree of Master of Engineering in Software Engineering, 
	Computing and Software Department, 
	McMaster University
	2003 - 2007
*/

#include <QApplication>
#include <iostream>
#include <QString>
#include <QMessageBox>
#include "MainForm.h"
#include "CommonDefinitions.h"
#include "HostFileManager.h"
#include <string.h>

using namespace DESpot;

int main(int argc, char* argv[])
{
	try
	{
		#ifdef __ENABLE_DIST__
		// Check if the application was started with mpirun
		if (getenv("OMPI_COMM_WORLD_RANK") == NULL)
		{	
			// Check if the hostfile exists
			if (!HostFileManager::hostFileExists())
				HostFileManager::createHostFile();

			// It was not, so relaunch it with mpirun
			char** args = (char**)malloc(sizeof(char*)*(argc + 5));
			args[0] = "mpirun";
			args[1] = "-np";
			args[2] = "1";
			args[3] = "-hostfile";
			
			string hostfile = HostFileManager::getHostFileName();
			args[4] = (char*)malloc(sizeof(char)*hostfile.length());
			strcpy(args[4], hostfile.c_str());

			for (int i = 0; i < argc; i++)
			{
				args[i+3] = (char*)malloc(sizeof(char*)*(strlen(argv[i])));
				strcpy(args[i+3], argv[i]);
			}

			execvp("mpirun", args);

			return EXIT_SUCCESS;
		}
		#endif


		Q_INIT_RESOURCE(DESpot);
		
		QApplication app(argc, argv);
		MainForm*	 mainForm = new MainForm;
		mainForm->open();
		return app.exec();
	}
	catch(EXO)
	{
		QMessageBox::critical(null, QString("DESpot Error"), exo_msg());	
                return -1;
	}
	catch(...)
	{
		QMessageBox::critical(null, QString("DESpot Error"), "An unhandled exception was detected. Program will terminate.");
                return -1;
	}
}

