#include <stdlib.h>
#include "tcl.h"
#include <jni.h>

JDK1_1InitArgs vm_args;
JavaVM *vm;			/* Java virtual machine. */
JNIEnv *env;			/* Java run-time environment. */


/*
 *----------------------------------------------------------------------
 *
 * main --
 *
 *	This is the main program for the application.
 *
 * Results:
 *	None: Tcl_Main never returns here, so this procedure never
 *	returns either.
 *
 * Side effects:
 *	Whatever the application does.
 *
 *----------------------------------------------------------------------
 */

int
main(argc, argv)
    int argc;			/* Number of command-line arguments. */
    char **argv;		/* Values of command-line arguments. */
{
    jsize nVMs;
    char *path, *newPath;
    int oldSize, size;
    JDK1_1InitArgs vm_args;
    Tcl_Interp *interp;

    memset(&vm_args, 0, sizeof(vm_args));
    JNI_GetDefaultJavaVMInitArgs(&vm_args);
	path = getenv("CLASSPATH");
	if (path && vm_args.classpath) {
	    oldSize = strlen(path);
	    size = oldSize + strlen(vm_args.classpath);
	    newPath = ckalloc(size+2);
	    strcpy(newPath, path);
#ifdef __WIN32__
	    newPath[oldSize] = ';';
#else
	    newPath[oldSize] = ':';
#endif
	    strcpy(newPath+oldSize+1, vm_args.classpath);
	    vm_args.classpath = newPath;
	} else if (path) {
	    vm_args.classpath = path;
	}

    if (JNI_GetCreatedJavaVMs(&vm, 1, &nVMs) < 0) {
	printf("JNI_GetCreatedJavaVMs failed!\n");
	exit(1);
    }

    if (nVMs == 0) {
	if (JNI_CreateJavaVM(&vm, &env, &vm_args) < 0) {
	    printf("can't initialize Java VM\n");
	    exit(2);
	}
    } else {
	printf("got %d vms\n", nVMs);
    }

    Tcl_Main(argc, argv, Tcl_AppInit);
    return 0;			/* Needed only to prevent compiler warning. */
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_AppInit --
 *
 *	This procedure performs application-specific initialization.
 *	Most applications, especially those that incorporate additional
 *	packages, will have their own version of this procedure.
 *
 * Results:
 *	Returns a standard Tcl completion code, and leaves an error
 *	message in interp->result if an error occurs.
 *
 * Side effects:
 *	Depends on the startup script.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_AppInit(interp)
    Tcl_Interp *interp;		/* Interpreter for application. */
{
    if (Tcl_Init(interp) == TCL_ERROR) {
	return TCL_ERROR;
    }
    if (Java_Init(interp) == TCL_ERROR) {
	return TCL_ERROR;
    }
    return TCL_OK;
}

