/* 
 * (C) 2006 Copywrite. All rights reserved.
 *
 * A program to launch a GUI program.
 *
 * Author : Matthew William Coan
 * Date   : 1:29 PM 8/22/2006
 *
 **/

#include "stdafx.h"

#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
 
#define PATH_SEPARATOR ';' /* define it to be ':' on Solaris */
#define USER_CLASSPATH "." /* where Prog.class is */
 

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.
     JNIEnv *env;
     JavaVM *jvm;
     jint res;
     jclass cls;
     jmethodID mid;
     jstring jstr;
     jclass stringClass;
     jobjectArray args;

	 /*
	 char * path = getenv("PATH");
	 const char * jvmPATH = "C:\\Program Files\\Java\\jdk1.5.0_07\\jre\\bin\\client";
	 char * buffer;
	 size_t size = strlen(path) + strlen(jvmPATH) + 10;
	 buffer = new char[size];
	 memset(buffer, 0, size);
	 sprintf(buffer, "PATH=%s;%s", jvmPATH, path);
	 putenv(buffer);
     delete [] buffer;
	 */

 #ifdef JNI_VERSION_1_2
     JavaVMInitArgs vm_args;
     JavaVMOption options[1];
     options[0].optionString =
         "-Djava.class.path=" USER_CLASSPATH;
     vm_args.version = 0x00010002;
     vm_args.options = options;
     vm_args.nOptions = 1;
     vm_args.ignoreUnrecognized = JNI_TRUE;
     /* Create the Java VM */
     res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
 #else
     JDK1_1InitArgs vm_args;
     char classpath[1024];
     vm_args.version = 0x00010001;
     JNI_GetDefaultJavaVMInitArgs(&vm_args);
     /* Append USER_CLASSPATH to the default system class path */
     sprintf(classpath, "%s%c%s",
             vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH);
     vm_args.classpath = classpath;
     /* Create the Java VM */
     res = JNI_CreateJavaVM(&jvm, &env, &vm_args);
 #endif /* JNI_VERSION_1_2 */
 
     if (res < 0) {
         fprintf(stderr, "Can't create Java VM\n");
         exit(1);
     }
     cls = (env)->FindClass("Prog");
     if (cls == NULL) {
         goto destroy;
     }
 
     mid = (env)->GetStaticMethodID(cls, "main",
                                     "([Ljava/lang/String;)V");
     if (mid == NULL) {
         goto destroy;
     }
     jstr = (env)->NewStringUTF(" from C!");
     if (jstr == NULL) {
         goto destroy;
     }
     stringClass = (env)->FindClass("java/lang/String");
     args = (env)->NewObjectArray(1, stringClass, jstr);
     if (args == NULL) {
         goto destroy;
     }
     (env)->CallStaticVoidMethod(cls, mid, args);
 
 destroy:
     if ((env)->ExceptionOccurred()) {
         (env)->ExceptionDescribe();
     }
     (jvm)->DestroyJavaVM();


	return 0;
}



