#ifdef _WIN32
#include <windows.h>
#include <process.h>
#endif

#include <stdio.h>
#include <string.h>
#include <errno.h>

#define PACKAGE "stec.ss."
#define JAVA "java"
#define SPACE " "
#define PATHSIZE 256
#define MSVM "jview"

void error(char *msg)
{
    fprintf(stderr, "%s\n", msg);
    exit(-1);
}

int main( int argc, char *argv[], char *envp[] )
{
    char *java_exe;
	char *classpath;
    char buf[2048];
	char **envarg;
	int rc;
	char *envfilenm;
	FILE *envFH;

#ifdef _WIN32
    char **args, **ap;

	boolean usingMSVM;
	char *p;
	int l;
	int lMSVM;
	int i;
#else
	char command[2048];
#endif

	// setup java
	java_exe = (char *)getenv("JAVA_EXE");
    if (java_exe == 0)
		error("JAVA_EXE is not defined");

#ifdef _WIN32
	// which java vm, microsoft/javasoft
	usingMSVM = FALSE;
	p = java_exe;
	lMSVM = strlen(MSVM);
	l = strlen(java_exe) - lMSVM + 1;
	for(i = 0; i < l; i++)
	{
		if(strnicmp(p, MSVM, lMSVM) == 0)
		{
			usingMSVM = TRUE;
			break;
		}

		p++;
	}

	// setup java executable
    ap = args = (char **)malloc((argc + 5) * sizeof(char *));
    *ap++ = strdup(java_exe);

	// setup args

	// setup classpath
	classpath = (char *)getenv("CLASSPATH");
    if (classpath == 0)
		error("CLASSPATH is not defined");

	if(!usingMSVM)
	{
	    sprintf(buf, "-classpath %s", classpath);
	    *ap++ = strdup(buf);
	}
#else
	// setup java executable
    strcpy(command, java_exe);

	// setup args

	// setup classpath
	classpath = (char *)getenv("CLASSPATH");
    if (classpath == 0)
		error("CLASSPATH is not defined");

    sprintf(buf, "-classpath %s", classpath);
    strcat(command, SPACE);
	strcat(command, buf);
#endif

	// setup env file
	envfilenm = (char *)tempnam(NULL, "~" CLASS);
	if(envfilenm == NULL)
		error( "Unable to create a temp filename" );

	envFH = fopen(envfilenm, "wb");

	// setup environmental variables
	
	envarg = envp;
	while(*envarg)
	{
		fprintf(envFH, "%s\n", *envarg++);
	}

	fflush(envFH);
	fclose(envFH);

#ifdef _WIN32
	if(usingMSVM)
		sprintf(buf, "/D:env=%s", envfilenm);
	else
		sprintf(buf, "-Denv=%s", envfilenm);

	*ap++ = strdup(buf);

	// setup CLASS executable
    *ap++ = strdup(PACKAGE CLASS);

	// setup user arguements
    while (--argc > 0)
		*ap++ = *++argv;

    *ap = 0;

	rc = spawnv(P_WAIT, args[0], args);
#else
	sprintf(buf, "-Denv=%s", envfilenm);
    strcat(command, SPACE);
	strcat(command, buf);

	// setup CLASS executable
    strcat(command, SPACE);
	strcat(command, PACKAGE CLASS);

	// setup user arguements
    while (--argc > 0)
	{
	    strcat(command, SPACE);
		strcat(command, *++argv);
	}

	rc = system(command);
#endif

	remove(envfilenm);
	free(envfilenm);

	if(rc != 0)
	{
		sprintf(buf, "errno: %d", errno);
		error(buf);
	}

	return rc;
}
