/*
 * @(#)xmlink.c
 *
 * Copyright 1994 - 2022  David A. Bagley, bagleyd AT verizon.net
 *
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of the author not be
 * used in advertising or publicity pertaining to distribution of the
 * software without specific, written prior permission.
 *
 * This program is distributed in the hope that it will be "useful",
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

/* Driver file for Mlink */

#ifndef WINVER
#include "version.h"
static const char aboutHelp[] = {
"Mlink Version " VERSION "\n"
"Send bugs (reports or fixes) to the author: "
"David Bagley <bagleyd AT verizon.net>\n"
"The latest version is at: "
"https://www.sillycycle.com/puzzles.html"
};

static const char synopsisHelp[] = {
"[-geometry [{width}][x{height}][{+-}{xoff}[{+-}{yoff}]]]\n"
"[-display [{host}]:[{vs}]] [-[no]mono] [-[no]{reverse|rv}]\n"
"[-{foreground|fg} {color}] [-{background|bg} {color}]\n"
"[-tile {color}] [-face{0|1|2|3|4|5|6|7} {color}]\n"
"[-{border|bd} {color}] [-[no]install]\n"
"[-picture {filename}] [-delay msecs] [-[no]sound]\n"
"[-bumpSound {filename}] [-moveSound {filename}]\n"
"[-{font|fn} {fontname}] [-tiles {int}] [-faces {int}]\n"
"[-[no]orient] [-[no]middle] [-base {int}]\n"
"[-userName {string}] [-scoreFile {filename}] [-scores]\n"
"[-version]"
};
#endif

#if defined(HAVE_MOTIF) || defined(WINVER)
static const char descriptionHelp[] = {
"Ideal's The Missing Link, a 4x4 puzzle, riding on the wave "
"of Rubik's Cube craze.  There are many variations on this\n"
"theme, including the \"6x6\" puzzle and Babylon Tower.  What "
"makes the Missing Link a harder puzzle to solve is that the\n"
"2 center positions rotate together."
};

static const char featuresHelp[] = {
"Press \"mouse-left\" button to move a tile. Release "
"\"mouse-left\" button in the same row would move the tile towards\n"
"the space (unless there is no space in that row).  "
"Release on a different row will move the tiles up or down.\n"
"\n"
"Click \"mouse-center\" button, or press \"P\" or \"p\" "
"keys, to toggle the practice mode (in practice mode the\n"
"record should say \"practice\").  This is good for learning "
"moves and experimenting.\n"
"\n"
"Click \"mouse-right\" button, or press \"Z\" or \"z\" "
"keys, to randomize the puzzle (this must be done first\n"
"to set a new record).\n"
"\n"
"Press \"G\" or \"g\" keys to read (get) a saved puzzle.\n"
"\n"
"Press \"W\" or \"w\" keys to save (write) a puzzle.\n"
"\n"
"Press \"U\" or \"u\" keys to undo a move.\n"
"\n"
"Press \"R\" or \"r\" keys to redo a move.\n"
"\n"
"Press \"C\" or \"c\" keys to clear the puzzle.\n"
"\n"
"\"S\" or \"s\" keys reserved for the auto-solver "
"(not implemented).\n"
"\n"
"Press \"O\" or \"o\" keys to toggle orient mode.  Slightly "
"more challenging on (default is off).\n"
"\n"
"Press \"M\" or \"m\" keys to toggle the middle mode.  All "
"the middle tiles rotate together.  This is considerably\n"
"more challenging on (default is on).\n"
"\n"
"Press \">\" or \".\" keys to speed up the movement of tiles.\n"
"\n"
"Press \"<\" or \",\" keys to slow down the movement of tiles.\n"
"\n"
"Press \"@\" key to toggle the sound.\n"
"\n"
"Press \"Esc\" key to hide program.\n"
"\n"
"Press \"Q\", \"q\", or \"CTRL-C\" keys to kill program.\n"
"\n"
"Use the key pad or arrow keys to move without the mouse.\n"
"Key pad is defined for Missing Link as:\n"
"  8    Up\n"
"  ^\n"
"4< >6  Left, Right\n"
"  v\n"
"  2    Down\n"
"\n"
"Use the shift key and the up or down arrow keys to rotate "
"all the tiles.\n"
"\n"
"Use the control key and the keypad or arrow keys to reduce "
"or enlarge the complexity of the puzzle."
};

static const char referencesHelp[] = {
"L. E. Horden, Sliding Piece Puzzles (Recreations in "
"Mathematics Series), Oxford University\n"
"Press 1986, Plate X.\n"
"you are about to find the solution: The Missing Link, "
"Ideal Toy Corporation, 1981."
};
#endif

static const char solveHelp[] = {
"Auto-solver: sorry, only implemented "
"for tiles = 4 and faces = 4."
};

#include "file.h"
#ifdef WINVER
#include "MlinkP.h"
#define TITLE "wmlink"

static MlinkRec widget;

#ifndef SCOREPATH
#ifdef UNIXDELIM
#define SCOREPATH "c:/WINDOWS"
#else
#define SCOREPATH "c:\\WINDOWS"
#endif
#endif
#define PRINT_MESSAGE(b) (void) MessageBox(widget.core.hWnd, (LPCSTR) b, "Warning", MB_OK);
#define SET_STARTED(w,b) w->mlink.started = b
#else
#include "xwin.h"
#include <X11/Shell.h>
#include <X11/cursorfont.h>
#ifdef HAVE_MOTIF
#include <Xm/PanedW.h>
#include <Xm/RowColumn.h>
#include <Xm/Label.h>
#include <Xm/LabelG.h>
#include <Xm/MessageB.h>
#include <Xm/PushBG.h>
#include <Xm/CascadeB.h>
#ifdef USE_SPIN
#include <Xm/SSpinB.h>
#else
#include <Xm/Scale.h>
#endif
#include <Xm/ToggleB.h>
#include <Xm/Text.h>
#include <Xm/Form.h>
#ifdef MOUSEBITMAPS
#include "pixmaps/mouse-l.xbm"
#include "pixmaps/mouse-r.xbm"
#endif
#elif defined(HAVE_XAW3D)
#include <X11/Xaw3d/Form.h>
#include <X11/Xaw3d/Label.h>
#include <X11/Xaw3d/Toggle.h>
#include <X11/Xaw3d/Box.h>
#include <X11/Xaw3d/Scrollbar.h>
#include <X11/Xaw3d/Command.h>
#include <X11/Xaw3d/Dialog.h>
#define HAVE_ATHENA 1
#elif defined(HAVE_ATHENA)
#include <X11/Xaw/Form.h>
#include <X11/Xaw/Label.h>
#include <X11/Xaw/Toggle.h>
#include <X11/Xaw/Box.h>
#include <X11/Xaw/Scrollbar.h>
#include <X11/Xaw/Command.h>
#include <X11/Xaw/Dialog.h>
#endif
#define SET_STARTED(w,b) XtVaSetValues(w, XtNstart, b, NULL)
#include "Mlink.h"
#ifdef HAVE_XPM
#include <X11/xpm.h>
#ifdef CONSTPIXMAPS
#include "16x16/mlink.xpm"
#include "22x22/mlink.xpm"
#include "24x24/mlink.xpm"
#include "32x32/mlink.xpm"
#include "48x48/mlink.xpm"
#include "64x64/mlink.xpm"
#else
#include "pixmaps/16x16/mlink.xpm"
#include "pixmaps/22x22/mlink.xpm"
#include "pixmaps/24x24/mlink.xpm"
#include "pixmaps/32x32/mlink.xpm"
#include "pixmaps/48x48/mlink.xpm"
#include "pixmaps/64x64/mlink.xpm"
#endif
#define RESIZE_XPM(s) ((char **) (((s)<=32)?\
(((s)<=22)?(((s)<=16)?mlink_16x16:mlink_22x22):\
(((s)<=24)?mlink_24x24:mlink_32x32)):\
(((s)<=48)?mlink_48x48:mlink_64x64)))
#endif
#include "pixmaps/64x64/mlink.xbm"
#define DEFINE_XBM (char *) mlink_64x64_bits, mlink_64x64_width, mlink_64x64_height
#ifndef SCOREPATH
#ifdef VMS
#define SCOREPATH "SYS$LOGIN:"
#else
#define SCOREPATH "/var/games/xpuzzles"
#endif
#endif
#endif

#ifndef SCOREFILE
#define SCOREFILE "mlink.scores"
#endif

#define MAX_TILES 8
#define NEVER (-1)
#define FILE_NAME_LENGTH 1024
#define TITLE_FILE_LENGTH (FILE_NAME_LENGTH+8)
#define USER_NAME_LENGTH 120
#define MESSAGE_LENGTH (USER_NAME_LENGTH+64)
#define TITLE_LENGTH 2048
#define NOACCESS "noaccess"
#define NOBODY "nobody"

typedef struct {
	int score;
	char name[USER_NAME_LENGTH];
} PuzzleRecord;

static PuzzleRecord puzzleRecord[2][2]
[MAX_FACES - MIN_FACES + 1][MAX_TILES - MIN_TILES + 1];
static int movesDsp = 0;
static char messageDsp[MESSAGE_LENGTH] =
	"Welcome                        ";
static char recordDsp[MESSAGE_LENGTH] = "NOT RECORDED";

#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
static Widget movesText, recordText, message;
static Widget tileChanger, faceChanger, speedChanger;
static Widget orientizeSwitch, middleSwitch, practiceSwitch;
static Widget practiceDialog, randomizeDialog, solveDialog;
static char buff[MESSAGE_LENGTH];
#define PRINT_MESSAGE(b) printState(message, b)
#define MIN_SPEED 1
#define MAX_SPEED 50
#elif !defined(WINVER)
#define PRINT_MESSAGE(b) XtWarning(b)
#endif
#ifdef HAVE_MOTIF
#define SCROLL_SIZE 30 /* A page */
static Widget descriptionDialog, featuresDialog;
static Widget synopsisDialog, referencesDialog, aboutDialog;
static Arg args[10];
#elif defined(HAVE_ATHENA)
#define SCROLL_SIZE 100
static Widget tileSliderLabel, faceSliderLabel, speedSliderLabel;
static Widget practiceOKDialog, practiceCancelDialog;
static Widget randomizeOKDialog, randomizeCancelDialog;
static Widget solveOKDialog;
#else
static char titleDsp[TITLE_LENGTH] = "";
#endif
static char scoreFileName[FILE_NAME_LENGTH] = SCOREFILE;
static char fileName[FILE_NAME_LENGTH];
#ifdef WINVER
#define PROGRAM_NAME_LENGTH 80
static char progDsp[PROGRAM_NAME_LENGTH] = TITLE;
static char userNameDsp[USER_NAME_LENGTH] = "guest";
#else
static Pixmap pixmap = None;
static Widget topLevel, puzzle;
static char *progDsp;
static char userNameDsp[USER_NAME_LENGTH] = "";

#ifdef HAVE_MOTIF
static void
printState(Widget w, char *msg)
{
	XmString xmstr;

	if (!XtIsSubclass(w, xmLabelWidgetClass))
		XtError("printState() requires a Label Widget");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	XtVaSetValues(w, XmNlabelString, xmstr, NULL);
	XmStringFree(xmstr);
}
#elif defined(HAVE_ATHENA)
static void
printState(Widget w, char *msg)
{
	XtVaSetValues(w,
		XtNlabel, msg, NULL);
	if (w == movesText)
		XtVaSetValues(w,
			XtNwidth, 64, NULL);
}
#endif

static void
printRecords(void)
{
	int i, j, k, l;

	(void) printf("                    MLINK  HALL OF FAME\n\n");
	(void) printf("MIDDLE ORIENT FACE TILE USER            MOVES\n");
	for (l = 0; l < 2; l++)
		for (k = 0; k < 2; k++)
			for (j = 0; j < MAX_FACES - MIN_FACES + 1; j++)
				for (i = 0; i < MAX_TILES - MIN_TILES + 1; i++) {
					if (puzzleRecord[l][k][j][i].score > 0)
						(void) printf("%6d%7d%5d%5d %-12s%9d\n",
							l, k, j + 1, i + 1,
							puzzleRecord[l][k][j][i].name,
							puzzleRecord[l][k][j][i].score);
				}
}
#endif

static void
initRecords(void)
{
	int i, j, k, l;

	for (l = 0; l < 2; l++)
		for (k = 0; k < 2; k++)
			for (j = 0; j < MAX_FACES - MIN_FACES + 1; j++)
				for (i = 0; i < MAX_TILES - MIN_TILES + 1; i++) {
					puzzleRecord[l][k][j][i].score = NEVER;
					(void) strncpy(puzzleRecord[l][k][j][i].name,
						NOACCESS, USER_NAME_LENGTH);
				}
}

static void
readRecords(void)
{
	FILE *fp;
	int i, j, k, l, n;
	char userName[USER_NAME_LENGTH];
	char *buf1 = NULL, *buf2 = NULL;
	char *fname, *lname;

	stringCat(&buf1, CURRENTDELIM, scoreFileName);
	lname = buf1;
	stringCat(&buf1, SCOREPATH, FINALDELIM);
	stringCat(&buf2, buf1, SCOREFILE);
	free(buf1);
	fname = buf2;
	(void) strncpy(fileName, lname, USER_NAME_LENGTH);
	if ((fp = fopen(fileName, "r")) == NULL) {
		(void) strncpy(fileName, fname, USER_NAME_LENGTH);
		/* Try installed directory. */
		if ((fp = fopen(fileName, "r")) == NULL) {
			stringCat(&buf1, "Cannot read ", fname);
			stringCat(&buf2, buf1, " or ");
			free(buf1);
			stringCat(&buf1, buf2, lname);
			free(buf2);
			PRINT_MESSAGE(buf1);
			free(buf1);
			free(lname);
			free(fname);
			return;
		}
/* Probably annoying */
#if 0
		else {
			stringCat(&buf1, "Cannot read ", fname);
			stringCat(&buf2, buf1, ", falling back to ");
			free(buf1);
			stringCat(&buf1, buf2, lname);
			free(buf2);
			PRINT_MESSAGE(buf1);
			free(buf1);
		}
#endif
	}
	free(lname);
	free(fname);
	for (l = 0; l < 2; l++)
		for (k = 0; k < 2; k++)
			for (j = 0; j < MAX_FACES - MIN_FACES + 1; j++)
				for (i = 0; i < MAX_TILES - MIN_TILES + 1; i++) {
					if (fscanf(fp, "%d %s\n", &n, userName) != 2) {
						(void) fprintf(stderr,
							"corrupt record, expecting integer and name for %d %d %d %d\n",
							l, k, j, i);
						(void) fclose(fp);
						return;
					}
					if (n <= puzzleRecord[l][k][j][i].score ||
							puzzleRecord[l][k][j][i].score <= NEVER) {
						puzzleRecord[l][k][j][i].score = n;
						(void) strncpy(puzzleRecord[l][k][j][i].name,
							userName, USER_NAME_LENGTH);
					}
				}
	(void) fclose(fp);
}

static void
writeRecords(void)
{
	FILE *fp;
	int i, j, k, l;
	char *buf1 = NULL;

	if ((fp = fopen(fileName, "w")) == NULL) {
		stringCat(&buf1, "Cannot write to ", fileName);
		PRINT_MESSAGE(buf1);
		free(buf1);
		return;
	}
	{
#if HAVE_FCNTL_H
		int lfd;
		char lockFile[FILE_NAME_LENGTH];

		(void) strncpy(lockFile, fileName, FILE_NAME_LENGTH - 6);
		lockFile[FILE_NAME_LENGTH - 6] = '\0';
		(void) strncat(lockFile, ".lock", 6);
		while (((lfd = open(lockFile, O_CREAT | O_EXCL, 0644)) < 0) &&
				errno == EEXIST)
			(void) sleep(1);
		if (lfd < 0) {
#if 1
			(void) fprintf(stderr,
				"Lock file exists... guessing its an old one.\n");
#else
			(void) fprintf(stderr,
				"Lock file exists... score not recorded - sorry.\n");
			return;
#endif
		}
#endif
		for (l = 0; l < 2; l++) {
			for (k = 0; k < 2; k++) {
				for (j = 0; j < MAX_FACES - MIN_FACES + 1; j++) {
					for (i = 0; i < MAX_TILES - MIN_TILES + 1; i++)
						(void) fprintf(fp, "%d %s\n",
							puzzleRecord[l][k][j][i].score, puzzleRecord[l][k][j][i].name);
					if (j < MAX_TILES - MIN_TILES ||
							k < 1 || l < 1)
						(void) fprintf(fp, "\n");
				}
				if (k < 1 || l < 1)
					(void) fprintf(fp, "\n");
			}
			if (l < 1)
				(void) fprintf(fp, "\n");
		}
#if HAVE_FCNTL_H
		(void) close(lfd);
		(void) unlink(lockFile);
#endif
		(void) fclose(fp);
	}
}

static void
printRecord(int tiles, int faces, Boolean orient, Boolean middle,
		Boolean practice)
{
	int i = tiles - MIN_TILES, j = faces - MIN_FACES;
	int k = (orient) ? 1 : 0, l = (middle) ? 1 : 0;

	if (practice) {
		(void) strncpy(recordDsp, "practice", 9);
	} else if (tiles > MAX_TILES) {
		(void) strncpy(recordDsp, "NOT RECORDED", 13);
	} else if (puzzleRecord[l][k][j][i].score <= NEVER) {
		(void) strncpy(recordDsp, "NEVER ", 7);
		(void) strncat(recordDsp, NOACCESS, strlen(NOACCESS) + 1);
	} else {
#ifdef HAVE_SNPRINTF
		(void) snprintf(recordDsp, MESSAGE_LENGTH, "%d %s",
			puzzleRecord[l][k][j][i].score,
			puzzleRecord[l][k][j][i].name);
#else
		(void) sprintf(recordDsp, "%d %s",
			puzzleRecord[l][k][j][i].score,
			puzzleRecord[l][k][j][i].name);
#endif
	}
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	printState(recordText, recordDsp);
#endif
}

static void
printStatus(char *msg, int nMoves
#if !defined(HAVE_MOTIF) && !defined(HAVE_ATHENA)
		, int tiles, int faces, Boolean middle
#endif
		)
{
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	printState(message, msg);
	intCpy(buff, nMoves);
	printState(movesText, buff);
#else
	if (middle)
#ifdef HAVE_SNPRINTF
		(void) snprintf(titleDsp, TITLE_LENGTH,
			"%s: %dx%d norm@ (%d/%s) - %s",
			progDsp, tiles, faces, nMoves, recordDsp, msg);
#else
		(void) sprintf(titleDsp,
			"%s: %dx%d norm@ (%d/%s) - %s",
			progDsp, tiles, faces, nMoves, recordDsp, msg);
#endif
	else
#ifdef HAVE_SNPRINTF
		(void) snprintf(titleDsp, TITLE_LENGTH,
			"%s: %dx%d ind@ (%d/%s) - %s",
			progDsp, tiles, faces, nMoves, recordDsp, msg);
#else
		(void) sprintf(titleDsp,
			"%s: %dx%d ind@ (%d/%s) - %s",
			progDsp, tiles, faces, nMoves, recordDsp, msg);
#endif
#ifdef WINVER
	SetWindowText(widget.core.hWnd, (LPSTR) titleDsp);
#else
	XtVaSetValues(XtParent(puzzle), XtNtitle, titleDsp, NULL);
#endif
#endif
}

static Boolean
handleSolved(int counter, int tiles, int faces, Boolean orient, Boolean middle)
{
	int i = tiles - MIN_TILES, j = faces - MIN_FACES;
	int k = (orient) ? 1 : 0, l = (middle) ? 1 : 0;

	if (tiles <= MAX_TILES && (counter < puzzleRecord[l][k][j][i].score ||
			puzzleRecord[l][k][j][i].score <= NEVER)) {
		readRecords();	/* Maybe its been updated by another */
		puzzleRecord[l][k][j][i].score = counter;
		(void) strncpy(puzzleRecord[l][k][j][i].name, userNameDsp,
			USER_NAME_LENGTH);
		if (tiles < 4 || faces < 2) {
			puzzleRecord[!l][k][j][i].score = counter;
			(void) strncpy(puzzleRecord[!l][k][j][i].name,
				userNameDsp, USER_NAME_LENGTH);
		}
		writeRecords();
		printRecord(tiles, faces, orient, middle, False);
		return True;
	}
	return False;
}

#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
static void
orientToggle(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
		XmToggleButtonCallbackStruct *cbs
#elif defined(HAVE_ATHENA)
		int state
#endif
		)
{
	int tiles, faces;
	Boolean orient, middle, practice, old;
	char *picture;

#ifdef HAVE_MOTIF
	orient = cbs->set;
#elif defined(HAVE_ATHENA)
	orient = state;
#endif
	XtVaGetValues(puzzle,
		XtNtiles, &tiles,
		XtNfaces, &faces,
		XtNorient, &old,
		XtNmiddle, &middle,
		XtNpicture, &picture,
		XtNpractice, &practice, NULL);
	if (old == orient)
		return;
	if (!orient && picture && *picture) {
#ifdef HAVE_MOTIF
		XmToggleButtonSetState(orientizeSwitch, old, True);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(orientizeSwitch,
			XtNstate, old, NULL);
#endif
		return;
	}
	XtVaSetValues(puzzle,
		XtNorient, orient, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(tiles, faces, orient, middle, practice);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}

static void
middleToggle(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
		XmToggleButtonCallbackStruct *cbs
#elif defined(HAVE_ATHENA)
		int state
#endif
		)
{
	int tiles, faces;
	Boolean orient, middle, practice, old;

#ifdef HAVE_MOTIF
	middle = cbs->set;
#elif defined(HAVE_ATHENA)
	middle = state;
#endif
	XtVaGetValues(puzzle,
		XtNtiles, &tiles,
		XtNfaces, &faces,
		XtNorient, &orient,
		XtNmiddle, &old,
		XtNpractice, &practice, NULL);
	if (old == middle)
		return;
	XtVaSetValues(puzzle,
		XtNmiddle, middle, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(tiles, faces, orient, middle, practice);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}

static void
practiceToggle(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
		XmToggleButtonCallbackStruct *cbs
#elif defined(HAVE_ATHENA)
		int state
#endif
		)
{
	int tiles, faces;
	Boolean orient, middle, practice, old;

#ifdef HAVE_MOTIF
	practice = cbs->set;
#elif defined(HAVE_ATHENA)
	practice = state;
#endif
	XtVaGetValues(puzzle,
		XtNtiles, &tiles,
		XtNfaces, &faces,
		XtNorient, &orient,
		XtNmiddle, &middle,
		XtNpractice, &old, NULL);
	if (old == practice)
		return;
	XtVaSetValues(puzzle,
		XtNpractice, practice,
		XtNstart, False, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(tiles, faces, orient, middle, practice);
	if (practice)
		messageDsp[0] = '\0';
	else
		(void) strncpy(messageDsp, "Randomize (z) to start",
			MESSAGE_LENGTH);
	printState(message, messageDsp);
}

static void
tileChangeListener(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XmSpinBoxCallbackStruct *cbs
#else
		XmScaleCallbackStruct *cbs
#endif
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
	int tiles, faces, old;
	Boolean orient, middle, practice;

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	int limit;
	tiles = cbs->position;
#else
	tiles = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	long position = (size_t) callData; /* left or right button */
	tiles = ABS(position) *
		(MAX_TILES - MIN_TILES) / SCROLL_SIZE + 1;
	if (tiles < MIN_TILES || tiles > MAX_TILES) {
		/* middle button */
		tiles = (int) (*((float *) callData) *
			(MAX_TILES - MIN_TILES)) + MIN_TILES;
		if (tiles < MIN_TILES || tiles > MAX_TILES)
			return;
	}
#endif

	XtVaGetValues(puzzle,
		XtNtiles, &old,
		XtNfaces, &faces,
		XtNorient, &orient,
		XtNmiddle, &middle,
		XtNpractice, &practice, NULL);
	if (old == tiles)
		return;
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	XtVaGetValues(tileChanger,
		XmNmaximumValue, &limit, NULL);
	if (tiles >= limit)
		XtVaSetValues(tileChanger,
			XmNmaximumValue, tiles + 1,
			XmNposition, tiles, NULL);
#elif defined(HAVE_ATHENA)
	(void) sprintf(buff, "Tiles: %d", tiles);
	XtVaSetValues(label,
		XtNlabel, buff, NULL);
#endif
	XtVaSetValues(puzzle,
		XtNtiles, tiles, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(tiles, faces, orient, middle, practice);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}

static void
faceChangeListener(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XmSpinBoxCallbackStruct *cbs
#else
		XmScaleCallbackStruct *cbs
#endif
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
	int tiles, faces, old;
	Boolean orient, middle, practice;

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	faces = cbs->position;
#else
	faces = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	long position = (size_t) callData; /* left or right button */
	faces = ABS(position) *
		(MAX_FACES - MIN_FACES) / SCROLL_SIZE + 1;
	if (faces < MIN_FACES || faces > MAX_FACES) {
		/* middle button */
		faces = (int) (*((float *) callData) *
			(MAX_FACES - MIN_FACES)) + MIN_FACES;
		if (faces < MIN_FACES || faces > MAX_FACES)
			return;
	}
#endif
	XtVaGetValues(puzzle,
		XtNtiles, &tiles,
		XtNfaces, &old,
		XtNorient, &orient,
		XtNmiddle, &middle,
		XtNpractice, &practice, NULL);
	if (old == faces)
		return;
#ifdef HAVE_ATHENA
	(void) sprintf(buff, "Faces: %d", faces);
	XtVaSetValues(label,
		XtNlabel, buff, NULL);
#endif
	XtVaSetValues(puzzle,
		XtNfaces, faces, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(tiles, faces, orient, middle, practice);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}

static void
speedChangeListener(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XmSpinBoxCallbackStruct *cbs
#else
		XmScaleCallbackStruct *cbs
#endif
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
	int speed, delay, old;

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	speed = cbs->position;
#else
	speed = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	long position = (size_t) callData; /* left or right button */
	speed = ABS(position) *
		(MAX_SPEED - MIN_SPEED) / SCROLL_SIZE + 1;
	if (speed < MIN_SPEED || speed > MAX_SPEED) {
		/* middle button */
		speed = (int) (*((float *) callData) *
			(MAX_SPEED - MIN_SPEED)) + MIN_SPEED;
		if (speed < MIN_SPEED || speed > MAX_SPEED)
			return;
	}
	(void) sprintf(buff, "Animation Speed: %d", speed);
	XtVaSetValues(label,
		XtNlabel, buff, NULL);
#endif
	delay = MAX_SPEED + MIN_SPEED - speed - 1;
	XtVaGetValues(puzzle,
		XtNdelay, &old, NULL);
	if (old != delay) {
		XtVaSetValues(puzzle,
			XtNdelay, delay, NULL);
	}
}

static void
puzzlePracticeListener(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
		XmAnyCallbackStruct *cbs
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
#ifdef HAVE_MOTIF
	if (cbs->reason == XmCR_OK)
#elif defined(HAVE_ATHENA)
	XtUnmanageChild(practiceDialog);
#endif
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_PRACTICE, NULL);
}

static void
puzzleRandomizeListener(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
		XmAnyCallbackStruct *cbs
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
#ifdef HAVE_MOTIF
	if (cbs->reason == XmCR_OK)
#elif defined(HAVE_ATHENA)
	XtUnmanageChild(randomizeDialog);
#endif
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_RANDOMIZE, NULL);
}
#endif

static void
initialize(
#ifdef WINVER
MlinkWidget w, HBRUSH brush
#else
Widget w
#endif
)
{
	int tiles, faces;
	Boolean orient, middle, practice;
	char *userName, *scoreFile;

#ifdef WINVER
	initializePuzzle(w, brush);

	tiles = w->mlink.tiles;
	faces = w->mlink.faces;
	orient = w->mlink.orient;
	middle = w->mlink.middle;
	practice = w->mlink.practice;
	userName = w->mlink.userName;
	scoreFile = w->mlink.scoreFile;
	if (strcmp(scoreFile, "")) {
		(void) strncpy(scoreFileName, scoreFile, FILE_NAME_LENGTH - 1);
		scoreFileName[FILE_NAME_LENGTH - 1] = '\0';
	}
#else
	Boolean scoreOnly, versionOnly;

	XtVaGetValues(w,
		XtNuserName, &userName,
		XtNscoreFile, &scoreFile,
		XtNtiles, &tiles,
		XtNfaces, &faces,
		XtNorient, &orient,
		XtNmiddle, &middle,
		XtNpractice, &practice,
		XtNscoreOnly, &scoreOnly,
		XtNversionOnly, &versionOnly, NULL);
	if (versionOnly) {
		(void) printf("%s\n", aboutHelp);
		exit(0);
	}
	if (strcmp(scoreFile, "")) {
		(void) strncpy(scoreFileName, scoreFile, FILE_NAME_LENGTH - 1);
		scoreFileName[FILE_NAME_LENGTH - 1] = '\0';
	}
	if (scoreOnly) {
		initRecords();
		readRecords();
		printRecords();
		exit(0);
	}
#ifdef HAVE_MOTIF
	{
		int delay, speed;

#ifdef USE_SPIN
		int limit;
		XtVaGetValues(tileChanger,
			XmNmaximumValue, &limit, NULL);
		if (tiles >= limit)
			XtVaSetValues(tileChanger,
				XmNposition, tiles,
				XmNmaximumValue, tiles + 1, NULL);
		else
			XtVaSetValues(tileChanger,
				XmNposition, tiles, NULL);
		XtVaSetValues(faceChanger, XmNposition, faces, NULL);
#else
		if (tiles > MAX_TILES)
			XtVaSetValues(tileChanger,
				XmNmaximum, tiles, NULL);
		XmScaleSetValue(tileChanger, tiles);
		XmScaleSetValue(faceChanger, faces);
#endif
		XmToggleButtonSetState(orientizeSwitch, orient, True);
		XmToggleButtonSetState(middleSwitch, middle, True);
		XmToggleButtonSetState(practiceSwitch, practice, True);
		XtVaGetValues(w, XtNdelay, &delay, NULL);
		speed = MAX_SPEED + MIN_SPEED - delay - 1;
#ifdef USE_SPIN
		XtVaSetValues(speedChanger,
			XmNposition, speed, NULL);
#else
		XmScaleSetValue(speedChanger, speed);
#endif
	}
#endif
#endif
	SET_STARTED(w, False);
	initRecords();
	readRecords();
#ifndef WINVER
	(void) strncpy(userNameDsp, userName, USER_NAME_LENGTH - 1);
	userNameDsp[USER_NAME_LENGTH - 1] = '\0';
#endif
	if (!strcmp(userName, "") || !strcmp(userName, "(null)") ||
			!strcmp(userName, NOACCESS) ||
			!strcmp(userName, NOBODY)) {
#ifdef WINVER
		(void) strncpy(userNameDsp, userName, USER_NAME_LENGTH - 1);
		userNameDsp[USER_NAME_LENGTH - 1] = '\0';
#else
		char *login;

#ifdef HAVE_CUSERID
		login = cuserid(NULL);
#else
		login = getlogin();
#endif
		if (login == NULL) {
			userNameDsp[0] = '\0';
		} else {
			(void) strncpy(userNameDsp, login, USER_NAME_LENGTH - 1);
			userNameDsp[USER_NAME_LENGTH - 1] = '\0';
		}
		if (!strcmp(userNameDsp, "") ||
				!strcmp(userNameDsp, "(null)") ||
				!strcmp(userNameDsp, NOACCESS) ||
				!strcmp(userNameDsp, NOBODY))
			/* It really IS nobody */
			(void) strncpy(userNameDsp, "guest", 6);
#endif
	}
	printRecord(tiles, faces, orient, middle, practice);
	printStatus(messageDsp, movesDsp
#if !defined(HAVE_MOTIF) && !defined(HAVE_ATHENA)
		, tiles, faces, middle
#endif
		);
}

#ifdef WINVER
void
setPuzzle(MlinkWidget w, int reason)
#else
static void
puzzleListener(Widget w, caddr_t clientData,
		mlinkCallbackStruct *callData)
#endif
{
#ifndef WINVER
	int reason = callData->reason;
#endif
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	int limit;
#endif
	int tiles, faces;
	Boolean orient, middle, practice, cheat;

	messageDsp[0] = '\0';
#ifdef WINVER
	tiles = w->mlink.tiles;
	faces = w->mlink.faces;
	orient = w->mlink.orient;
	middle = w->mlink.middle;
	practice = w->mlink.practice;
	cheat = w->mlink.cheat;
#else
	XtVaGetValues(w,
		XtNtiles, &tiles,
		XtNfaces, &faces,
		XtNorient, &orient,
		XtNmiddle, &middle,
		XtNpractice, &practice,
		XtNcheat, &cheat, NULL);
#endif
	switch (reason) {
	case ACTION_HIDE:
#ifdef WINVER
		ShowWindow(w->core.hWnd, SW_SHOWMINIMIZED);
#else
		(void) XIconifyWindow(XtDisplay(topLevel),
			XtWindow(topLevel),
			XScreenNumberOfScreen(XtScreen(topLevel)));
#endif
		break;
#ifndef WINVER
	case ACTION_PRACTICE_QUERY:
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
		XtManageChild(practiceDialog);
#else
		XtVaSetValues(puzzle, XtNmenu, ACTION_PRACTICE, NULL);
#endif
		break;
	case ACTION_RANDOMIZE_QUERY:
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
		XtManageChild(randomizeDialog);
#else
		XtVaSetValues(puzzle, XtNmenu, ACTION_RANDOMIZE, NULL);
#endif
		break;
#endif
	case ACTION_SOLVE_MESSAGE:
#ifdef WINVER
		(void) MessageBox(w->core.hWnd, solveHelp,
			"Auto-solve", MB_OK);
#else
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
		XtManageChild(solveDialog);
#else
		(void) strncpy(messageDsp, solveHelp, MESSAGE_LENGTH);
#endif
#endif
		break;
	case ACTION_RESTORE:
		if (practice) {
			(void) strncpy(recordDsp, "practice",
				MESSAGE_LENGTH);
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
			printState(recordText, recordDsp);
#endif
		}
		movesDsp = 0;
		break;
	case ACTION_RESET:
		movesDsp = 0;
		break;
	case ACTION_BLOCKED:
		(void) strncpy(messageDsp, "Blocked", MESSAGE_LENGTH);
		break;
	case ACTION_SPACE:
#if 0
		/* Too annoying */
		(void) strncpy(messageDsp, "A space cannot slide",
			MESSAGE_LENGTH);
#endif
		break;
	case ACTION_IGNORE:
		(void) strncpy(messageDsp, "Randomize (z) to start",
			MESSAGE_LENGTH);
		break;
	case ACTION_MOVED:
		movesDsp++;
		SET_STARTED(w, True);
		break;
	case ACTION_CONTROL:
		return;
	case ACTION_SOLVED:
		if (practice) {
			movesDsp = 0;
		} else if (cheat) {
			(void) strncpy(messageDsp, "No cheating ", 13);
			(void) strncat(messageDsp, userNameDsp, USER_NAME_LENGTH);
			(void) strncat(messageDsp, "!!", 3);
		} else if (handleSolved(movesDsp, tiles, faces,
				orient, middle)) {
			(void) strncpy(messageDsp, "Congratulations ", 17);
			(void) strncat(messageDsp, userNameDsp, USER_NAME_LENGTH);
			(void) strncat(messageDsp, "!!", 3);
		} else {
			(void) strncpy(messageDsp, "Solved!", 8);
		}
		SET_STARTED(w, False);
		break;
	case ACTION_COMPUTED:
		SET_STARTED(w, False);
		break;
	case ACTION_PRACTICE:
		movesDsp = 0;
		practice = !practice;
		if (!practice)
			(void) strncpy(messageDsp, "Randomize (z) to start",
				MESSAGE_LENGTH);
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.practice = practice;
		w->mlink.started = False;
#else
		XtVaSetValues(w,
			XtNpractice, practice,
			XtNstart, False, NULL);
#ifdef HAVE_MOTIF
		XmToggleButtonSetState(practiceSwitch, practice, True);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(practiceSwitch, XtNstate, practice, NULL);
#endif
#endif
		break;
	case ACTION_RANDOMIZE:
		movesDsp = 0;
#ifdef WINVER
		w->mlink.practice = False;
		w->mlink.started = False;
#else
		XtVaSetValues(w,
			XtNpractice, False,
			XtNstart, False, NULL);
#endif
		break;
	case ACTION_ORIENTIZE:
		movesDsp = 0;
		orient = !orient;
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.orient = orient;
#else
		XtVaSetValues(w, XtNorient, orient, NULL);
#ifdef HAVE_MOTIF
		XmToggleButtonSetState(orientizeSwitch, orient, True);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(orientizeSwitch, XtNstate, orient, NULL);
#endif
#endif
		break;
	case ACTION_MIDDLE:
		movesDsp = 0;
		middle = !middle;
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.middle = middle;
#else
		XtVaSetValues(w, XtNmiddle, middle, NULL);
#ifdef HAVE_MOTIF
		XmToggleButtonSetState(middleSwitch, middle, True);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(middleSwitch, XtNstate, middle, NULL);
#endif
#endif
		break;
	case ACTION_INCX:
		movesDsp = 0;
		tiles++;
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.tiles = tiles;
#else
		XtVaSetValues(w, XtNtiles, tiles, NULL);
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XtVaGetValues(tileChanger,
			XmNmaximumValue, &limit, NULL);
		if (tiles >= limit)
			XtVaSetValues(tileChanger,
				XmNmaximumValue, tiles + 1,
				XmNposition, tiles, NULL);
		else
			XtVaSetValues(tileChanger,
				XmNposition, tiles, NULL);
#else
		if (tiles > MAX_TILES)
			XtVaSetValues(tileChanger,
				XmNmaximum, tiles, NULL);
		XmScaleSetValue(tileChanger, tiles);
#endif
#elif defined(HAVE_ATHENA)
		(void) sprintf(buff, "Tiles: %d", tiles);
		XtVaSetValues(tileSliderLabel,
			XtNlabel, buff, NULL);
#endif
#endif
		break;
	case ACTION_DECX:
		movesDsp = 0;
		tiles--;
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.tiles = tiles;
#else
		XtVaSetValues(w, XtNtiles, tiles, NULL);
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		if (tiles > MAX_TILES)
			XtVaSetValues(tileChanger,
				XmNmaximumValue, tiles,
				XmNposition, tiles, NULL);
		else
			XtVaSetValues(tileChanger,
				XmNposition, tiles, NULL);
#else
		if (tiles > MAX_TILES)
			XtVaSetValues(tileChanger,
				XmNmaximum, tiles, NULL);
		XmScaleSetValue(tileChanger, tiles);
#endif
#elif defined(HAVE_ATHENA)
		(void) sprintf(buff, "Tiles: %d", tiles);
		XtVaSetValues(tileSliderLabel,
			XtNlabel, buff, NULL);
#endif
#endif
		break;
	case ACTION_INCY:
		movesDsp = 0;
		faces++;
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.faces = faces;
#else
		XtVaSetValues(w, XtNfaces, faces, NULL);
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XtVaSetValues(faceChanger, XmNposition, faces, NULL);
#else
		XmScaleSetValue(faceChanger, faces);
#endif
#elif defined(HAVE_ATHENA)
		(void) sprintf(buff, "Faces: %d", faces);
		XtVaSetValues(faceSliderLabel,
			XtNlabel, buff, NULL);
#endif
#endif
		break;
	case ACTION_DECY:
		movesDsp = 0;
		faces--;
		printRecord(tiles, faces, orient, middle, practice);
#ifdef WINVER
		w->mlink.faces = faces;
#else
		XtVaSetValues(w, XtNfaces, faces, NULL);
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XtVaSetValues(faceChanger, XmNposition, faces, NULL);
#else
		XmScaleSetValue(faceChanger, faces);
#endif
#elif defined(HAVE_ATHENA)
		(void) sprintf(buff, "Faces: %d", faces);
		XtVaSetValues(faceSliderLabel,
			XtNlabel, buff, NULL);
#endif
#endif
		break;
	case ACTION_UNDO:
		movesDsp--;
		SET_STARTED(w, True);
		break;
	case ACTION_REDO:
		movesDsp++;
		SET_STARTED(w, True);
		break;
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	case ACTION_SPEED:
		{
			int oldDelay, delay, speed;

			XtVaGetValues(puzzle,
				XtNdelay, &delay, NULL);
			oldDelay = delay;
			if (delay > MAX_SPEED - MIN_SPEED)
				delay = MAX_SPEED - MIN_SPEED;
			if (delay < 0)
				delay = 0;
			if (delay != oldDelay) {
				XtVaSetValues(w,
					XtNdelay, delay, NULL);
			}
			speed = MAX_SPEED + MIN_SPEED - delay - 1;
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
			XtVaSetValues(speedChanger,
				XmNposition, speed, NULL);
#else
			XmScaleSetValue(speedChanger, speed);
#endif
#elif defined(HAVE_ATHENA)
			(void) sprintf(buff, "Animation Speed: %d", speed);
			XtVaSetValues(speedSliderLabel,
				XtNlabel, buff, NULL);
#endif
		}
		return;
#endif
	}
	printStatus(messageDsp, movesDsp
#if !defined(HAVE_MOTIF) && !defined(HAVE_ATHENA)
		, tiles, faces, middle
#endif
		);
}

#ifdef WINVER
static LRESULT CALLBACK
about(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	if (message == WM_COMMAND && LOWORD(wParam) == IDOK) {
		(void) EndDialog(hDlg, TRUE);
		return TRUE;
	}
	return FALSE;
}

static LRESULT CALLBACK
WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HBRUSH brush = (HBRUSH) NULL;
	PAINTSTRUCT paint;
	static Boolean mousePressed = False;

	widget.core.hWnd = hWnd;
	if (GetFocus()) {
		if (!widget.mlink.focus) {
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_BRUSH));
			enterPuzzle(&widget);
			(void) EndPaint(hWnd, &paint);
		}
	} else {
		if (widget.mlink.focus) {
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_BRUSH));
			leavePuzzle(&widget);
			(void) EndPaint(hWnd, &paint);
		}
	}
	switch (message) {
	case WM_CREATE:
		initialize(&widget, brush);
		break;
	case WM_DESTROY:
		destroyPuzzle(&widget, brush);
		break;
	case WM_SIZE:
		resizePuzzle(&widget);
		(void) InvalidateRect(hWnd, NULL, TRUE);
		break;
	case WM_PAINT:
		widget.core.hDC = BeginPaint(hWnd, &paint);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		exposePuzzle(&widget);
		(void) EndPaint(hWnd, &paint);
		break;
	case WM_RBUTTONDOWN:
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		randomizePuzzle(&widget);
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
	case WM_LBUTTONDOWN:
		mousePressed = True;
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		selectPuzzle(&widget, LOWORD(lParam), HIWORD(lParam),
			((GetKeyState(VK_SHIFT) >> 1) ||
			(GetKeyState(VK_CAPITAL) & 1)));
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
	case WM_MOUSEMOVE:
		if (!(wParam & MK_LBUTTON)) {
			if (mousePressed) {
				mousePressed = False;
				widget.core.hDC = GetDC(hWnd);
				(void) SelectObject(widget.core.hDC,
					GetStockObject(NULL_PEN));
				releasePuzzle(&widget,
					LOWORD(lParam), HIWORD(lParam),
					((GetKeyState(VK_SHIFT) >> 1) ||
					(GetKeyState(VK_CAPITAL) & 1)));
				(void) ReleaseDC(hWnd, widget.core.hDC);
			}
			break;
		}
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		motionPuzzle(&widget, LOWORD(lParam), HIWORD(lParam),
			((GetKeyState(VK_SHIFT) >> 1) ||
			(GetKeyState(VK_CAPITAL) & 1)));
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
	case WM_LBUTTONUP:
		mousePressed = False;
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		releasePuzzle(&widget, LOWORD(lParam), HIWORD(lParam),
			((GetKeyState(VK_SHIFT) >> 1) ||
			(GetKeyState(VK_CAPITAL) & 1)));
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
	case WM_MOUSEWHEEL:
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		{
			int zDelta = ((short) HIWORD(wParam));
			POINT cursor, origin;

			origin.x = 0, origin.y = 0;
			ClientToScreen(hWnd, &origin);
			(void) GetCursorPos(&cursor);
			if (zDelta > (WHEEL_DELTA >> 1)) {
				movePuzzleInput(&widget, cursor.x - origin.x,
					TOP,
					((GetKeyState(VK_SHIFT) >> 1) ||
					(GetKeyState(VK_CAPITAL) & 1)),
					(GetKeyState(VK_CONTROL) >> 1) ? 1 : 0);
				if (GetKeyState(VK_CONTROL) >> 1) {
					sizePuzzle(&widget);
					(void) InvalidateRect(hWnd, NULL, TRUE);
				}
			} else if (zDelta < -(WHEEL_DELTA >> 1)) {
				movePuzzleInput(&widget, cursor.x - origin.x,
					BOTTOM,
					((GetKeyState(VK_SHIFT) >> 1) ||
					(GetKeyState(VK_CAPITAL) & 1)),
					(GetKeyState(VK_CONTROL) >> 1) ? 1 : 0);
				if (GetKeyState(VK_CONTROL) >> 1) {
					sizePuzzle(&widget);
					(void) InvalidateRect(hWnd, NULL, TRUE);
				}
			}
		}
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
#endif
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case ACTION_GET:
			getPuzzle(&widget);
			resizePuzzle(&widget);
			(void) InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ACTION_WRITE:
			writePuzzle(&widget);
			break;
		case ACTION_EXIT:
			destroyPuzzle(&widget, brush);
			break;
		case ACTION_HIDE:
			hidePuzzle(&widget);
			break;
		case ACTION_UNDO:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			undoPuzzle(&widget);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_REDO:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			redoPuzzle(&widget);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_CLEAR:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			clearPuzzle(&widget);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_PRACTICE:
			practicePuzzle(&widget);
			sizePuzzle(&widget);
			(void) InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ACTION_RANDOMIZE:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			randomizePuzzle(&widget);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_SOLVE:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			solvePuzzle(&widget);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_ORIENTIZE:
			orientizePuzzle(&widget);
			sizePuzzle(&widget);
			(void) InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ACTION_MIDDLE:
			(void) middlePuzzle(&widget);
			sizePuzzle(&widget);
			(void) InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ACTION_LEFT:
		case ACTION_RIGHT:
		case ACTION_SHIFT_UP:
		case ACTION_SHIFT_DOWN:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			(void) movePuzzleInput(&widget, 0,
				(int) LOWORD(wParam) - ACTION_SHIFT_UP,
				!((int) wParam & 1), FALSE);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_UP:
		case ACTION_DOWN:
			{
				POINT cursor, origin;

				widget.core.hDC = GetDC(hWnd);
				(void) SelectObject(widget.core.hDC,
					GetStockObject(NULL_PEN));
				origin.x = 0, origin.y = 0;
				ClientToScreen(hWnd, &origin);
				(void) GetCursorPos(&cursor);
				(void) movePuzzleInput(&widget,
					cursor.x - origin.x,
					(int) LOWORD(wParam) - ACTION_UP,
					FALSE, FALSE);
				(void) ReleaseDC(hWnd, widget.core.hDC);
			}
			break;
		case ACTION_DECY:
		case ACTION_INCX:
		case ACTION_INCY:
		case ACTION_DECX:
			movePuzzleInput(&widget, 0,
				(int) LOWORD(wParam) - ACTION_INCY,
				FALSE, TRUE);
			sizePuzzle(&widget);
			(void) InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ACTION_SPEED:
			speedUpPuzzle(&widget);
			break;
		case ACTION_SLOW:
			slowDownPuzzle(&widget);
			break;
		case ACTION_SOUND:
			toggleSoundPuzzle(&widget);
			break;
		case ACTION_DESCRIPTION:
			(void) MessageBox(hWnd, descriptionHelp,
				"Description", MB_OK | MB_ICONQUESTION);
			break;
		case ACTION_FEATURES:
			(void) MessageBox(hWnd, featuresHelp,
				"Features", MB_OK | MB_ICONEXCLAMATION);
			break;
		case ACTION_REFERENCES:
			(void) MessageBox(hWnd, referencesHelp,
				"References", MB_OK | MB_ICONINFORMATION);
			break;
		case ACTION_ABOUT:
			(void) DialogBox(widget.core.hInstance,
				"About", hWnd, (DLGPROC) about);
			break;
		}
		break;
	default:
		return (DefWindowProc(hWnd, message, wParam, lParam));
	}
	return FALSE;
}

int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine,
		int numCmdShow)
{
	HWND hWnd;
	MSG msg;
	WNDCLASS wc;
	HACCEL hAccel;

	if (!hPrevInstance) {
		wc.style = CS_HREDRAW | CS_VREDRAW;
		wc.lpfnWndProc = WindowProc;
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hInstance = hInstance;
		wc.hIcon = LoadIcon(hInstance, TITLE);
		wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW);
		wc.hbrBackground = (HBRUSH) GetStockObject(GRAY_BRUSH);
		wc.lpszMenuName = TITLE;
		wc.lpszClassName = TITLE;
		if (!RegisterClass(&wc))
			return FALSE;
	}
	widget.core.hInstance = hInstance;
	hWnd = CreateWindow(TITLE,
		TITLE,
		WS_OVERLAPPEDWINDOW,
		(signed) CW_USEDEFAULT,
		(signed) CW_USEDEFAULT,
#if 0
		(signed) CW_USEDEFAULT,
		(signed) CW_USEDEFAULT,
#else
		512 + 10, 512 + 10 + 34,
#endif
		HWND_DESKTOP,
		(HMENU) NULL,
		hInstance,
		(XtPointer) NULL);
	if (!hWnd)
		return FALSE;
	hAccel = (HACCEL) LoadAccelerators(hInstance, TITLE);
	(void) ShowWindow(hWnd, numCmdShow);
	(void) UpdateWindow(hWnd);
	while (GetMessage(&msg, (HWND) NULL, 0, 0))
		if (!TranslateAccelerator(hWnd, hAccel, &msg)) {
			(void) TranslateMessage(&msg);
			(void) DispatchMessage(&msg);
		}
	return (int) msg.wParam;
}

#else

static void
usage(char *programName)
{
	unsigned int i;

	(void) fprintf(stderr, "usage: %s\n", programName);
	for (i = 0; i < strlen(synopsisHelp); i++) {
		if (i == 0 || synopsisHelp[i - 1] == '\n')
			(void) fprintf(stderr, "\t");
		(void) fprintf(stderr, "%c", (synopsisHelp[i]));
	}
	(void) fprintf(stderr, "\n");
	exit(1);
}

static XrmOptionDescRec options[] =
{
	{(char *) "-mono", (char *) "*mlink.mono", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nomono", (char *) "*mlink.mono", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-rv", (char *) "*mlink.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-reverse", (char *) "*mlink.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-norv", (char *) "*mlink.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-noreverse", (char *) "*mlink.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-fg", (char *) "*mlink.Foreground", XrmoptionSepArg, NULL},
	{(char *) "-foreground", (char *) "*mlink.Foreground", XrmoptionSepArg, NULL},
	{(char *) "-bg", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-background", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-bd", (char *) "*mlink.tileBorder", XrmoptionSepArg, NULL},
	{(char *) "-border", (char *) "*mlink.tileBorder", XrmoptionSepArg, NULL},
	{(char *) "-tile", (char *) "*mlink.tileColor", XrmoptionSepArg, NULL},
	{(char *) "-face0", (char *) "*mlink.faceColor0", XrmoptionSepArg, NULL},
	{(char *) "-face1", (char *) "*mlink.faceColor1", XrmoptionSepArg, NULL},
	{(char *) "-face2", (char *) "*mlink.faceColor2", XrmoptionSepArg, NULL},
	{(char *) "-face3", (char *) "*mlink.faceColor3", XrmoptionSepArg, NULL},
	{(char *) "-face4", (char *) "*mlink.faceColor4", XrmoptionSepArg, NULL},
	{(char *) "-face5", (char *) "*mlink.faceColor5", XrmoptionSepArg, NULL},
	{(char *) "-face6", (char *) "*mlink.faceColor6", XrmoptionSepArg, NULL},
	{(char *) "-face7", (char *) "*mlink.faceColor7", XrmoptionSepArg, NULL},
	{(char *) "-install", (char *) "*mlink.install", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-noinstall", (char *) "*mlink.install", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-picture", (char *) "*mlink.picture", XrmoptionSepArg, NULL},
	{(char *) "-delay", (char *) "*mlink.delay", XrmoptionSepArg, NULL},
	{(char *) "-sound", (char *) "*mlink.sound", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nosound", (char *) "*mlink.sound", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-bumpSound", (char *) "*mlink.bumpSound", XrmoptionSepArg, NULL},
	{(char *) "-moveSound", (char *) "*mlink.moveSound", XrmoptionSepArg, NULL},
	{(char *) "-base", (char *) "*mlink.base", XrmoptionSepArg, NULL},
	{(char *) "-fn", (char *) "*mlink.font", XrmoptionSepArg, NULL},
	{(char *) "-font", (char *) "*mlink.font", XrmoptionSepArg, NULL},
	{(char *) "-tiles", (char *) "*mlink.tiles", XrmoptionSepArg, NULL},
	{(char *) "-faces", (char *) "*mlink.faces", XrmoptionSepArg, NULL},
	{(char *) "-orient", (char *) "*mlink.orient", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-noorient", (char *) "*mlink.orient", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-middle", (char *) "*mlink.middle", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nomiddle", (char *) "*mlink.middle", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-practice", (char *) "*mlink.practice", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nopractice", (char *) "*mlink.practice", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-userName", (char *) "*mlink.userName", XrmoptionSepArg, NULL},
	{(char *) "-scoreFile", (char *) "*mlink.scoreFile", XrmoptionSepArg, NULL},
	{(char *) "-scores", (char *) "*mlink.scoreOnly", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-version", (char *) "*mlink.versionOnly", XrmoptionNoArg, (char *) "TRUE"}
};

#ifdef HAVE_MOTIF
static void
fileMenuListener(Widget w, XtPointer value, XtPointer clientData)
{
	int val = (int) ((size_t) value) + ACTION_GET;

	if (val == ACTION_EXIT)
		exit(0);
	XtVaSetValues(puzzle, XtNmenu, val, NULL);
}

static void
playMenuListener(Widget w, XtPointer value, XtPointer clientData)
{
	int val = (int) ((size_t) value) + ACTION_UNDO;

#ifndef EXTRA
	if (val >= ACTION_PRACTICE)
		val += ACTION_RANDOMIZE - ACTION_PRACTICE;
	if (val >= ACTION_ORIENTIZE)
		val += ACTION_SOUND - ACTION_ORIENTIZE;
#endif
	XtVaSetValues(puzzle, XtNmenu, val, NULL);
}

static Widget
createQuery(Widget w, char *text, char *title, XtCallbackProc callback)
{
	Widget button, messageBox;
	char titleDsp[FILE_NAME_LENGTH + 8];
	XmString titleString = NULL, messageString = NULL;
	static XmStringCharSet charSet =
		(XmStringCharSet) XmSTRING_DEFAULT_CHARSET;

	messageString = XmStringCreateLtoR(text, charSet);
#ifdef HAVE_SNPRINTF
	(void) snprintf(titleDsp, TITLE_FILE_LENGTH,
		"%s: %s", progDsp, title);
#else
	(void) sprintf(titleDsp, "%s: %s", progDsp, title);
#endif
	titleString = XmStringCreateSimple((char *) titleDsp);
	XtSetArg(args[0], XmNdialogTitle, titleString);
	XtSetArg(args[1], XmNmessageString, messageString);
	messageBox = XmCreateWarningDialog(w, (char *) "queryBox",
		args, 2);
	button = XmMessageBoxGetChild(messageBox, XmDIALOG_HELP_BUTTON);
	XtUnmanageChild(button);
	XmStringFree(titleString);
	XmStringFree(messageString);
	XtAddCallback(messageBox, XmNokCallback, callback, (XtPointer) NULL);
	XtAddCallback(messageBox, XmNcancelCallback, callback,
		(XtPointer) NULL);
	return messageBox;
}

static Widget
createHelp(Widget w, char *text, char *title)
{
	Widget button, messageBox;
	char titleDsp[FILE_NAME_LENGTH + 8];
	XmString titleString = NULL, messageString = NULL, buttonString = NULL;
	static XmStringCharSet charSet =
		(XmStringCharSet) XmSTRING_DEFAULT_CHARSET;

	messageString = XmStringCreateLtoR(text, charSet);
#ifdef HAVE_SNPRINTF
	(void) snprintf(titleDsp, TITLE_FILE_LENGTH,
		"%s: %s", progDsp, title);
#else
	(void) sprintf(titleDsp, "%s: %s", progDsp, title);
#endif
	titleString = XmStringCreateSimple((char *) titleDsp);
	buttonString = XmStringCreateSimple((char *) "OK");
	XtSetArg(args[0], XmNdialogTitle, titleString);
	XtSetArg(args[1], XmNokLabelString, buttonString);
	XtSetArg(args[2], XmNmessageString, messageString);
	messageBox = XmCreateInformationDialog(w, (char *) "helpBox",
		args, 3);
	button = XmMessageBoxGetChild(messageBox, XmDIALOG_CANCEL_BUTTON);
	XtUnmanageChild(button);
	button = XmMessageBoxGetChild(messageBox, XmDIALOG_HELP_BUTTON);
	XtUnmanageChild(button);
	XmStringFree(titleString);
	XmStringFree(buttonString);
	XmStringFree(messageString);
	return messageBox;
}

/*http://www.ist.co.uk/motif/books/vol6A/ch-5.fm.html*/
static Widget
createScrollHelp(Widget w, const char *text, char *title)
{
	Widget dialog, pane, scrolledText, form, label, button;
	int n = 0;
	char titleDsp[FILE_NAME_LENGTH + 8];
	XmString titleString = NULL;

#ifdef HAVE_SNPRINTF
	(void) snprintf(titleDsp, TITLE_FILE_LENGTH,
		"%s: %s", progDsp, title);
#else
	(void) sprintf(titleDsp, "%s: %s", progDsp, title);
#endif
	dialog = XmCreateMessageDialog(w, titleDsp, NULL, 0);
	titleString = XmStringCreateSimple((char *) titleDsp);
	pane = XtVaCreateWidget("pane", xmPanedWindowWidgetClass, dialog,
		XmNsashWidth, 1, XmNsashHeight, 1, NULL);
	form = XtVaCreateWidget("form", xmFormWidgetClass, pane, NULL);
	label = XtVaCreateManagedWidget("label", xmLabelGadgetClass, form,
		XmNlabelType, XmPIXMAP,
		XmNlabelPixmap, pixmap,
		XmNleftAttachment, XmATTACH_FORM,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM, NULL);
	XtSetArg(args[n], XmNdialogTitle, titleString); n++;
	XtSetArg(args[n], XmNscrollVertical, True); n++;
	XtSetArg(args[n], XmNscrollHorizontal, False); n++;
	XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++;
	XtSetArg(args[n], XmNeditable, False); n++;
	XtSetArg(args[n], XmNcursorPositionVisible, False); n++;
	XtSetArg(args[n], XmNwordWrap, False); n++;
	XtSetArg(args[n], XmNresizeWidth, True); n++;
	XtSetArg(args[n], XmNvalue, text); n++;
	XtSetArg(args[n], XmNrows, SCROLL_SIZE); n++;
	scrolledText = XmCreateScrolledText(form, (char *) "helpText", args, n);
	XtVaSetValues(XtParent(scrolledText),
		XmNleftAttachment, XmATTACH_WIDGET,
		XmNleftWidget, label,
		XmNtopAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM, NULL);
	XmStringFree(titleString);
	XtManageChild(scrolledText);
	XtManageChild(form);
	XtManageChild(pane);
	button = XmMessageBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON);
	XtUnmanageChild(button);
	button = XmMessageBoxGetChild(dialog, XmDIALOG_HELP_BUTTON);
	XtUnmanageChild(button);
	return dialog;
}

static void
helpMenuListener(Widget w, XtPointer value, XtPointer clientData)
{
	int val = (int) ((size_t) value);

	switch (val) {
	case 0:
		XtManageChild(descriptionDialog);
		break;
	case 1:
		XtManageChild(featuresDialog);
		break;
	case 2:
		XtManageChild(synopsisDialog);
		break;
	case 3:
		XtManageChild(referencesDialog);
		break;
	case 4:
		XtManageChild(aboutDialog);
		break;
	default:
		{
			char *buf;

			intCat(&buf, "helpMenuListener: %d", val);
			XtWarning(buf);
			free(buf);
		}
	}
}

#elif defined(HAVE_ATHENA)
static void
createTileSlider(Widget form)
{
	Widget scrollbar;
	char message[BUFSIZ];
	int tiles;

	XtVaGetValues(puzzle,
		XtNtiles, &tiles, NULL);
	(void) sprintf(message, "Tiles: %d", tiles);
	scrollbar = XtVaCreateManagedWidget("scrollbar",
		scrollbarWidgetClass, form,
		XtNorientation, XtorientHorizontal,
		XtNlength, SCROLL_SIZE, NULL);
	tileSliderLabel = XtVaCreateManagedWidget(message,
		labelWidgetClass, form,
		XtNfromHoriz, scrollbar, NULL);
	XtAddCallback(scrollbar,
		XtNscrollProc, tileChangeListener,
		(XtPointer) tileSliderLabel);
	XtAddCallback(scrollbar,
		XtNjumpProc, tileChangeListener,
		(XtPointer) tileSliderLabel);
}

static void
createFaceSlider(Widget form)
{
	Widget scrollbar;
	char message[BUFSIZ];
	int faces;

	XtVaGetValues(puzzle,
		XtNfaces, &faces, NULL);
	(void) sprintf(message, "Faces: %d", faces);
	scrollbar = XtVaCreateManagedWidget("scrollbar",
		scrollbarWidgetClass, form,
		XtNorientation, XtorientHorizontal,
		XtNlength, SCROLL_SIZE, NULL);
	faceSliderLabel = XtVaCreateManagedWidget(message,
		labelWidgetClass, form,
		XtNfromHoriz, scrollbar, NULL);
	XtAddCallback(scrollbar,
		XtNscrollProc, faceChangeListener,
		(XtPointer) faceSliderLabel);
	XtAddCallback(scrollbar,
		XtNjumpProc, faceChangeListener,
		(XtPointer) faceSliderLabel);
}

static void
createSpeedSlider(Widget form)
{
	Widget scrollbar;
	char message[BUFSIZ];
	int delay;

	XtVaGetValues(puzzle,
		XtNdelay, &delay, NULL);
	(void) sprintf(message, "Animation Speed: %d",
		MAX_SPEED + MIN_SPEED - delay - 1);
	scrollbar = XtVaCreateManagedWidget("scrollbar",
		scrollbarWidgetClass, form,
		XtNorientation, XtorientHorizontal,
		XtNlength, SCROLL_SIZE, NULL);
	speedSliderLabel = XtVaCreateManagedWidget(message,
		labelWidgetClass, form,
		XtNfromHoriz, scrollbar, NULL);
	XtAddCallback(scrollbar,
		XtNscrollProc, speedChangeListener,
		(XtPointer) speedSliderLabel);
	XtAddCallback(scrollbar,
		XtNjumpProc, speedChangeListener,
		(XtPointer) speedSliderLabel);
}

static void
puzzlePracticeCancelListener(Widget w, XtPointer clientData, XtPointer callData)
{
	XtUnmanageChild(practiceDialog);
}

static void
createPracticeQuery(char *text, char *title)
{
	Widget dialog;

	practiceDialog = XtCreatePopupShell(title,
		transientShellWidgetClass, topLevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog",
		dialogWidgetClass, practiceDialog,
		XtNlabel, text, NULL);
	practiceOKDialog = XtVaCreateManagedWidget("OK",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(practiceOKDialog, XtNcallback,
		puzzlePracticeListener, dialog);
	practiceCancelDialog = XtVaCreateManagedWidget("Cancel",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(practiceCancelDialog, XtNcallback,
		puzzlePracticeCancelListener, dialog);
}

static void
puzzleRandomizeCancelListener(Widget w, XtPointer clientData, XtPointer callData)
{
	XtUnmanageChild(randomizeDialog);
}

static void
createRandomizeQuery(char *text, char *title)
{
	Widget dialog;

	randomizeDialog = XtCreatePopupShell(title,
		transientShellWidgetClass, topLevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog",
		dialogWidgetClass, randomizeDialog,
		XtNlabel, text, NULL);
	randomizeOKDialog = XtVaCreateManagedWidget("OK",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(randomizeOKDialog, XtNcallback,
		puzzleRandomizeListener, dialog);
	randomizeCancelDialog = XtVaCreateManagedWidget("Cancel",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(randomizeCancelDialog, XtNcallback,
		puzzleRandomizeCancelListener, dialog);
}

static void
puzzleSolveOKListener(Widget w, XtPointer clientData, XtPointer callData)
{
	XtUnmanageChild(solveDialog);
}

static void
createSolveInfo(char *text, char *title)
{
	Widget dialog;

	solveDialog = XtCreatePopupShell(title,
		transientShellWidgetClass, topLevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog",
		dialogWidgetClass, solveDialog,
		XtNlabel, text, NULL);
	solveOKDialog = XtVaCreateManagedWidget("OK",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(solveOKDialog, XtNcallback,
		puzzleSolveOKListener, dialog);
}
#endif

int
main(int argc, char **argv)
{
	int pixmapSize;
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	Widget mainPanel, controlPanel;
	Widget movesRowCol, changerRowCol;
#endif
#ifdef HAVE_MOTIF
	Widget menuBar, pullDownMenu, widget;
	Widget menuBarPanel;
	Widget changerTilesRowCol, changerFacesRowCol, changerSpeedRowCol;
	Widget switchRowCol, messageRowCol;
	XmString fileString, playString;
	XmString getString, writeString, quitString;
	XmString undoString, redoString, clearString;
#ifdef EXTRA
	XmString practiceString;
#endif
	XmString randomizeString, solveString;
#ifdef EXTRA
	XmString orientizeString, middleString;
	XmString speedString, slowString;
#endif
	XmString soundString;
#elif defined(HAVE_ATHENA)
	Widget movesLabel, recordLabel, switchRowCol, speedRowCol;
#endif

	progDsp = argv[0];
	topLevel = XtInitialize(argv[0], "Mlink",
		options, XtNumber(options), &argc, argv);
	if (argc != 1)
		usage(argv[0]);

#ifdef HAVE_MOTIF
	menuBarPanel = XtVaCreateManagedWidget("menuBarPanel",
		xmPanedWindowWidgetClass, topLevel,
		XmNseparatorOn, False,
		XmNsashWidth, 1,
		XmNsashHeight, 1, NULL);
	fileString = XmStringCreateSimple((char *) "File");
	playString = XmStringCreateSimple((char *) "Play");
	menuBar = XmVaCreateSimpleMenuBar(menuBarPanel, (char *) "menuBar",
		XmVaCASCADEBUTTON, fileString, 'F',
		XmVaCASCADEBUTTON, playString, 'P', NULL);
	XmStringFree(fileString);
	XmStringFree(playString);
	getString = XmStringCreateSimple((char *) "Get");
	writeString = XmStringCreateSimple((char *) "Write");
	quitString = XmStringCreateSimple((char *) "Exit");
	(void) XmVaCreateSimplePulldownMenu(menuBar, (char *) "fileMenu",
		0, fileMenuListener,
		XmVaPUSHBUTTON, getString, 'G', NULL, NULL,
		XmVaPUSHBUTTON, writeString, 'W', NULL, NULL,
		XmVaSEPARATOR,
		XmVaPUSHBUTTON, quitString, 'x', NULL, NULL, NULL);
	XmStringFree(getString);
	XmStringFree(writeString);
	XmStringFree(quitString);
	undoString = XmStringCreateSimple((char *) "Undo");
	redoString = XmStringCreateSimple((char *) "Redo");
	clearString = XmStringCreateSimple((char *) "Clear");
#ifdef EXTRA
	practiceString = XmStringCreateSimple((char *) "Practice");
#endif
	randomizeString = XmStringCreateSimple((char *) "Randomize");
	solveString = XmStringCreateSimple((char *) "Auto-solve");
#ifdef EXTRA
	orientizeString = XmStringCreateSimple((char *) "Orientize");
	middleString = XmStringCreateSimple((char *) "Middle");
	speedString = XmStringCreateSimple((char *) "Speed >");
	slowString = XmStringCreateSimple((char *) "Slow <");
#endif
	soundString = XmStringCreateSimple((char *) "Sound @");
	(void) XmVaCreateSimplePulldownMenu(menuBar, (char *) "playMenu",
		1, playMenuListener,
		XmVaPUSHBUTTON, undoString, 'U', NULL, NULL,
		XmVaPUSHBUTTON, redoString, 'R', NULL, NULL,
		XmVaPUSHBUTTON, clearString, 'C', NULL, NULL,
#ifdef EXTRA
		XmVaPUSHBUTTON, practiceString, 'P', NULL, NULL,
#endif
		XmVaPUSHBUTTON, randomizeString, 'z', NULL, NULL,
		XmVaPUSHBUTTON, solveString, 's', NULL, NULL,
#ifdef EXTRA
		XmVaPUSHBUTTON, orientizeString, 'O', NULL, NULL,
		XmVaPUSHBUTTON, middleString, 'M', NULL, NULL,
		XmVaPUSHBUTTON, speedString, '>', NULL, NULL,
		XmVaPUSHBUTTON, slowString, '<', NULL, NULL,
#endif
		XmVaPUSHBUTTON, soundString, '@', NULL, NULL, NULL);
	XmStringFree(undoString);
	XmStringFree(redoString);
	XmStringFree(clearString);
#ifdef EXTRA
	XmStringFree(practiceString);
#endif
	XmStringFree(randomizeString);
	XmStringFree(solveString);
#ifdef EXTRA
	XmStringFree(orientizeString);
	XmStringFree(middleString);
	XmStringFree(speedString);
	XmStringFree(slowString);
#endif
	XmStringFree(soundString);
	pullDownMenu = XmCreatePulldownMenu(menuBar,
		(char *) "helpPullDown", NULL, 0);
	widget = XtVaCreateManagedWidget("Help",
		xmCascadeButtonWidgetClass, menuBar,
		XmNsubMenuId, pullDownMenu,
		XmNmnemonic, 'H', NULL); /* mnemonic error on Cygwin */
	XtVaSetValues(menuBar, XmNmenuHelpWidget, widget, NULL);
	widget = XtVaCreateManagedWidget("Description",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'D', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 0);
	widget = XtVaCreateManagedWidget("Features",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'F', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 1);
	widget = XtVaCreateManagedWidget("Synopsis",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'S', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 2);
	widget = XtVaCreateManagedWidget("References",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'R', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 3);
	widget = XtVaCreateManagedWidget("About",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'A', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 4);
	XtManageChild(menuBar);
	solveDialog = createHelp(menuBar, (char *) solveHelp,
		(char *) "Solve");
	practiceDialog = createQuery(topLevel,
		(char *) "Are you sure you want to toggle the practice mode?",
		(char *) "Practice Query",
		(XtCallbackProc) puzzlePracticeListener);
	randomizeDialog = createQuery(topLevel,
		(char *) "Are you sure you want to randomize?",
		(char *) "Randomize Query",
		(XtCallbackProc) puzzleRandomizeListener);
	mainPanel = XtVaCreateManagedWidget("mainPanel",
		xmPanedWindowWidgetClass, menuBarPanel, NULL);
	controlPanel = XtVaCreateManagedWidget("controlPanel",
		xmPanedWindowWidgetClass, mainPanel,
		XmNseparatorOn, False,
		XmNsashWidth, 1,
		XmNsashHeight, 1, NULL);
	movesRowCol = XtVaCreateManagedWidget("movesRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef MOUSEBITMAPS
	{
		/* Takes up valuable real estate. */
		Pixmap mouseLeftCursor, mouseRightCursor;
		Pixel fg, bg;

		(void) XtVaGetValues(movesRowCol,
			XmNforeground, &fg,
			XmNbackground, &bg, NULL);
		mouseLeftCursor = XCreatePixmapFromBitmapData(
			XtDisplay(movesRowCol),
			RootWindowOfScreen(XtScreen(movesRowCol)),
			(char *) mouse_left_bits,
			mouse_left_width, mouse_left_height, fg, bg,
			DefaultDepthOfScreen(XtScreen(movesRowCol)));
		mouseRightCursor = XCreatePixmapFromBitmapData(
			XtDisplay(movesRowCol),
			RootWindowOfScreen(XtScreen(movesRowCol)),
			(char *) mouse_right_bits,
			mouse_right_width, mouse_right_height, fg, bg,
			DefaultDepthOfScreen(XtScreen(movesRowCol)));
		(void) XtVaCreateManagedWidget("mouseLeftText",
			xmLabelGadgetClass, movesRowCol,
			XtVaTypedArg, XmNlabelString,
			XmRString, "Move tile", 10, NULL);
		(void) XtVaCreateManagedWidget("mouseLeft",
			xmLabelGadgetClass, movesRowCol,
			XmNlabelType, XmPIXMAP,
			XmNlabelPixmap, mouseLeftCursor, NULL);
		(void) XtVaCreateManagedWidget("mouseRightText",
			xmLabelGadgetClass, movesRowCol,
			XtVaTypedArg, XmNlabelString,
			XmRString, "Randomize", 10, NULL);
		(void) XtVaCreateManagedWidget("mouseRight",
			xmLabelGadgetClass, movesRowCol,
			XmNlabelType, XmPIXMAP,
			XmNlabelPixmap, mouseRightCursor, NULL);
	}
#endif
	(void) XtVaCreateManagedWidget("movesText",
		xmLabelGadgetClass, movesRowCol,
		XtVaTypedArg, XmNlabelString, XmRString, "Moves", 6, NULL);
	movesText = XtVaCreateManagedWidget("0",
		xmLabelWidgetClass, movesRowCol, NULL);
	(void) XtVaCreateManagedWidget("nullText",
		xmLabelGadgetClass, movesRowCol,
		XtVaTypedArg, XmNlabelString, XmRString, " ", 2, NULL);
	(void) XtVaCreateManagedWidget("recordText",
		xmLabelGadgetClass, movesRowCol,
		XtVaTypedArg, XmNlabelString, XmRString, "Record", 7, NULL);
	recordText = XtVaCreateManagedWidget("0",
		xmLabelWidgetClass, movesRowCol, NULL);
	changerRowCol = XtVaCreateManagedWidget("changerRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	changerTilesRowCol = XtVaCreateManagedWidget("changerTilesRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	XtManageChild(XmCreateLabel(changerTilesRowCol, (char *) "Tiles:", NULL, 0));
	tileChanger = XtVaCreateManagedWidget("tileChanger",
#ifdef USE_SPIN
		xmSimpleSpinBoxWidgetClass, changerTilesRowCol,
		XmNspinBoxChildType, XmNUMERIC,
		XmNminimumValue, MIN_TILES,
		XmNmaximumValue, MAX_TILES,
		XmNposition, DEFAULT_TILES,
		XmNwrap, FALSE,
		XmNincrementValue, 1,
		XmNcolumns, 2,
#else
		xmScaleWidgetClass, changerTilesRowCol,
		XmNminimum, MIN_TILES,
		XmNmaximum, MAX_TILES,
		XmNvalue, DEFAULT_TILES,
#endif
		/*XtVaTypedArg, XmNtitleString, XmRString, "Tiles", 6,*/
		XmNshowValue, True,
		XmNorientation, XmHORIZONTAL, NULL);
	XtAddCallback(tileChanger, XmNvalueChangedCallback,
		(XtCallbackProc) tileChangeListener, (XtPointer) NULL);
	changerFacesRowCol = XtVaCreateManagedWidget("changerFacesRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	XtManageChild(XmCreateLabel(changerFacesRowCol, (char *) "Faces:", NULL, 0));
	faceChanger = XtVaCreateManagedWidget("faceChanger",
#ifdef USE_SPIN
		xmSimpleSpinBoxWidgetClass, changerFacesRowCol,
		XmNspinBoxChildType, XmNUMERIC,
		XmNminimumValue, MIN_FACES,
		XmNmaximumValue, MAX_FACES,
		XmNposition, DEFAULT_FACES,
		XmNwrap, FALSE,
		XmNincrementValue, 1,
		XmNcolumns, 2,
#else
		xmScaleWidgetClass, changerFacesRowCol,
		XmNminimum, MIN_FACES,
		XmNmaximum, MAX_FACES,
		XmNvalue, DEFAULT_FACES,
#endif
		/*XtVaTypedArg, XmNtitleString, XmRString, "Faces", 6,*/
		XmNshowValue, True,
		XmNorientation, XmHORIZONTAL, NULL);
	XtAddCallback(faceChanger, XmNvalueChangedCallback,
		(XtCallbackProc) faceChangeListener, (XtPointer) NULL);
	changerSpeedRowCol = XtVaCreateManagedWidget("changerSpeedRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	XtManageChild(XmCreateLabel(changerSpeedRowCol, (char*) "Animation Speed:", NULL, 0));
	speedChanger = XtVaCreateManagedWidget("speedChanger",
#ifdef USE_SPIN
		xmSimpleSpinBoxWidgetClass, changerSpeedRowCol,
		XmNspinBoxChildType, XmNUMERIC,
		XmNminimumValue, MIN_SPEED,
		XmNmaximumValue, MAX_SPEED,
		XmNposition, MAX_SPEED - DEFAULT_DELAY,
		XmNwrap, FALSE,
		XmNincrementValue, 1,
		XmNcolumns, 2,
#else

		xmScaleWidgetClass, changerSpeedRowCol,
		XmNminimum, MIN_SPEED,
		XmNmaximum, MAX_SPEED,
		XmNvalue, MAX_SPEED - DEFAULT_DELAY,
#endif
		/*XtVaTypedArg, XmNtitleString, XmRString, "Animation Speed", 16,*/
		XmNshowValue, True,
		XmNorientation, XmHORIZONTAL, NULL);
	XtAddCallback(speedChanger, XmNvalueChangedCallback,
		(XtCallbackProc) speedChangeListener, (XtPointer) NULL);
	switchRowCol = XtVaCreateManagedWidget("switchRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	orientizeSwitch = XtVaCreateManagedWidget("Oriented",
		xmToggleButtonWidgetClass, switchRowCol,
		XmNset, DEFAULT_ORIENT, NULL);
	XtAddCallback(orientizeSwitch, XmNvalueChangedCallback,
		(XtCallbackProc) orientToggle, (XtPointer) NULL);
	middleSwitch = XtVaCreateManagedWidget("Middle rigid",
		xmToggleButtonWidgetClass, switchRowCol,
		XmNset, DEFAULT_MIDDLE, NULL);
	XtAddCallback(middleSwitch, XmNvalueChangedCallback,
		(XtCallbackProc) middleToggle, (XtPointer) NULL);
	practiceSwitch = XtVaCreateManagedWidget("Practice",
		xmToggleButtonWidgetClass, switchRowCol,
		XmNset, DEFAULT_PRACTICE, NULL);
	XtAddCallback(practiceSwitch, XmNvalueChangedCallback,
		(XtCallbackProc) practiceToggle, (XtPointer) NULL);
	messageRowCol = XtVaCreateManagedWidget("messageRowCol",
		xmRowColumnWidgetClass, controlPanel, NULL);
	message = XtVaCreateManagedWidget("Play Missing Link! (use mouse and keypad)",
		xmLabelWidgetClass, messageRowCol, NULL);
	puzzle = XtVaCreateManagedWidget("mlink",
		mlinkWidgetClass, mainPanel, NULL);
#elif defined(HAVE_ATHENA)
	createPracticeQuery(
		(char *) "Are you sure you want to toggle the practice mode?",
		(char *) "Practice Query");
	createRandomizeQuery(
		(char *) "Are you sure you want to randomize?",
		(char *) "Randomize Query");
	createSolveInfo(
		(char *) solveHelp,
		(char *) "Auto-solve");
	mainPanel = XtVaCreateManagedWidget("mainPanel",
		formWidgetClass, topLevel, NULL);
	controlPanel = XtVaCreateManagedWidget("controlPanel",
		formWidgetClass, mainPanel,
		XtNborderWidth, 0, NULL);
	movesRowCol = XtVaCreateManagedWidget("movesRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0, NULL);
	movesLabel = XtVaCreateManagedWidget("Moves",
		labelWidgetClass, movesRowCol,
		XtNborderWidth, 0, NULL);
	movesText = XtVaCreateManagedWidget("0",
		labelWidgetClass, movesRowCol,
		XtNwidth, 9,
		XtNfromHoriz, movesLabel, NULL);
	recordLabel = XtVaCreateManagedWidget("Record",
		labelWidgetClass, movesRowCol,
		XtNborderWidth, 0,
		XtNfromHoriz, movesText, NULL);
	recordText = XtVaCreateManagedWidget("0",
		labelWidgetClass, movesRowCol,
		XtNfromHoriz, recordLabel, NULL);
	changerRowCol = XtVaCreateManagedWidget("changerRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, movesRowCol, NULL);
	tileChanger = XtVaCreateManagedWidget("tileChanger",
		boxWidgetClass, changerRowCol,
		XtNborderWidth, 0, NULL);
	faceChanger = XtVaCreateManagedWidget("faceChanger",
		boxWidgetClass, changerRowCol,
		XtNborderWidth, 0,
		XtNfromHoriz, tileChanger, NULL);
	switchRowCol = XtVaCreateManagedWidget("switchRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, changerRowCol, NULL);
	orientizeSwitch = XtVaCreateManagedWidget("Oriented",
		toggleWidgetClass, switchRowCol,
		XtNstate, DEFAULT_ORIENT, NULL);
	XtAddCallback(orientizeSwitch, XtNcallback,
		(XtCallbackProc) orientToggle, (XtPointer) NULL);
	middleSwitch = XtVaCreateManagedWidget("Middle rigid",
		toggleWidgetClass, switchRowCol,
		XtNstate, DEFAULT_MIDDLE,
		XtNfromHoriz, orientizeSwitch, NULL);
	XtAddCallback(middleSwitch, XtNcallback,
		(XtCallbackProc) middleToggle, (XtPointer) NULL);
	practiceSwitch = XtVaCreateManagedWidget("Practice",
		toggleWidgetClass, switchRowCol,
		XtNstate, DEFAULT_PRACTICE,
		XtNfromHoriz, middleSwitch, NULL);
	XtAddCallback(practiceSwitch, XtNcallback,
		(XtCallbackProc) practiceToggle, (XtPointer) NULL);
	speedRowCol = XtVaCreateManagedWidget("speedRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, switchRowCol, NULL);
	speedChanger = XtVaCreateManagedWidget("speedChanger",
		boxWidgetClass, speedRowCol,
		XtNborderWidth, 0, NULL);
	message = XtVaCreateManagedWidget("Welcome",
		labelWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, speedRowCol, NULL);
	puzzle = XtVaCreateManagedWidget("mlink",
		mlinkWidgetClass, mainPanel,
		XtNfromVert, controlPanel, NULL);
#else
	puzzle = XtVaCreateManagedWidget("mlink",
		mlinkWidgetClass, topLevel, NULL);
#endif
	XtVaGetValues(puzzle,
		XtNpixmapSize, &pixmapSize, NULL);
#ifdef HAVE_XPM
	{
		XpmAttributes xpmAttributes;
		XpmColorSymbol transparentColor[1] = {{NULL,
			(char *) "none", 0 }};
		Pixel bg;

		xpmAttributes.valuemask = XpmColorSymbols | XpmCloseness;
		xpmAttributes.colorsymbols = transparentColor;
		xpmAttributes.numsymbols = 1;
		xpmAttributes.closeness = 40000;
		XtVaGetValues(topLevel, XtNbackground, &bg, NULL);
		transparentColor[0].pixel = bg;
		(void) XpmCreatePixmapFromData(XtDisplay(topLevel),
			RootWindowOfScreen(XtScreen(topLevel)),
			RESIZE_XPM(pixmapSize), &pixmap, NULL,
			&xpmAttributes);
	}
	if (pixmap == (Pixmap) NULL)
#endif
		pixmap = XCreateBitmapFromData(XtDisplay(topLevel),
			RootWindowOfScreen(XtScreen(topLevel)),
			DEFINE_XBM);
	XtVaSetValues(topLevel,
#ifdef HAVE_MOTIF
		XmNkeyboardFocusPolicy, XmPOINTER, /* not XmEXPLICIT */
#else
		XtNinput, True,
#endif
		XtNiconPixmap, pixmap, NULL);
	XtAddCallback(puzzle, XtNselectCallback,
		(XtCallbackProc) puzzleListener, (XtPointer) NULL);
#ifdef HAVE_MOTIF
	descriptionDialog = createHelp(menuBar, (char *) descriptionHelp,
		(char *) "Description");
	featuresDialog = createScrollHelp(menuBar, (char *) featuresHelp,
		(char *) "Features");
	synopsisDialog = createHelp(menuBar, (char *) synopsisHelp,
		(char *) "Synopsis");
	referencesDialog = createHelp(menuBar, (char *) referencesHelp,
		(char *) "References");
	aboutDialog = createHelp(menuBar, (char *) aboutHelp,
		(char *) "About");
#elif defined(HAVE_ATHENA)
	createTileSlider(tileChanger);
	createFaceSlider(faceChanger);
	createSpeedSlider(speedChanger);
#endif
	initialize(puzzle);
	XtRealizeWidget(topLevel);
	XGrabButton(XtDisplay(puzzle), (unsigned int) AnyButton, AnyModifier,
		XtWindow(puzzle), TRUE, (unsigned int) (ButtonPressMask |
		ButtonMotionMask | ButtonReleaseMask),
		GrabModeAsync, GrabModeAsync, XtWindow(puzzle),
		XCreateFontCursor(XtDisplay(puzzle), XC_hand2));
	XtMainLoop();

#ifdef VMS
	return 1;
#else
	return 0;
#endif
}
#endif
