/*
 * @(#)xbarrel.c
 *
 * Copyright 2003 - 2025  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 Barrel */

#ifndef WINVER
#include "version.h"
static const char aboutHelp[] = {
"Barrel 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"
"[-{border|bd} {color}] [-face{0|1|2|3|4|5} {color}]\n"
"[-tile {color}] [-frame {color}] [-[no]stippleFrame]\n"
"[-[no]install] [-picture {filename}] [-delay msecs]\n"
"[-[no]sound] [-bumpSound {filename}]\n"
"[-moveSound {filename}] [-{font|fn} {fontname}]\n"
"[-[no]orient] [-[no]pairs] [-[no]practice] [-base {int}]\n"
"[-userName {string}] [-scoreFile {filename}] [-scores]\n"
"[-version]"
};
#endif

#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA) || defined(WINVER)
static const char descriptionHelp[] = {
"The Barrel, the Billion Barrel, or Wonderful Barrel also "
"seen as the Cylinder Puzzle of Japanese origin.  The puzzle\n"
"contains 23 beads of 6 different colors.  4 each of 5 "
"different colors arranged in 5 rows and 3 black beads making\n"
"3 rows one unit longer.  A system of plungers slide all "
"three of the long rows left and right.  Two of the plungers\n"
"sit together and the other (the middle plunger) is "
"separate from the other two.  There are 2 separate wheels or\n"
"disks that rotate about the center axis."
};

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"
"Press \"S\" or \"s\" keys to start the auto-solver.  Only works "
"where oriented is off.\n"
"\n"
"Press \"O\" or \"o\" keys to toggle orient mode.  Slightly "
"more challenging on (default is off).\n"
"\n"
"Press \"I\" or \"i\" keys to toggle the pairs mode.  All "
"the tiles rotate in pairs.  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 Barrel 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."
};

static const char referencesHelp[] = {
"L. E. Horden, Sliding Piece Puzzles (Recreations in "
"Mathematics Series), Oxford University\n"
"Press 1986, Plate X.\n"
"James G Nourse, The Simple Solutions to Cubic, Puzzles, "
"Bantam Books, New York, November 1981, pp 25-42.\n"
"John Ewing & Czes Kosniowski, Puzzle it Out: "
"Cubes Groups and Puzzles, Cambridge University Press,\n"
"New York, 1982, pp 50-54?"
};
#endif

static const char solveHelp[] = {
"Auto-solver: sorry, only implemented when oriented is off."
};

#include "file.h"
#ifdef WINVER
#include "BarrelP.h"
#define TITLE "wbarrel"

static BarrelRec widget;

#ifndef SCOREPATH
#ifdef UNIXDELIM
#define SCOREPATH "C:/ProgramData/wpuzzles"
#else
#define SCOREPATH "C:\\ProgramData\\wpuzzles"
#endif
#endif
#define PRINT_MESSAGE(b) (void) MessageBox(widget.core.hWnd, (LPCSTR) b, "Warning", MB_OK);
#define SET_STARTED(w,b) w->barrel.started = b
#else
#include "xwin.h"
#include "xgui.h"
#define SET_STARTED(w,b) XtVaSetValues(w, XtNstart, b, NULL)
#include "Barrel.h"
#ifdef HAVE_XPM
#include <X11/xpm.h>
#ifdef CONSTPIXMAPS
#include "icons/16x16/barrel.xpm"
#include "icons/22x22/barrel.xpm"
#include "icons/24x24/barrel.xpm"
#include "icons/32x32/barrel.xpm"
#include "icons/48x48/barrel.xpm"
#include "icons/64x64/barrel.xpm"
#else
#include "pixmaps/16x16/barrel.xpm"
#include "pixmaps/22x22/barrel.xpm"
#include "pixmaps/24x24/barrel.xpm"
#include "pixmaps/32x32/barrel.xpm"
#include "pixmaps/48x48/barrel.xpm"
#include "pixmaps/64x64/barrel.xpm"
#endif
#define RESIZE_XPM(s) ((char **) (((s)<=32)?\
(((s)<=22)?(((s)<=16)?barrel_16x16:barrel_22x22):\
(((s)<=24)?barrel_24x24:barrel_32x32)):\
(((s)<=48)?barrel_48x48:barrel_64x64)))
#endif
#include "pixmaps/64x64/barrel.xbm"
#define DEFINE_XBM (char *) barrel_64x64_bits, barrel_64x64_width, barrel_64x64_height
#ifdef HAVE_EDITRES
#ifdef __VMS
#include <Xmu/Editres.h>
#else
#include <X11/Xmu/Editres.h>
#endif
#endif
#ifndef SCOREPATH
#ifdef __VMS
#define SCOREPATH "SYS$LOGIN:"
#else
#define SCOREPATH "/var/games/xpuzzles"
#endif
#endif
#endif

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

#define NEVER (-1)
#define USER_NAME_LENGTH 120
#define MESSAGE_LENGTH (USER_NAME_LENGTH+64)
#define NOACCESS "noaccess"
#define NOBODY "nobody"

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

static PuzzleRecord puzzleRecord[2][2];
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 orientToggle, pairsToggle, practiceToggle;
static Widget soundMenuItem;
static Widget practiceDialog, randomizeDialog, solveDialog;
static Widget descriptionDialog, featuresDialog;
static Widget synopsisDialog, referencesDialog, aboutDialog;
static char buff[MESSAGE_LENGTH];
static const char *speedLabel = "Animation Speed:";
#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
#if 0
static Widget tileChanger, faceChanger;
#endif
static Widget speedChanger;
#elif defined(HAVE_ATHENA)
#if 0
static Widget tileSlider, tileSliderLabel;
static Widget faceSlider, faceSliderLabel;
#endif
static Widget speedSlider, speedSliderLabel;
static const char *fileTypes[] =
{
	"Get",
	"Write",
	"Exit"
};
#define numFileTypes (sizeof(fileTypes)/sizeof(fileTypes[0]))
static const char *playTypes[] =
{
	"Undo",
	"Redo",
	"Clear",
#ifdef EXTRA
	"Practice",
#endif
	"Randomize",
	"Auto-solve",
#ifdef EXTRA
	"Increment",
	"Decrement",
	"Oriented",
	"Pairs",
	"Speed >",
	"Slow <",
#endif
	"Sound @"
};
#define numPlayTypes (sizeof(playTypes)/sizeof(playTypes[0]))
static const char *helpTypes[] =
{
	"Description...",
	"Features...",
	"Synopsis...",
	"References...",
	"About..."
};
#define numHelpTypes (sizeof(helpTypes)/sizeof(helpTypes[0]))
#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 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 k, l;

	(void) printf("    BARREL  HALL OF FAME\n\n");
	(void) printf("PAIR ORIENT USER            MOVES\n");
	for (l = 0; l < 2; l++)
		for (k = 0; k < 2; k++) {
			if (puzzleRecord[l][k].score > 0)
				(void) printf("%4d%7d %-12s%9d\n",
					l, k,
					puzzleRecord[l][k].name,
					puzzleRecord[l][k].score);
		}
}
#endif

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

	for (l = 0; l < 2; l++)
		for (k = 0; k < 2; k++) {
			puzzleRecord[l][k].score = NEVER;
			(void) strncpy(puzzleRecord[l][k].name,
				NOACCESS, USER_NAME_LENGTH);
		}
}

static void
readRecords(void)
{
	FILE *fp;
	int 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++) {
			if (fscanf(fp, "%d %s\n", &n, userName) != 2) {
				(void) fprintf(stderr,
					"corrupt record, expecting integer and name for %d %d\n",
					l, k);
				(void) fclose(fp);
				return;
			}
			if (n <= puzzleRecord[l][k].score ||
					puzzleRecord[l][k].score <= NEVER) {
				puzzleRecord[l][k].score = n;
				(void) strncpy(puzzleRecord[l][k].name,
					userName, USER_NAME_LENGTH);
			}
		}
	(void) fclose(fp);
}

static void
writeRecords(void)
{
	FILE *fp;
	int 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++) {
				(void) fprintf(fp, "%d %s\n",
					puzzleRecord[l][k].score,
					puzzleRecord[l][k].name);
			}
			if (l < 1)
				(void) fprintf(fp, "\n");
		}
#if HAVE_FCNTL_H
		(void) close(lfd);
		(void) unlink(lockFile);
#endif
		(void) fclose(fp);
	}
}

static void
printRecord(Boolean orient, Boolean pairs, Boolean practice)
{
	int k = (orient) ? 1 : 0, l = (pairs) ? 1 : 0;

	if (practice) {
		(void) strncpy(recordDsp, "practice", 9);
#if 0
	} else if (tiles > MAX_TILES) {
		(void) strncpy(recordDsp, "NOT RECORDED", 13);
#endif
	} else if (puzzleRecord[l][k].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].score,
			puzzleRecord[l][k].name);
#else
		(void) sprintf(recordDsp, "%d %s",
			puzzleRecord[l][k].score,
			puzzleRecord[l][k].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)
		, Boolean pairs
#endif
		)
{
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	printState(message, msg);
	intCpy(buff, nMoves);
	printState(movesText, buff);
#else
	char titleDsp[TITLE_LENGTH] = "";
	if (pairs)
#ifdef HAVE_SNPRINTF
		(void) snprintf(titleDsp, TITLE_LENGTH, "%s: norm@ (%d/%s) - %s",
			progDsp, nMoves, recordDsp, msg);
#else
		(void) sprintf(titleDsp, "%s: norm@ (%d/%s) - %s",
			progDsp, nMoves, recordDsp, msg);
#endif
	else
#ifdef HAVE_SNPRINTF
		(void) snprintf(titleDsp, TITLE_LENGTH, "%s: ind@ (%d/%s) - %s",
			progDsp, nMoves, recordDsp, msg);
#else
		(void) sprintf(titleDsp, "%s: ind@ (%d/%s) - %s",
			progDsp, 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, Boolean orient, Boolean pairs)
{
	int k = (orient) ? 1 : 0, l = (pairs) ? 1 : 0;

	if ((counter < puzzleRecord[l][k].score ||
			puzzleRecord[l][k].score <= NEVER)) {
		readRecords();	/* Maybe its been updated by another */
		puzzleRecord[l][k].score = counter;
		(void) strncpy(puzzleRecord[l][k].name, userNameDsp,
			USER_NAME_LENGTH);
		writeRecords();
		printRecord(orient, pairs, False);
		return True;
	}
	return False;
}

#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
static int
getSpeed(int delay)
{
	return MAX_SPEED + MIN_SPEED - delay - 1;
}

static int
getDelay(int speed)
{
	return MAX_SPEED + MIN_SPEED - speed - 1;
}

static void
orientCallback(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
		XmToggleButtonCallbackStruct *cbs
#elif defined(HAVE_ATHENA)
		int state
#endif
		)
{
	Boolean orient, pairs, practice, old;
	char *picture;

#ifdef HAVE_MOTIF
	orient = cbs->set;
#elif defined(HAVE_ATHENA)
	orient = state;
#endif
	XtVaGetValues(puzzle,
		XtNorient, &old,
		XtNpairs, &pairs,
		XtNpicture, &picture,
		XtNpractice, &practice, NULL);
	if (old == orient)
		return;
	if (!orient && picture && *picture) {
#ifdef HAVE_MOTIF
		setToggle(orientToggle, old, False);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(orientToggle,
			XtNstate, old, NULL);
#endif
		return;
	}
	XtVaSetValues(puzzle,
		XtNorient, orient, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(orient, pairs, practice);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}

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

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

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

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

#if 0
#if defined(HAVE_ATHENA) && defined(USE_SPIN)
static void
UpCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int tiles;

	XtVaGetValues(puzzle,
		XtNtiles, &tiles, NULL);
	tiles++;
	setScale(tileSlider, tileSliderLabel, tiles,
		MIN_TILES, MAX_TILES, True);
	XtVaSetValues(puzzle,
		XtNtiles, tiles, NULL);
}

static void
tileDownCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int tiles;

	XtVaGetValues(puzzle,
		XtNtiles, &tiles, NULL);
	tiles--;
	if (tiles < MIN_TILES) {
		return;
	}
	setScale(tileSlider, tileSliderLabel, tiles,
		MIN_TILES, MAX_TILES, True);
	XtVaSetValues(puzzle,
		XtNtiles, tiles, NULL);
}

#else

static void
tileChangeCallback(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;
	if (!thumbScroll(callData, &tiles,
			MIN_TILES, MAX_TILES, SCROLL_SIZE)) {
		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)
	setScale(w, label, tiles, MIN_TILES, MAX_TILES, False);
#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);
}
#endif

#if defined(HAVE_ATHENA) && defined(USE_SPIN)
static void
faceUpCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int faces;

	XtVaGetValues(puzzle,
		XtNfaces, &faces, NULL);
	faces++;
	setScale(faceSlider, faceSliderLabel, faces,
		MIN_FACES, MAX_FACES, True);
	XtVaSetValues(puzzle,
		XtNfaces, faces, NULL);
}

static void
faceDownCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int faces;

	XtVaGetValues(puzzle,
		XtNfaces, &faces, NULL);
	faces--;
	if (faces < MIN_FACES) {
		return;
	}
	setScale(faceSlider, faceSliderLabel, faces,
		MIN_FACES, MAX_FACES, True);
	XtVaSetValues(puzzle,
		XtNfaces, faces, NULL);
}

#else

static void
faceChangeCallback(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;
	if (!thumbScroll(callData, &faces,
			MIN_FACES, MAX_FACES, SCROLL_SIZE)) {
		return;
	}
#endif
	XtVaGetValues(puzzle,
		XtNtiles, &tiles,
		XtNfaces, &old,
		XtNorient, &orient,
		XtNmiddle, &middle,
		XtNpractice, &practice, NULL);
	if (old == faces)
		return;
#ifdef HAVE_ATHENA
	setScale(w, label, faces, MIN_FACES, MAX_FACES, True);
#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);
}
#endif
#endif

#if defined(HAVE_ATHENA) && defined(USE_SPIN)
static void
speedUpCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int delay, speed;

	XtVaGetValues(puzzle,
		XtNdelay, &delay, NULL);
	speed = getSpeed(delay);
	speed++;
	if (speed > MAX_SPEED) {
		return;
	}
	setScale(speedSlider, speedSliderLabel, speed,
		MIN_SPEED, MAX_SPEED, True);
	delay = getDelay(speed);
	XtVaSetValues(puzzle,
		XtNdelay, delay, NULL);
}

static void
speedDownCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int delay, speed;

	XtVaGetValues(puzzle,
		XtNdelay, &delay, NULL);
	speed = getSpeed(delay);
	speed--;
	if (speed < MIN_SPEED) {
		return;
	}
	setScale(speedSlider, speedSliderLabel, speed,
		MIN_SPEED, MAX_SPEED, True);
	delay = getDelay(speed);
	XtVaSetValues(puzzle,
		XtNdelay, delay, NULL);
}

#else

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

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	speed = cbs->position;
#else
	speed = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	if (!thumbScroll(callData, &speed,
			MIN_SPEED, MAX_SPEED, SCROLL_SIZE)) {
		return;
	}
#endif
	delay = getDelay(speed);
	XtVaGetValues(puzzle,
		XtNdelay, &old, NULL);
	if (old == delay)
		return;
#ifdef HAVE_ATHENA
	setScale(w, label, speed, MIN_SPEED, MAX_SPEED, True);
#endif
	XtVaSetValues(puzzle,
		XtNdelay, delay, NULL);
}
#endif

static void
puzzlePracticeCallback(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)
	XtPopdown(practiceDialog);
#endif
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_PRACTICE, NULL);
}

static void
puzzleRandomizeCallback(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)
	XtPopdown(randomizeDialog);
#endif
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_RANDOMIZE, NULL);
}

static void
fileMenuCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int value = (int) ((size_t) clientData) + ACTION_GET;

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

static void
setSoundCheck(Widget w)
{
	Boolean sound;
	XtVaGetValues(puzzle,
		XtNsound, &sound, NULL);
#ifdef HAVE_MOTIF
	setToggle(w, sound, False);
#elif defined(HAVE_ATHENA)
	menuCheck(topLevel, w, sound);
#endif
}

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

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

static void
helpMenuCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int value = (int) ((size_t) clientData);
	Widget dialog;

#ifdef HAVE_ATHENA
	if (wmDeleteWindow == None)
		wmDeleteWindow = XInternAtom(XtDisplay(topLevel),
			"WM_DELETE_WINDOW", FALSE);
#endif
	switch (value) {
	case 0:
		dialog = descriptionDialog;
		break;
	case 1:
		dialog = featuresDialog;
		break;
	case 2:
		dialog = synopsisDialog;
		break;
	case 3:
		dialog = referencesDialog;
		break;
	case 4:
		dialog = aboutDialog;
		break;
	default:
		{
			char *buf;

			intCat(&buf, "helpMenuCallback: %d", value);
			XtWarning(buf);
			free(buf);
			return;
		}
	}
#ifdef HAVE_MOTIF
	XtManageChild(dialog);
#elif defined(HAVE_ATHENA)
	XtPopup(dialog, XtGrabNone);
	XSetWMProtocols(XtDisplay(topLevel),
		XtWindow(dialog), &wmDeleteWindow, 1);
#endif
}
#endif

static void
initialize(
#ifdef WINVER
BarrelWidget w, HBRUSH brush
#else
Widget w
#endif
)
{
	Boolean orient, pairs, practice;
	char *userName, *scoreFile;

#ifdef WINVER
	initializePuzzle(w, brush);

	w->barrel.started = FALSE;
	orient = w->barrel.orient;
	pairs = w->barrel.pairs;
	practice = w->barrel.practice;
	userName = w->barrel.userName;
	scoreFile = w->barrel.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,
		XtNorient, &orient,
		XtNpairs, &pairs,
		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
#if 0
#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
#endif
	setToggle(orientToggle, orient, False);
	setToggle(pairsToggle, pairs, False);
	setToggle(practiceToggle, practice, False);
	{
		int delay, speed;
		XtVaGetValues(w,
			XtNdelay, &delay, NULL);
		speed = getSpeed(delay);
#ifdef USE_SPIN
		XtVaSetValues(speedChanger,
			XmNposition, speed, NULL);
#else
		XmScaleSetValue(speedChanger, speed);
#endif
	}
	setSoundCheck(soundMenuItem);
#elif defined(HAVE_ATHENA)
	XtVaSetValues(orientToggle,
		XtNstate, orient, NULL);
	XtVaSetValues(pairsToggle,
		XtNstate, pairs, NULL);
	XtVaSetValues(practiceToggle,
		XtNstate, practice, NULL);
#if 0
	setScale(tileSlider, tileSliderLabel, tiles,
		MIN_TILES, MAX_TILES, False);
	setScale(faceSlider, faceSliderLabel, faces,
		MIN_FACES, MAX_FACES, True);
#endif
	{
		int delay, speed;
		XtVaGetValues(w,
			XtNdelay, &delay, NULL);
		speed = getSpeed(delay);
		setScale(speedSlider, speedSliderLabel, speed,
			MIN_SPEED, MAX_SPEED, True);
	}
	setSoundCheck(soundMenuItem);
#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(orient, pairs, practice);
	printStatus(messageDsp, movesDsp
#if !defined(HAVE_MOTIF) && !defined(HAVE_ATHENA)
		, pairs
#endif
		);
}

#ifdef WINVER
void
setPuzzle(BarrelWidget w, int reason)
#else
static void
puzzleCallback(Widget w, caddr_t clientData,
		barrelCallbackStruct *callData)
#endif
{
#ifndef WINVER
	int reason = callData->reason;
#endif
#if 0
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	int limit;
#endif
#endif
	Boolean orient, pairs, practice, cheat;

	messageDsp[0] = '\0';
#ifdef WINVER
	orient = w->barrel.orient;
	pairs = w->barrel.pairs;
	practice = w->barrel.practice;
	cheat = w->barrel.cheat;
#else
	XtVaGetValues(w,
		XtNorient, &orient,
		XtNpairs, &pairs,
		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:
#ifdef HAVE_MOTIF
		XtManageChild(practiceDialog);
#elif defined(HAVE_ATHENA)
		XtPopup(practiceDialog, XtGrabNone);
		XSetWMProtocols(XtDisplay(topLevel),
			XtWindow(practiceDialog), &wmDeleteWindow, 1);
#else
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_PRACTICE, NULL);
#endif
		break;
	case ACTION_RANDOMIZE_QUERY:
#ifdef HAVE_MOTIF
		XtManageChild(randomizeDialog);
#elif defined(HAVE_ATHENA)
		XtPopup(randomizeDialog, XtGrabNone);
		XSetWMProtocols(XtDisplay(topLevel),
			XtWindow(randomizeDialog), &wmDeleteWindow, 1);
#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
#ifdef HAVE_MOTIF
		XtManageChild(solveDialog);
#elif defined(HAVE_ATHENA)
		XtPopup(solveDialog, XtGrabNone);
		XSetWMProtocols(XtDisplay(topLevel),
			XtWindow(solveDialog), &wmDeleteWindow, 1);
#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, orient, pairs)) {
			(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(orient, pairs, practice);
#ifdef WINVER
		w->barrel.practice = practice;
		w->barrel.started = False;
#else
		XtVaSetValues(w,
			XtNpractice, practice,
			XtNstart, False, NULL);
#ifdef HAVE_MOTIF
		setToggle(practiceToggle, practice, False);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(practiceToggle,
			XtNstate, practice, NULL);
#endif
#endif
		break;
	case ACTION_RANDOMIZE:
		movesDsp = 0;
#ifdef WINVER
		w->barrel.practice = False;
		w->barrel.started = False;
#else
		XtVaSetValues(w,
			XtNpractice, False,
			XtNstart, False, NULL);
#endif
		break;
	case ACTION_ORIENTIZE:
		movesDsp = 0;
		orient = !orient;
		printRecord(orient, pairs, practice);
#ifdef WINVER
		w->barrel.orient = orient;
#else
		XtVaSetValues(w,
			XtNorient, orient, NULL);
#ifdef HAVE_MOTIF
		setToggle(orientToggle, orient, False);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(orientToggle,
			XtNstate, orient, NULL);
#endif
#endif
		break;
	case ACTION_PAIRS:
		movesDsp = 0;
		pairs = !pairs;
		printRecord(orient, pairs, practice);
#ifdef WINVER
		w->barrel.pairs = pairs;
#else
		XtVaSetValues(w,
			XtNpairs, pairs, NULL);
#ifdef HAVE_MOTIF
		setToggle(pairsToggle, pairs, False);
#elif defined(HAVE_ATHENA)
		XtVaSetValues(pairsToggle,
			XtNstate, pairs, NULL);
#endif
#endif
		break;
#if 0
	case ACTION_INCX:
		movesDsp = 0;
		tiles++;
		printRecord(tiles, faces, orient, pairs, practice);
#ifdef WINVER
		w->barrel.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)
		setScale(tileSlider, tileSliderLabel, tiles,
			MIN_TILES, MAX_TILES, False);
#endif
#endif
		break;
	case ACTION_DECX:
		movesDsp = 0;
		tiles--;
		printRecord(tiles, faces, orient, pairs, practice);
#ifdef WINVER
		w->barrel.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)
		setScale(tileSlider, tileSliderLabel, tiles,
			MIN_TILES, MAX_TILES, False);
#endif
#endif
		break;
	case ACTION_INCY:
		movesDsp = 0;
		faces++;
		printRecord(tiles, faces, orient, pairs, practice);
#ifdef WINVER
		w->barrel.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)
		setScale(faceSlider, faceSliderLabel, faces,
			MIN_FACES, MAX_FACES, True);
#endif
#endif
		break;
	case ACTION_DECY:
		movesDsp = 0;
		faces--;
		printRecord(tiles, faces, orient, pairs, practice);
#ifdef WINVER
		w->barrel.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)
		setScale(faceSlider, faceSliderLabel, faces,
			MIN_FACES, MAX_FACES, True);
#endif
#endif
		break;
#endif
	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 = getSpeed(delay);
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
			XtVaSetValues(speedChanger,
				XmNposition, speed, NULL);
#else
			XmScaleSetValue(speedChanger, speed);
#endif
#elif defined(HAVE_ATHENA)
			setScale(speedSlider, speedSliderLabel, speed,
				MIN_SPEED, MAX_SPEED, True);
#endif
		}
		return;
	case ACTION_SOUND:
		setSoundCheck(soundMenuItem);
		break;
#endif
	}
	printStatus(messageDsp, movesDsp
#if !defined(HAVE_MOTIF) && !defined(HAVE_ATHENA)
		, pairs
#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.barrel.focus) {
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_BRUSH));
			enterPuzzle(&widget);
			(void) EndPaint(hWnd, &paint);
		}
	} else {
		if (widget.barrel.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)));
			} else if (zDelta < -(WHEEL_DELTA >> 1)) {
				movePuzzleInput(&widget, cursor.x - origin.x,
					BOTTOM,
					((GetKeyState(VK_SHIFT) >> 1) ||
					(GetKeyState(VK_CAPITAL) & 1)));
			}
		}
		(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_PAIRS:
			(void) pairsPuzzle(&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));
			(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);
				(void) ReleaseDC(hWnd, widget.core.hDC);
			}
			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 XrmOptionDescRec options[] =
{
	{(char *) "-mono", (char *) "*barrel.mono", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nomono", (char *) "*barrel.mono", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-rv", (char *) "*barrel.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-reverse", (char *) "*barrel.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-norv", (char *) "*barrel.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-noreverse", (char *) "*barrel.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-fg", (char *) "*barrel.Foreground", XrmoptionSepArg, NULL},
	{(char *) "-foreground", (char *) "*barrel.Foreground", XrmoptionSepArg, NULL},
	{(char *) "-bg", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-background", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-bd", (char *) "*barrel.tileBorder", XrmoptionSepArg, NULL},
	{(char *) "-border", (char *) "*barrel.tileBorder", XrmoptionSepArg, NULL},
	{(char *) "-face0", (char *) "*barrel.faceColor0", XrmoptionSepArg, NULL},
	{(char *) "-face1", (char *) "*barrel.faceColor1", XrmoptionSepArg, NULL},
	{(char *) "-face2", (char *) "*barrel.faceColor2", XrmoptionSepArg, NULL},
	{(char *) "-face3", (char *) "*barrel.faceColor3", XrmoptionSepArg, NULL},
	{(char *) "-face4", (char *) "*barrel.faceColor4", XrmoptionSepArg, NULL},
	{(char *) "-face5", (char *) "*barrel.faceColor5", XrmoptionSepArg, NULL},
	{(char *) "-tile", (char *) "*barrel.tileColor", XrmoptionSepArg, NULL},
	{(char *) "-frame", (char *) "*barrel.frameColor", XrmoptionSepArg, NULL},
	{(char *) "-stippleFrame", (char *) "*barrel.stippleFrame", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nostippleFrame", (char *) "*barrel.stippleFrame", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-install", (char *) "*barrel.install", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-noinstall", (char *) "*barrel.install", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-picture", (char *) "*barrel.picture", XrmoptionSepArg, NULL},
	{(char *) "-delay", (char *) "*barrel.delay", XrmoptionSepArg, NULL},
	{(char *) "-sound", (char *) "*barrel.sound", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nosound", (char *) "*barrel.sound", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-bumpSound", (char *) "*barrel.bumpSound", XrmoptionSepArg, NULL},
	{(char *) "-moveSound", (char *) "*barrel.moveSound", XrmoptionSepArg, NULL},
	{(char *) "-base", (char *) "*barrel.base", XrmoptionSepArg, NULL},
	{(char *) "-fn", (char *) "*barrel.font", XrmoptionSepArg, NULL},
	{(char *) "-font", (char *) "*barrel.font", XrmoptionSepArg, NULL},
#if 0
	{(char *) "-tiles", (char *) "*barrel.tiles", XrmoptionSepArg, NULL},
	{(char *) "-faces", (char *) "*barrel.faces", XrmoptionSepArg, NULL},
#endif
	{(char *) "-orient", (char *) "*barrel.orient", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-noorient", (char *) "*barrel.orient", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-pairs", (char *) "*barrel.pairs", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nopairs", (char *) "*barrel.pairs", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-practice", (char *) "*barrel.practice", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nopractice", (char *) "*barrel.practice", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-userName", (char *) "*barrel.userName", XrmoptionSepArg, NULL},
	{(char *) "-scoreFile", (char *) "*barrel.scoreFile", XrmoptionSepArg, NULL},
	{(char *) "-scores", (char *) "*barrel.scoreOnly", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-version", (char *) "*barrel.versionOnly", XrmoptionNoArg, (char *) "TRUE"}
};

#ifdef HAVE_MOTIF
static void
soundCallback(Widget w, XtPointer clientData,
		XmToggleButtonCallbackStruct *cbs)
{
	Boolean value = cbs->set;

	XtVaSetValues(puzzle,
		XtNsound, value, NULL);
}

#elif defined(HAVE_ATHENA)
static void
puzzlePracticeCancelCallback(Widget w, XtPointer clientData,
		XtPointer callData)
{
	XtPopdown(practiceDialog);
}

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

	practiceDialog = XtCreatePopupShell(title,
		transientShellWidgetClass, topLevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog",
		dialogWidgetClass, practiceDialog,
		XtNlabel, text, NULL);
	okDialog = XtVaCreateManagedWidget("OK",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(okDialog, XtNcallback,
		puzzlePracticeCallback, dialog);
	cancelDialog = XtVaCreateManagedWidget("Cancel",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(cancelDialog, XtNcallback,
		puzzlePracticeCancelCallback, dialog);
	XtRealizeWidget(practiceDialog);
	XSetWMProtocols(XtDisplay(topLevel),
		XtWindow(practiceDialog), &wmDeleteWindow, 1);
}

static void
puzzleRandomizeCancelCallback(Widget w, XtPointer clientData,
		XtPointer callData)
{
	XtPopdown(randomizeDialog);
}

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

	randomizeDialog = XtCreatePopupShell(title,
		transientShellWidgetClass, topLevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog",
		dialogWidgetClass, randomizeDialog,
		XtNlabel, text, NULL);
	okDialog = XtVaCreateManagedWidget("OK",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(okDialog, XtNcallback,
		puzzleRandomizeCallback, dialog);
	cancelDialog = XtVaCreateManagedWidget("Cancel",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(cancelDialog, XtNcallback,
		puzzleRandomizeCancelCallback, dialog);
	XtRealizeWidget(randomizeDialog);
	XSetWMProtocols(XtDisplay(topLevel),
		XtWindow(randomizeDialog), &wmDeleteWindow, 1);
}
#endif

int
main(int argc, char **argv)
{
	int pixmapSize;
	XtAppContext appCon;
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	Widget mainPanel, controlPanel, menuBar;
	Widget movesRowCol;
	Widget speedChangerRowCol, toggleRowCol;
	Widget playMenu;
#if 0
	Widget changerRowCol;
#endif
#endif
#ifdef HAVE_MOTIF
	Widget pullDownMenu, widget;
	Widget menuBarPanel;
#if 0
	Widget tileChangerRowCol, faceChangerRowCol;
#endif
	Widget messageRowCol;
	XmString fileString, playString;
	XmString getString, writeString, quitString;
	XmString undoString, redoString, clearString;
#ifdef EXTRA
	XmString practiceString;
#endif
	XmString randomizeString, solveString;
#ifdef EXTRA
	XmString orientString, pairsString;
	XmString speedString, slowString;
#endif
	XmString soundString;
#elif defined(HAVE_ATHENA)
	XtActionsRec actions[] = {
		{(char *) "DeleteWindowProc", deleteWindowProc},
		{(char *) "ClosePopupPanel", (XtActionProc) closePopupPanel}
	};
	String fallbackResources[] = {
		(char *) "?.translations: #override <Message>WM_PROTOCOLS: DeleteWindowProc()",
		(char *) "?.TransientShell.translations: #override <Message>WM_PROTOCOLS: ClosePopupPanel()",
		NULL
	};
#if 0
	Widget tileBox, faceBox;
#endif
	Widget speedBox;
	Widget orientBox, pairsBox, practiceBox;
	Widget movesLabel, recordLabel;
	Widget w;
	Widget fileLabel, playLabel, helpLabel;
#if 0
	int tiles, faces;
#endif
	int delay;
	Boolean orient, pairs, practice;
	unsigned int i;
#endif

#ifdef __VMS
	int n;
	progDsp = strrchr(argv[0], ']');
	for (n = 0; progDsp[n] != '\0' && progDsp[n] != '.'; n++);
	progDsp[n] = '\0';
#else
	progDsp = strrchr(argv[0], '/');
#endif
	if (progDsp != NULL)
		progDsp++;
	if (progDsp == NULL)
		progDsp = argv[0];
	topLevel = XtVaAppInitialize(NULL, "XBarrel",
		options, XtNumber(options), &argc, argv,
#ifdef HAVE_ATHENA
		fallbackResources,
#else
		NULL,
#endif
		NULL);
	appCon = XtWidgetToApplicationContext(topLevel);
	if (argc != 1)
		usage(argv[0], synopsisHelp);
#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, fileMenuCallback,
		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
	orientString = XmStringCreateSimple((char *) "Oriented");
	pairsString = XmStringCreateSimple((char *) "Pairs");
	speedString = XmStringCreateSimple((char *) "Speed >");
	slowString = XmStringCreateSimple((char *) "Slow <");
#endif
	soundString = XmStringCreateSimple((char *) "Sound @");
	playMenu = XmVaCreateSimplePulldownMenu(menuBar, (char *) "playMenu",
		1, playMenuCallback,
		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, orientString, 'O', NULL, NULL,
		XmVaPUSHBUTTON, pairsString, 'i', NULL, NULL,
		XmVaPUSHBUTTON, speedString, '>', NULL, NULL,
		XmVaPUSHBUTTON, slowString, '<', NULL, NULL,
#endif
		XmVaTOGGLEBUTTON, soundString, '@', NULL, NULL, NULL);
	XmStringFree(undoString);
	XmStringFree(redoString);
	XmStringFree(clearString);
#ifdef EXTRA
	XmStringFree(practiceString);
#endif
	XmStringFree(randomizeString);
	XmStringFree(solveString);
#ifdef EXTRA
	XmStringFree(orientString);
	XmStringFree(pairsString);
	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 warning on Cygwin */
	XtVaSetValues(menuBar,
		XmNmenuHelpWidget, widget, NULL);
	widget = XtVaCreateManagedWidget("Description...",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'D', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuCallback, (char *) 0);
	widget = XtVaCreateManagedWidget("Features...",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'F', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuCallback, (char *) 1);
	widget = XtVaCreateManagedWidget("Synopsis...",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'S', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuCallback, (char *) 2);
	widget = XtVaCreateManagedWidget("References...",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'R', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuCallback, (char *) 3);
	widget = XtVaCreateManagedWidget("About...",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'A', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuCallback, (char *) 4);
	XtManageChild(menuBar);
	solveDialog = createHelp(menuBar, "Solve", (char *) solveHelp);
	practiceDialog = createQuery(topLevel, "Practice Query",
		(char *) "Are you sure you want to toggle the practice mode?",
		(XtCallbackProc) puzzlePracticeCallback);
	randomizeDialog = createQuery(topLevel, "Randomize Query",
		(char *) "Are you sure you want to randomize?",
		(XtCallbackProc) puzzleRandomizeCallback);
	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 and out of date. */
		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);
#if 0
	changerRowCol = XtVaCreateManagedWidget("changerRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	tileChangerRowCol = XtVaCreateManagedWidget("tileChangerRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef USE_SPIN
	createSpinner(tileChangerRowCol, &tileChanger,
		(char *) sizeLabel, DEFAULT_TILES,
		MIN_TILES, MAX_TILES, 2,
		(XtCallbackProc) tileChangeCallback);
#else
	createSlider(tileChangerRowCol, &tileChanger,
		(char *) sizeLabel, DEFAULT_TILES,
		MIN_TILES, MAX_TILES, 2, SCROLL_SIZE,
		(XtCallbackProc) tileChangeCallback);
#endif
	faceChangerRowCol = XtVaCreateManagedWidget("faceChangerRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef USE_SPIN
	createSpinner(faceChangerRowCol, &faceChanger,
		(char *) sizeLabel, DEFAULT_FACES,
		MIN_FACES, MAX_FACES, 1,
		(XtCallbackProc) faceChangeCallback);
#else
	createSlider(faceChangerRowCol, &faceChanger,
		(char *) sizeLabel, DEFAULT_FACES,
		MIN_FACES, MAX_FACES, 1, SCROLL_SIZE,
		(XtCallbackProc) faceChangeCallback);
#endif
#endif
	speedChangerRowCol = XtVaCreateManagedWidget("speedChangerRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef USE_SPIN
	createSpinner(speedChangerRowCol, &speedChanger,
		(char *) speedLabel, MAX_SPEED - DEFAULT_DELAY,
		MIN_SPEED, MAX_SPEED, 2,
		(XtCallbackProc) speedChangeCallback);
#else
	createSlider(speedChangerRowCol, &speedChanger,
		(char *) speedLabel, MAX_SPEED - DEFAULT_DELAY,
		MIN_SPEED, MAX_SPEED, 2, SCROLL_SIZE,
		(XtCallbackProc) speedChangeCallback);
#endif
	toggleRowCol = XtVaCreateManagedWidget("toggleRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
	orientToggle = XtVaCreateManagedWidget("Oriented",
		xmToggleButtonWidgetClass, toggleRowCol,
		XmNset, DEFAULT_ORIENT, NULL);
	XtAddCallback(orientToggle, XmNvalueChangedCallback,
		(XtCallbackProc) orientCallback, (XtPointer) NULL);
	pairsToggle = XtVaCreateManagedWidget("Pairs rigid",
		xmToggleButtonWidgetClass, toggleRowCol,
		XmNset, DEFAULT_PAIRS, NULL);
	XtAddCallback(pairsToggle, XmNvalueChangedCallback,
		(XtCallbackProc) pairsCallback, (XtPointer) NULL);
	practiceToggle = XtVaCreateManagedWidget("Practice",
		xmToggleButtonWidgetClass, toggleRowCol,
		XmNset, DEFAULT_PRACTICE, NULL);
	XtAddCallback(practiceToggle, XmNvalueChangedCallback,
		(XtCallbackProc) practiceCallback, (XtPointer) NULL);
	messageRowCol = XtVaCreateManagedWidget("messageRowCol",
		xmRowColumnWidgetClass, controlPanel, NULL);
	message = XtVaCreateManagedWidget("Play Barrel! (use mouse and keypad)",
		xmLabelWidgetClass, messageRowCol, NULL);
	puzzle = XtVaCreateManagedWidget("barrel",
		barrelWidgetClass, mainPanel, NULL);
#elif defined(HAVE_ATHENA)
	XtAppAddActions(appCon, actions, XtNumber(actions));
	createPracticeQuery((char *) "Practice Query",
		(char *) "Are you sure you want to toggle the practice mode?");
	createRandomizeQuery((char *) "Randomize Query",
		(char *) "Are you sure you want to randomize?");
	createHelp(topLevel, &solveDialog, (char *) "Auto-solve",
		(char *) solveHelp, (XtCallbackProc) closePopupPanel2);
	createHelp(topLevel, &descriptionDialog, (char *) "Description",
		(char *) descriptionHelp, (XtCallbackProc) closePopupPanel2);
	createScrollHelp(topLevel, &featuresDialog, (char *) "Features",
		(char *) featuresHelp, (XtCallbackProc) closePopupPanel2);
	createHelp(topLevel, &synopsisDialog, (char *) "Synopsis",
		(char *) synopsisHelp, (XtCallbackProc) closePopupPanel2);
	createHelp(topLevel, &referencesDialog, (char *) "References",
		(char *) referencesHelp, (XtCallbackProc) closePopupPanel2);
	createHelp(topLevel, &aboutDialog, (char *) "About",
		(char *) aboutHelp, (XtCallbackProc) closePopupPanel2);
	mainPanel = XtVaCreateManagedWidget("form",
		panedWidgetClass, topLevel, NULL);
	menuBar = XtVaCreateManagedWidget("MenuBar",
		formWidgetClass, mainPanel,
		XtNborderWidth, 1, NULL);
	createMenu(menuBar, &fileLabel, NULL,
		fileTypes, "File", numFileTypes,
		0, False, fileMenuCallback);
	playLabel = XtVaCreateManagedWidget("Play",
		menuButtonWidgetClass, menuBar,
		XtNborderWidth, 0,
		XtNfromHoriz, fileLabel, NULL);
	playMenu = XtVaCreatePopupShell("menu",
		simpleMenuWidgetClass, playLabel, NULL);
	for (i = 0; i < numPlayTypes; i++) {
		if (i == numPlayTypes - 1) {
			w = XtVaCreateManagedWidget(playTypes[i],
				smeBSBObjectClass, playMenu,
				XtNleftMargin, 20, NULL); /* for check */
			soundMenuItem = w;
		} else
			w = XtVaCreateManagedWidget(playTypes[i],
				smeBSBObjectClass, playMenu, NULL);
		XtAddCallback(w,
			XtNcallback, (XtCallbackProc) playMenuCallback,
			(XtPointer) (size_t) i);
	}
	createMenu(menuBar, &helpLabel, playLabel,
		helpTypes, "Help", numHelpTypes,
		0, False, helpMenuCallback);
	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, 32,
		XtNfromHoriz, movesLabel, NULL);
	recordLabel = XtVaCreateManagedWidget("Record",
		labelWidgetClass, movesRowCol,
		XtNborderWidth, 0,
		XtNfromHoriz, movesText, NULL);
	recordText = XtVaCreateManagedWidget("0",
		labelWidgetClass, movesRowCol,
		XtNwidth, 108,
		XtNfromHoriz, recordLabel, NULL);
#if 0
	changerRowCol = XtVaCreateManagedWidget("changerRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, movesRowCol, NULL);
	tileBox = XtVaCreateManagedWidget("tileBox",
		boxWidgetClass, changerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0, NULL);
	faceBox = XtVaCreateManagedWidget("faceBox",
		boxWidgetClass, changerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0,
		XtNfromHoriz, tileBox, NULL);
#endif
	speedChangerRowCol = XtVaCreateManagedWidget("speedChangerRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, movesRowCol, NULL);
	speedBox = XtVaCreateManagedWidget("speedBox",
		boxWidgetClass, speedChangerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0, NULL);
	toggleRowCol = XtVaCreateManagedWidget("toggleRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, speedChangerRowCol, NULL);
	orientBox = XtVaCreateManagedWidget("Oriented",
		boxWidgetClass, toggleRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0,
		XtNstate, DEFAULT_ORIENT, NULL);
	pairsBox = XtVaCreateManagedWidget("Pairs",
		boxWidgetClass, toggleRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0,
		XtNstate, DEFAULT_PAIRS,
		XtNfromHoriz, orientBox, NULL);
	practiceBox = XtVaCreateManagedWidget("Practice",
		boxWidgetClass, toggleRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0,
		XtNstate, DEFAULT_PRACTICE,
		XtNfromHoriz, pairsBox, NULL);
	message = XtVaCreateManagedWidget("Welcome",
		labelWidgetClass, controlPanel,
		XtNjustify,  XtJustifyLeft,
		XtNborderWidth, 0,
		XtNwidth, 180,
		XtNfromVert, toggleRowCol, NULL);
	puzzle = XtVaCreateManagedWidget("barrel",
		barrelWidgetClass, mainPanel,
		XtNfromVert, controlPanel, NULL);
	XtVaGetValues(puzzle,
#if 0
		XtNtiles, &tiles,
		XtNfaces, &faces,
#endif
		XtNorient, &orient,
		XtNpairs, &pairs,
		XtNpractice, &practice,
		XtNdelay, &delay, NULL);
#ifdef USE_SPIN
#if 0
	createSpinner(tileBox, &tileSliderLabel,
		tileLabel, 0, tiles, MIN_TILES, MAX_TILES, False,
		tileUpCallback, tileDownCallback);
	createSpinner(faceBox, &faceSliderLabel,
		faceLabel, 0, faces, MIN_FACES, MAX_FACES, True,
		faceUpCallback, faceDownCallback);
#endif
	createSpinner(speedBox, &speedSliderLabel,
		speedLabel, 0, getSpeed(delay), MIN_SPEED, MAX_SPEED, True,
		speedUpCallback, speedDownCallback);
#else
#if 0
	createSlider(tileBox, &tileliderLabel, &tileSlider,
		tileLabel, 0, tiles, MIN_TILES, MAX_TILES, False,
		SCROLL_SIZE, faceChangeCallback, faceChangeCallback);
	createSlider(faceBox, &faceSliderLabel, &faceSlider,
		faceLabel, 0, faces, MIN_FACES, MAX_FACES, True,
		SCROLL_SIZE, faceChangeCallback, faceChangeCallback);
#endif
	createSlider(speedBox, &speedSliderLabel, &speedSlider,
		speedLabel, 0, getSpeed(delay), MIN_SPEED, MAX_SPEED, True,
		SCROLL_SIZE, speedChangeCallback, speedChangeCallback);
#endif
	createToggle(orientBox, &orientToggle, "Oriented:", 0,
		orient, (XtCallbackProc) orientCallback);
	createToggle(pairsBox, &pairsToggle, "Pairs:", 0,
		pairs, (XtCallbackProc) pairsCallback);
	createToggle(practiceBox, &practiceToggle, "Practice:", 0,
		practice, (XtCallbackProc) practiceCallback);
	XtRealizeWidget(topLevel);
	if (wmDeleteWindow == None)
		wmDeleteWindow = XInternAtom(XtDisplay(topLevel),
			"WM_DELETE_WINDOW", FALSE);
	XSetWMProtocols(XtDisplay(topLevel), XtWindow(topLevel),
		&wmDeleteWindow, 1);
#else
	puzzle = XtVaCreateManagedWidget("barrel",
		barrelWidgetClass, 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) puzzleCallback, (XtPointer) NULL);
#ifdef HAVE_MOTIF
	updateToggle(playMenu, &soundMenuItem,
		False,
#ifdef EXTRA
		10,
#else
		5,
#endif
		(XtCallbackProc) soundCallback);
	descriptionDialog = createHelp(menuBar, (char *) "Description",
		(char *) descriptionHelp);
	featuresDialog = createScrollHelp(menuBar, (char *) "Features",
		(char *) featuresHelp, pixmap);
	synopsisDialog = createHelp(menuBar, (char *) "Synopsis",
		(char *) synopsisHelp);
	referencesDialog = createHelp(menuBar, (char *) "References",
		(char *) referencesHelp);
	aboutDialog = createHelp(menuBar, (char *) "About",
		(char *) aboutHelp);
#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));
#ifdef HAVE_EDITRES
	XtAddEventHandler(topLevel, (EventMask) 0, TRUE,
		(XtEventHandler) _XEditResCheckMessages, NULL);
#endif
	XtAppMainLoop(appCon);

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