/* 
 * (C) 2006 Copywrite. All rights reserved.
 *
 * A program to load a java launch program 
 * with jvm.dll in the PATH enviroment variable.
 *
 * Author : Matthew William Coan
 * Date   : 1:25 PM 8/22/2006
 **/

// load.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>

using namespace std;

string
GetJRE_PATH()
{
	FILE * f = fopen("jre.properties", "r");
	
	if(f == NULL)
		return string("");

    int ch;
	string str;

	while((ch = fgetc(f)) != EOF)
	{
		str += ((char)ch);
	}

	fclose(f);

	string ret;
	int i = 0;
	while(i < str.size()) {
		if(str[i] == '=')
		{
			i++;

			ret = str.substr(i);
		    
			break;
		}

		i++;
	}


	return ret;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.

   STARTUPINFO          si = { sizeof(si) };
   PROCESS_INFORMATION  pi;
   char                 szExe[] = "launch.exe";
   //char *				path = getenv("PATH");
   char *				env = "PATH=%s";
   string				jre = GetJRE_PATH();
   size_t size = strlen(env) + jre.size() + 10;
   char * buffer0 = new char[size];
   memset(buffer0, 0, size);
   sprintf(buffer0, env, jre.c_str());
   TCHAR * buffer = new TCHAR[size];
   memset(buffer, 0, size * sizeof(TCHAR));
   lstrcpy(buffer, TEXT(buffer0));
   delete [] buffer0;

   if(CreateProcess(0, szExe, 0, 0, FALSE, 0, (LPVOID)buffer, 0, &si, &pi))
   {
	   // optionally wait for process to finish
       WaitForSingleObject(pi.hProcess, INFINITE);

       CloseHandle(pi.hProcess);
	   CloseHandle(pi.hThread);
   }

   delete [] buffer;

   return 0;
}



