#include <tk.h>
/*
 * XErrorProc --
 *		Toe-hold for debugging X Protocol botches.
 */
static int
XErrorProc(data, errEventPtr)
	ClientData data;
	XErrorEvent *errEventPtr;
{
	Tk_Window w = (Tk_Window)data;
	fprintf(stderr, "X protocol error: ");
	fprintf(stderr, "error=%d request=%d minor=%d\n",
		errEventPtr->error_code, errEventPtr->request_code,
		errEventPtr->minor_code);
	/*
	 * Claim to have handled the error.
	 */
	return 0;
}

Tk_Window mainWindow;

/*
 * A table for command line arguments.
 */
static char *display = NULL;
static int debug = 0;
static char *geometry = NULL;

Tk_ArgvInfo argTable[] = {
	{"-display", TK_ARGV_STRING, (char *) NULL,
	(char *) &display, "Display to use"},
	{"-debug", TK_ARGV_CONSTANT, (char *) 1, (char *) &debug,
		"Set things up for gdb-type debugging"},
	{"", TK_ARGV_END, },
};
/*
 * This program takes one argument, which is the
 * name of a script to interpret.
 */
main(int argc, char *argv[])
{
	Tcl_Interp *interp;
	int error; char *trace;

	interp = Tcl_CreateInterp();
	if (Tk_ParseArgv(interp, (Tk_Window) NULL, &argc, argv,
		argTable, 0) != TCL_OK) {
		fprintf(stderr, "%s\n", interp->result);
		exit(1);
	}
	if (argc < 2) {
		fprintf(stderr, "Usage: %s filename\n", argv[0]);
		exit(1);
	}

	/*
	 * Create the main window. The name of the application
	 * for use with the send command is "myapp". The
	 * class of the application for X resources is "Myapp".
	 */
	mainWindow = Tk_CreateMainWindow(interp, display,
		"myapp", "Myapp");
	if (mainWindow == NULL) {
		fprintf(stderr, "%s\n", interp->result);
		exit(1);
	}
	/*
	 * Register the X protocol error handler, and ask for
	 * a synchronous protocol to help debugging.
	 */
	Tk_CreateErrorHandler(Tk_Display(mainWindow), -1, -1, -1,
		XErrorProc, (ClientData)mainWindow);
	if (debug) {
		XSynchronize(Tk_Display(mainWindow), True);
	}
	/*
	 * Grab an initial size and background.
	 */
	Tk_GeometryRequest(mainWindow, 200, 200);
	Tk_SetWindowBackground(mainWindow,
		WhitePixelOfScreen(Tk_Screen(mainWindow)));

	/*
	 * This is where Tcl_AppInit would be called.
	 * In this case, we do the work right here.
	 */
	if (Tcl_Init(interp) != TCL_OK) {
		fprintf(stderr, "Tcl_Init failed: %s\n",
			 interp->result);
	}
	if (Tk_Init(interp) != TCL_OK) {
		fprintf(stderr, "Tk_Init failed: %s\n",
			 interp->result);
	}
	error = Tcl_EvalFile(interp, argv[1]);
	if (error != TCL_OK) {
		fprintf(stderr, "%s: %s\n", argv[1],
				interp->result);
		trace = Tcl_GetVar(interp, "errorInfo",
			 	TCL_GLOBAL_ONLY);
		if (trace != NULL) {
			fprintf(stderr, "*** TCL TRACE ***\n");
			fprintf(stderr, "%s\n", trace);
		}
	}
	/*
	 * Enter the custom event loop.
	 */
	while (MyappExists()) {
		Tk_DoOneEvent(TK_ALL_EVENTS);
		MyappStuff();
	}
	/*
	 * Call the Tcl exit to ensure that everything is
	 * cleaned up properly.
	 */
	Tcl_Eval(interp, "exit");
	return 0;
}

int
MyappExists()
{
	return 1;
}
int
MyappStuff()
{
	return 0;
}
