/*
 * @(#)xcubes.c
 *
 * Copyright 1993 - 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 Cubes */

#ifndef WINVER
#include "version.h"
static const char aboutHelp[] = {
"Cubes 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"
"[-block {color}] [-text {color}] [-frame {color}]\n"
"[-[no]stippleFrame] [-[no]install] [-picture {filename}]\n"
"[-delay msecs] [-[no]sound] [-bumpSound {filename}]\n"
"[-dripSound {filename}] [-{font|fn} {fontname}]\n"
"[-size{X|Y|Z} {int}] [-base {int}] [-userName {string}]\n"
"[-scoreFile {filename}] [-scores] [-version]"
};
#endif

#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA) || defined(WINVER)
static const char descriptionHelp[] = {
"A 3D sliding block puzzle.  The cubes represented are  "
"flattened out on the plane.  If the Blocks Z changer is\n"
"greater than 1, then each group of boxes is a layer of the "
"puzzle.  If the Blocks Z changer = 1, then this is a\n"
"simple 15 block puzzle.  The 15 puzzle was originally made "
"around 1880 by Noyes Chapman (the 14-15 puzzle of Sam\n"
"Loyd was made soon after.)  Similar 3D puzzles include BloxBox; "
"Qrazy Qube (2x2x2) by P. Hein of Denmark and\n"
"Varikon Box 'L (3x3x3) (Hungary) and Mad Marbles (3x3x3) by "
"Toys & Games International USA."
};

static const char featuresHelp[] = {
"Click \"mouse-left\" button to move a block.  Clicks on "
"a space, or clicks on blocks that are not in line\n"
"with a space, will not move the blocks.  Notice, one can move "
"more than one block at a time by clicking\n"
"on the block farthest from the space but still in line "
"with the space.  Since you only have a 2-D screen\n"
"the next level the down is either the box to the right of "
"the current box or the bottom of the current\n"
"box.\n"
"\n"
"Click \"mouse-right\" button, or press \"C\" or \"c\" "
"keys, to clear the puzzle.\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 \"Z\" or \"z\" keys to randomize the puzzle.  New records "
"can only be set from a cleared state.\n"
"\n"
"Press \"S\" or \"s\" keys to start the auto-solver.  Only "
"works where z = 1.\n"
"\n"
"Press \"I\" or \"i\" keys to move a block in.\n"
"\n"
"Press \"O\" or \"o\" keys to move a block out.\n"
"\n"
"Press \">\" or \".\" keys to speed up the movement of blocks.\n"
"\n"
"Press \"<\" or \",\" keys to slow down the movement of blocks.\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 Cubes as:\n"
"  /    Out\n"
"  8    Up\n"
"  ^\n"
"4<5>6  Left, In, Right\n"
"  v\n"
"  2    Down\n"
"\n"
"The control key allows you to change the complexity of "
"xcubes.  Hold down control key and use the keypad\n"
"or arrow keys to reduce or enlarge puzzle complexity."
};

static const char referencesHelp[] = {
"L. E. Horden, Sliding Piece Puzzles (Recreations in "
"Mathematics Series), Oxford University Press 1986,\n"
"pp 1, 157-159.\n"
"Jerry Slocum & Jack Botermans, Puzzles Old & New (How to Make "
"and Solve Them), University of Washington\n"
"Press, Seattle 1987, p 126, 127."
};
#endif

static const char solveHelp[] = {
"Auto-solver: sorry, only implemented where x = 1 or y = 1 or z = 1."
};

#include "file.h"
#ifdef WINVER
#include "CubesP.h"
#define TITLE "wcubes"

static CubesRec 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->cubes.started = b
#else
#include "xwin.h"
#include "xgui.h"
#define SET_STARTED(w,b) XtVaSetValues(w, XtNstart, b, NULL)
#include "Cubes.h"
#ifdef HAVE_XPM
#include <X11/xpm.h>
#ifdef CONSTPIXMAPS
#include "icons/16x16/cubes.xpm"
#include "icons/22x22/cubes.xpm"
#include "icons/24x24/cubes.xpm"
#include "icons/32x32/cubes.xpm"
#include "icons/48x48/cubes.xpm"
#include "icons/64x64/cubes.xpm"
#else
#include "pixmaps/16x16/cubes.xpm"
#include "pixmaps/22x22/cubes.xpm"
#include "pixmaps/24x24/cubes.xpm"
#include "pixmaps/32x32/cubes.xpm"
#include "pixmaps/48x48/cubes.xpm"
#include "pixmaps/64x64/cubes.xpm"
#endif
#define RESIZE_XPM(s) ((char **) (((s)<=32)?\
(((s)<=22)?(((s)<=16)?cubes_16x16:cubes_22x22):\
(((s)<=24)?cubes_24x24:cubes_32x32)):\
(((s)<=48)?cubes_48x48:cubes_64x64)))
#endif
#include "pixmaps/64x64/cubes.xbm"
#define DEFINE_XBM (char *) cubes_64x64_bits, cubes_64x64_width, cubes_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 "cubes.scores"
#endif

#define MAX_BLOCKS 8
#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[MAX_BLOCKS - MIN_BLOCKS + 1]

[MAX_BLOCKS - MIN_BLOCKS + 1][MAX_BLOCKS - MIN_BLOCKS + 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 soundMenuItem;
static Widget clearDialog, solveDialog;
static Widget descriptionDialog, featuresDialog;
static Widget synopsisDialog, referencesDialog, aboutDialog;
static char buff[MESSAGE_LENGTH];
static const char *blockLabels[] =
{
	"Blocks X:",
	"Blocks Y:",
	"Blocks Z:"
};
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
static Widget blockXChanger, blockYChanger, blockZChanger;
static Widget speedChanger;
#elif defined(HAVE_ATHENA)
static Widget blockXSlider, blockYSlider, blockZSlider, speedSlider;
static Widget blockXSliderLabel, blockYSliderLabel, blockZSliderLabel;
static Widget speedSliderLabel;
static const char *fileTypes[] =
{
	"Get",
	"Write",
	"Exit"
};
#define numFileTypes (sizeof(fileTypes)/sizeof(fileTypes[0]))
static const char *playTypes[] =
{
	"Undo",
	"Redo",
	"Clear",
	"Randomize",
	"Auto-solve",
#ifdef EXTRA
	"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];
static Boolean randomized = False;
#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 i, j, k;

	(void) printf("   CUBES  HALL OF FAME\n\n");
	(void) printf("Z   Y   X USER            MOVES\n");
	for (i = 0; i < MAX_BLOCKS - MIN_BLOCKS + 1; i++)
		for (j = i; j < MAX_BLOCKS - MIN_BLOCKS + 1; j++)
			for (k = j; k < MAX_BLOCKS - MIN_BLOCKS + 1; k++) {
				if (puzzleRecord[k][j][i].score > 0)
					(void) printf("%1d%4d%4d %-12s%9d\n",
						i + 1, j + 1, k + 1,
						puzzleRecord[k][j][i].name,
						puzzleRecord[k][j][i].score);
			}
}
#endif

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

	for (i = 0; i < MAX_BLOCKS - MIN_BLOCKS + 1; i++)
		for (j = i; j < MAX_BLOCKS - MIN_BLOCKS + 1; j++)
			for (k = j; k < MAX_BLOCKS - MIN_BLOCKS + 1; k++) {
				puzzleRecord[k][j][i].score = puzzleRecord[k][i][j].score =
					puzzleRecord[j][k][i].score = puzzleRecord[j][i][k].score =
					puzzleRecord[i][k][j].score = puzzleRecord[i][j][k].score = NEVER;
				(void) strncpy(puzzleRecord[k][j][i].name,
					NOACCESS, USER_NAME_LENGTH);
				(void) strncpy(puzzleRecord[k][i][j].name,
					NOACCESS, USER_NAME_LENGTH);
				(void) strncpy(puzzleRecord[j][k][i].name,
					NOACCESS, USER_NAME_LENGTH);
				(void) strncpy(puzzleRecord[j][i][k].name,
					NOACCESS, USER_NAME_LENGTH);
				(void) strncpy(puzzleRecord[i][k][j].name,
					NOACCESS, USER_NAME_LENGTH);
				(void) strncpy(puzzleRecord[i][j][k].name,
					NOACCESS, USER_NAME_LENGTH);
			}
}

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

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

static void
printRecord(int sizeX, int sizeY, int sizeZ)
{
	int i = sizeX - MIN_BLOCKS, j = sizeY - MIN_BLOCKS, k = sizeZ - MIN_BLOCKS;

	if (sizeX > MAX_BLOCKS || sizeY > MAX_BLOCKS || sizeZ > MAX_BLOCKS) {
		(void) strncpy(recordDsp, "NOT RECORDED", 13);
	} else if (puzzleRecord[i][j][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[i][j][k].score,
			puzzleRecord[i][j][k].name);
#else
		(void) sprintf(recordDsp, "%d %s",
			puzzleRecord[i][j][k].score,
			puzzleRecord[i][j][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)
		, int sizeX, int sizeY, int sizeZ
#endif
		)
{
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	printState(message, msg);
	intCpy(buff, nMoves);
	printState(movesText, buff);
#else
	char titleDsp[TITLE_LENGTH] = "";
#ifdef HAVE_SNPRINTF
	(void) snprintf(titleDsp, TITLE_LENGTH,
		"%s: %dx%dx%d@ (%d/%s) - %s",
		progDsp, sizeX, sizeY, sizeZ, nMoves, recordDsp, msg);
#else
	(void) sprintf(titleDsp,
		"%s: %dx%dx%d@ (%d/%s) - %s",
		progDsp, sizeX, sizeY, sizeZ, 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 sizeX, int sizeY, int sizeZ)
{
	int i = sizeX - MIN_BLOCKS, j = sizeY - MIN_BLOCKS, k = sizeZ - MIN_BLOCKS;

	if (sizeX <= MAX_BLOCKS && sizeY <= MAX_BLOCKS && sizeZ <= MAX_BLOCKS &&
			(counter < puzzleRecord[i][j][k].score ||
			puzzleRecord[i][j][k].score <= NEVER)) {
		readRecords();	/* Maybe its been updated by another */

		puzzleRecord[i][j][k].score = puzzleRecord[i][k][j].score =
			puzzleRecord[j][i][k].score =
			puzzleRecord[j][k][i].score =
			puzzleRecord[k][i][j].score =
			puzzleRecord[k][j][i].score =
			counter;
		(void) strncpy(puzzleRecord[i][j][k].name, userNameDsp,
			USER_NAME_LENGTH);
		(void) strncpy(puzzleRecord[i][k][j].name, userNameDsp,
			USER_NAME_LENGTH);
		(void) strncpy(puzzleRecord[j][i][k].name, userNameDsp,
			USER_NAME_LENGTH);
		(void) strncpy(puzzleRecord[j][k][i].name, userNameDsp,
			USER_NAME_LENGTH);
		(void) strncpy(puzzleRecord[k][i][j].name, userNameDsp,
			USER_NAME_LENGTH);
		(void) strncpy(puzzleRecord[k][j][i].name, userNameDsp,
			USER_NAME_LENGTH);
		writeRecords();
		printRecord(sizeX, sizeY, sizeZ);
		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;
}

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

	XtVaGetValues(puzzle,
		XtNsizeX, &sizeX, NULL);
	sizeX++;
	setScale(blockXSlider, blockXSliderLabel, sizeX,
		MIN_BLOCKS, MAX_BLOCKS, True);
	XtVaSetValues(puzzle,
		XtNsizeX, sizeX, NULL);
}

static void
blockXDownCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int sizeX;

	XtVaGetValues(puzzle,
		XtNsizeX, &sizeX, NULL);
	sizeX--;
	if (sizeX < MIN_BLOCKS) {
		return;
	}
	setScale(blockXSlider, blockXSliderLabel, sizeX,
		MIN_BLOCKS, MAX_BLOCKS, True);
	XtVaSetValues(puzzle,
		XtNsizeX, sizeX, NULL);
}

#else

static void
blockXChangeCallback(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XmSpinBoxCallbackStruct *cbs
#else
		XmScaleCallbackStruct *cbs
#endif
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
	int sizeX, sizeY, sizeZ, old;

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	int limit;
	sizeX = cbs->position;
#else
	sizeX = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	if (!thumbScroll(callData, &sizeX,
			MIN_BLOCKS, MAX_BLOCKS, SCROLL_SIZE)) {
		return;
	}
#endif
	XtVaGetValues(puzzle,
		XtNsizeX, &old,
		XtNsizeY, &sizeY,
		XtNsizeZ, &sizeZ, NULL);
	if (old == sizeX)
		return;
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	XtVaGetValues(blockXChanger,
		XmNmaximumValue, &limit, NULL);
	if (sizeX >= limit)
		XtVaSetValues(blockXChanger,
			XmNmaximumValue, sizeX + 1,
			XmNposition, sizeX, NULL);
#elif defined(HAVE_ATHENA)
	setScale(w, label, sizeX, MIN_BLOCKS, MAX_BLOCKS, False);
#endif
	/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, sizeX - old);*/
	XtVaSetValues(puzzle,
		XtNsizeX, sizeX, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(sizeX, sizeY, sizeZ);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}
#endif

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

	XtVaGetValues(puzzle,
		XtNsizeY, &sizeY, NULL);
	sizeY++;
	setScale(blockYSlider, blockYSliderLabel, sizeY,
		MIN_BLOCKS, MAX_BLOCKS, True);
	XtVaSetValues(puzzle,
		XtNsizeY, sizeY, NULL);
}

static void
blockYDownCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int sizeY;

	XtVaGetValues(puzzle,
		XtNsizeY, &sizeY, NULL);
	sizeY--;
	if (sizeY < MIN_BLOCKS) {
		return;
	}
	setScale(blockYSlider, blockYSliderLabel, sizeY,
		MIN_BLOCKS, MAX_BLOCKS, True);
	XtVaSetValues(puzzle,
		XtNsizeY, sizeY, NULL);
}

#else

static void
blockYChangeCallback(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XmSpinBoxCallbackStruct *cbs
#else
		XmScaleCallbackStruct *cbs
#endif
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
	int sizeX, sizeY, sizeZ, old;

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	int limit;
	sizeY = cbs->position;
#else
	sizeY = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	if (!thumbScroll(callData, &sizeY,
			MIN_BLOCKS, MAX_BLOCKS, SCROLL_SIZE)) {
		return;
	}
#endif
	XtVaGetValues(puzzle,
		XtNsizeX, &sizeX,
		XtNsizeY, &old,
		XtNsizeZ, &sizeZ, NULL);
	if (old == sizeY)
		return;
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	XtVaGetValues(blockYChanger,
		XmNmaximumValue, &limit, NULL);
	if (sizeY >= limit)
		XtVaSetValues(blockYChanger,
			XmNmaximumValue, sizeY + 1,
			XmNposition, sizeY, NULL);
#elif defined(HAVE_ATHENA)
	setScale(w, label, sizeY, MIN_BLOCKS, MAX_BLOCKS, False);
#endif
	/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, sizeY - old);*/
	XtVaSetValues(puzzle,
		XtNsizeY, sizeY, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(sizeX, sizeY, sizeZ);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}
#endif

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

	XtVaGetValues(puzzle,
		XtNsizeZ, &sizeZ, NULL);
	sizeZ++;
	setScale(blockZSlider, blockZSliderLabel, sizeZ,
		MIN_BLOCKS, MAX_BLOCKS, True);
	XtVaSetValues(puzzle,
		XtNsizeZ, sizeZ, NULL);
}

static void
blockZDownCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	int sizeZ;

	XtVaGetValues(puzzle,
		XtNsizeZ, &sizeZ, NULL);
	sizeZ--;
	if (sizeZ < MIN_BLOCKS) {
		return;
	}
	setScale(blockZSlider, blockZSliderLabel, sizeZ,
		MIN_BLOCKS, MAX_BLOCKS, True);
	XtVaSetValues(puzzle,
		XtNsizeZ, sizeZ, NULL);
}

#else

static void
blockZChangeCallback(Widget w, XtPointer clientData,
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XmSpinBoxCallbackStruct *cbs
#else
		XmScaleCallbackStruct *cbs
#endif
#elif defined(HAVE_ATHENA)
		XtPointer callData
#endif
		)
{
	int sizeX, sizeY, sizeZ, old;

#ifdef HAVE_MOTIF
#ifdef USE_SPIN
	int limit;
	sizeZ = cbs->position;
#else
	sizeZ = cbs->value;
#endif
#elif defined(HAVE_ATHENA)
	Widget label = (Widget) clientData;
	if (!thumbScroll(callData, &sizeZ,
			MIN_BLOCKS, MAX_BLOCKS, SCROLL_SIZE)) {
		return;
	}
#endif
	XtVaGetValues(puzzle,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY,
		XtNsizeZ, &old, NULL);
	if (old == sizeZ)
		return;
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	XtVaGetValues(blockZChanger,
		XmNmaximumValue, &limit, NULL);
	if (sizeZ >= limit)
		XtVaSetValues(blockZChanger,
			XmNmaximumValue, sizeZ + 1,
			XmNposition, sizeZ, NULL);
#elif defined(HAVE_ATHENA)
	setScale(w, label, sizeZ, MIN_BLOCKS, MAX_BLOCKS, False);
#endif
	/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, sizeZ - old);*/
	XtVaSetValues(puzzle,
		XtNsizeZ, sizeZ, NULL);
	movesDsp = 0;
	intCpy(buff, movesDsp);
	printState(movesText, buff);
	printRecord(sizeX, sizeY, sizeZ);
	messageDsp[0] = '\0';
	printState(message, messageDsp);
}
#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
puzzleClearCallback(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(clearDialog);
#endif
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_CLEAR, 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_SPEED)
		value += ACTION_SOUND - ACTION_SPEED;
#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
CubesWidget w, HBRUSH brush
#else
Widget w
#endif
)
{
	int sizeX, sizeY, sizeZ;
	char *userName, *scoreFile;

#ifdef WINVER
	initializePuzzle(w, brush);

	sizeX = w->cubes.sizeX;
	sizeY = w->cubes.sizeY;
	sizeZ = w->cubes.sizeZ;
	userName = w->cubes.userName;
	scoreFile = w->cubes.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,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY,
		XtNsizeZ, &sizeZ,
		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
#ifdef USE_SPIN
	{
		int limit;
		XtVaGetValues(blockXChanger,
			XmNmaximumValue, &limit, NULL);
		if (sizeX >= limit)
			XtVaSetValues(blockXChanger,
				XmNposition, sizeX,
				XmNmaximumValue, sizeX + 1, NULL);
		else
			XtVaSetValues(blockXChanger,
				XmNposition, sizeX, NULL);
		XtVaGetValues(blockYChanger,
			XmNmaximumValue, &limit, NULL);
		if (sizeY >= limit)
			XtVaSetValues(blockYChanger,
				XmNposition, sizeY,
				XmNmaximumValue, sizeY + 1, NULL);
		else
			XtVaSetValues(blockYChanger,
				XmNposition, sizeY, NULL);
		XtVaGetValues(blockZChanger,
			XmNmaximumValue, &limit, NULL);
		if (sizeZ >= limit)
			XtVaSetValues(blockZChanger,
				XmNposition, sizeZ,
				XmNmaximumValue, sizeZ + 1, NULL);
		else
			XtVaSetValues(blockZChanger,
				XmNposition, sizeZ, NULL);
	}
#else
	if (sizeX > MAX_BLOCKS)
		XtVaSetValues(blockXChanger,
			XmNmaximum, sizeX, NULL);
	XmScaleSetValue(blockXChanger, sizeX);
	if (sizeY > MAX_BLOCKS)
		XtVaSetValues(blockYChanger,
			XmNmaximum, sizeY, NULL);
	XmScaleSetValue(blockYChanger, sizeY);
	if (sizeZ > MAX_BLOCKS)
		XtVaSetValues(blockZChanger,
			XmNmaximum, sizeZ, NULL);
	XmScaleSetValue(blockZChanger, sizeZ);
#endif
	{
		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)
	setScale(blockXSlider, blockXSliderLabel, sizeX,
		MIN_BLOCKS, MAX_BLOCKS, False);
	setScale(blockYSlider, blockYSliderLabel, sizeY,
		MIN_BLOCKS, MAX_BLOCKS, False);
	setScale(blockZSlider, blockZSliderLabel, sizeZ,
		MIN_BLOCKS, MAX_BLOCKS, False);
	{
		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(sizeX, sizeY, sizeZ);
	printStatus(messageDsp, movesDsp
#if !defined(HAVE_MOTIF) && !defined(HAVE_ATHENA)
		, sizeX, sizeY, sizeZ
#endif
		);
}

/*
#ifndef WINVER
static void
reformatPuzzle(int *sizeX, int *sizeY, int *sizeZ, int vector)
{
	if (vector <= 0) {
		if (*sizeX < *sizeY)
			*sizeY = *sizeX;
		if (*sizeY < *sizeZ)
			*sizeZ = *sizeY;
	} else if (vector > 0) {
		if (*sizeZ > *sizeY)
			*sizeY = *sizeZ;
		if (*sizeY > *sizeX)
			*sizeX = *sizeY;
	}
}
#endif
*/

#ifdef WINVER
void
setPuzzle(CubesWidget w, int reason)
#else
static void
puzzleCallback(Widget w, caddr_t clientData,
		cubesCallbackStruct *callData)
#endif
{
#ifndef WINVER
	int reason = callData->reason;
#endif
#if defined(HAVE_MOTIF) && defined(USE_SPIN)
	int limit;
#endif
	int sizeX, sizeY, sizeZ;
	Boolean cheat;

	messageDsp[0] = '\0';
#ifdef WINVER
	sizeX = w->cubes.sizeX;
	sizeY = w->cubes.sizeY;
	sizeZ = w->cubes.sizeZ;
	cheat = w->cubes.cheat;
	/*reformatPuzzle(w, 0);*/
#else
	XtVaGetValues(w,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY,
		XtNsizeZ, &sizeZ,
		XtNcheat, &cheat, NULL);
	/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, 0);
	XtVaSetValues(w,
		XtNsizeX, sizeX,
		XtNsizeY, sizeY,
		XtNsizeZ, sizeZ, 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;
#if !defined(WINVER) && defined(CLEAR_QUERY)
	case ACTION_CLEAR_QUERY:
#ifdef HAVE_MOTIF
		XtManageChild(clearDialog);
#elif defined(HAVE_ATHENA)
		XtPopup(clearDialog, XtGrabNone);
		XSetWMProtocols(XtDisplay(topLevel),
			XtWindow(clearDialog), &wmDeleteWindow, 1);
#else
		XtVaSetValues(puzzle,
			XtNmenu, ACTION_CLEAR, 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:
	case ACTION_RESET:
		movesDsp = 0;
		randomized = False;
		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, "Clear to start",
			MESSAGE_LENGTH);
		break;
	case ACTION_MOVED:
		movesDsp++;
		SET_STARTED(w, True);
		break;
	case ACTION_SOLVED:
		if (cheat) {
			(void) strncpy(messageDsp, "No cheating ", 13);
			(void) strncat(messageDsp, userNameDsp, USER_NAME_LENGTH);
			(void) strncat(messageDsp, "!!", 3);
		} else if (!randomized && handleSolved(movesDsp,
				sizeX, sizeY, sizeZ)) {
			(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_RANDOMIZE:
		movesDsp = 0;
		randomized = True;
		SET_STARTED(w, False);
		break;
	case ACTION_INCX:
		movesDsp = 0;
		sizeX++;
#ifdef WINVER
		w->cubes.sizeX = sizeX;
		/*reformatPuzzle(w, 1);*/
#else
		XtVaSetValues(w,
			XtNsizeX, sizeX, NULL);
		/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, 1);*/
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XtVaGetValues(blockXChanger,
			XmNmaximumValue, &limit, NULL);
		if (sizeX >= limit)
			XtVaSetValues(blockXChanger,
				XmNmaximumValue, sizeX + 1,
				XmNposition, sizeX, NULL);
		else
			XtVaSetValues(blockXChanger,
				XmNposition, sizeX, NULL);
#else
		if (sizeX > MAX_BLOCKS)
			XtVaSetValues(blockXChanger,
				XmNmaximum, sizeX, NULL);
		XmScaleSetValue(blockXChanger, sizeX);
#endif
#elif defined(HAVE_ATHENA)
		setScale(blockXSlider, blockXSliderLabel, sizeX,
			MIN_BLOCKS, MAX_BLOCKS, False);
#endif
#endif
		printRecord(sizeX, sizeY, sizeZ);
		break;
	case ACTION_DECX:
		movesDsp = 0;
		sizeX--;
#ifdef WINVER
		w->cubes.sizeX = sizeX;
		/*reformatPuzzle(w, -1);*/
#else
		XtVaSetValues(w,
			XtNsizeX, sizeX, NULL);
		/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, -1);*/
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		if (sizeX > MAX_BLOCKS)
			XtVaSetValues(blockXChanger,
				XmNmaximumValue, sizeX,
				XmNposition, sizeX, NULL);
		else
			XtVaSetValues(blockXChanger,
				XmNposition, sizeX, NULL);
#else
		if (sizeX > MAX_BLOCKS)
			XtVaSetValues(blockXChanger,
				XmNmaximum, sizeX, NULL);
		XmScaleSetValue(blockXChanger, sizeX);
#endif
#elif defined(HAVE_ATHENA)
		setScale(blockXSlider, blockXSliderLabel, sizeX,
			MIN_BLOCKS, MAX_BLOCKS, False);
#endif
#endif
		printRecord(sizeX, sizeY, sizeZ);
		break;
	case ACTION_INCY:
		movesDsp = 0;
		sizeY++;
#ifdef WINVER
		w->cubes.sizeY = sizeY;
		/*reformatPuzzle(w, 1);*/
#else
		XtVaSetValues(w,
			XtNsizeY, sizeY, NULL);
		/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, 1);*/
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XtVaGetValues(blockYChanger,
			XmNmaximumValue, &limit, NULL);
		if (sizeY >= limit)
			XtVaSetValues(blockYChanger,
				XmNmaximumValue, sizeY + 1,
				XmNposition, sizeY, NULL);
		else
			XtVaSetValues(blockYChanger,
				XmNposition, sizeY, NULL);
#else
		if (sizeY > MAX_BLOCKS)
			XtVaSetValues(blockYChanger,
				XmNmaximum, sizeY, NULL);
		XmScaleSetValue(blockYChanger, sizeY);
#endif
#elif defined(HAVE_ATHENA)
		setScale(blockYSlider, blockYSliderLabel, sizeY,
			MIN_BLOCKS, MAX_BLOCKS, False);
#endif
#endif
		printRecord(sizeX, sizeY, sizeZ);
		break;
	case ACTION_DECY:
		movesDsp = 0;
		sizeY--;
#ifdef WINVER
		w->cubes.sizeY = sizeY;
		/*reformatPuzzle(w, -1);*/
#else
		XtVaSetValues(w,
			XtNsizeY, sizeY, NULL);
		/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, -1);*/
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		if (sizeY > MAX_BLOCKS)
			XtVaSetValues(blockYChanger,
				XmNmaximumValue, sizeY,
				XmNposition, sizeY, NULL);
		else
			XtVaSetValues(blockYChanger,
				XmNposition, sizeY, NULL);
#else
		if (sizeY > MAX_BLOCKS)
			XtVaSetValues(blockYChanger,
				XmNmaximum, sizeY, NULL);
		XmScaleSetValue(blockYChanger, sizeY);
#endif
#elif defined(HAVE_ATHENA)
		setScale(blockYSlider, blockYSliderLabel, sizeY,
			MIN_BLOCKS, MAX_BLOCKS, False);
#endif
#endif
		printRecord(sizeX, sizeY, sizeZ);
		break;
	case ACTION_INCZ:
		movesDsp = 0;
		sizeZ++;
#ifdef WINVER
		w->cubes.sizeZ = sizeZ;
		/*reformatPuzzle(w, 1);*/
#else
		XtVaSetValues(w,
			XtNsizeZ, sizeZ, NULL);
		/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, 1);*/
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		XtVaGetValues(blockZChanger,
			XmNmaximumValue, &limit, NULL);
		if (sizeZ >= limit)
			XtVaSetValues(blockZChanger,
				XmNmaximumValue, sizeZ + 1,
				XmNposition, sizeZ, NULL);
		else
			XtVaSetValues(blockZChanger,
				XmNposition, sizeZ, NULL);
#else
		if (sizeZ > MAX_BLOCKS)
			XtVaSetValues(blockZChanger,
				XmNmaximum, sizeZ, NULL);
		XmScaleSetValue(blockZChanger, sizeZ);
#endif
#elif defined(HAVE_ATHENA)
		setScale(blockZSlider, blockZSliderLabel, sizeZ,
			MIN_BLOCKS, MAX_BLOCKS, False);
#endif
#endif
		printRecord(sizeX, sizeY, sizeZ);
		break;
	case ACTION_DECZ:
		movesDsp = 0;
		sizeZ--;
#ifdef WINVER
		w->cubes.sizeZ = sizeZ;
		/*reformatPuzzle(w, -1);*/
#else
		XtVaSetValues(w,
			XtNsizeZ, sizeZ, NULL);
		/*reformatPuzzle(&sizeX, &sizeY, &sizeZ, -1);*/
#ifdef HAVE_MOTIF
#ifdef USE_SPIN
		if (sizeZ > MAX_BLOCKS)
			XtVaSetValues(blockZChanger,
				XmNmaximumValue, sizeZ,
				XmNposition, sizeZ, NULL);
		else
			XtVaSetValues(blockZChanger,
				XmNposition, sizeZ, NULL);
#else
		if (sizeZ > MAX_BLOCKS)
			XtVaSetValues(blockZChanger,
				XmNmaximum, sizeZ, NULL);
		XmScaleSetValue(blockZChanger, sizeY);
#endif
#elif defined(HAVE_ATHENA)
		setScale(blockZSlider, blockZSliderLabel, sizeZ,
			MIN_BLOCKS, MAX_BLOCKS, False);
#endif
#endif
		printRecord(sizeX, sizeY, sizeZ);
		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 = 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)
		, sizeX, sizeY, sizeZ
#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;

	widget.core.hWnd = hWnd;
	if (GetFocus()) {
		if (!widget.cubes.focus) {
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_BRUSH));
			enterPuzzle(&widget);
			(void) EndPaint(hWnd, &paint);
		}
	} else {
		if (widget.cubes.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));
		clearPuzzle(&widget);
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
	case WM_LBUTTONDOWN:
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		selectPuzzle(&widget, LOWORD(lParam), HIWORD(lParam));
		(void) ReleaseDC(hWnd, widget.core.hDC);
		break;
	case WM_LBUTTONUP:
		widget.core.hDC = GetDC(hWnd);
		(void) SelectObject(widget.core.hDC,
			GetStockObject(NULL_PEN));
		releasePuzzle(&widget);
		(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)) {
				movePuzzle(&widget, TOP,
					(GetKeyState(VK_CONTROL) >> 1) ? 1 : 0);
				if (GetKeyState(VK_CONTROL) >> 1) {
					sizePuzzle(&widget);
					(void) InvalidateRect(hWnd, NULL, TRUE);
				}
			} else if (zDelta < -(WHEEL_DELTA >> 1)) {
				movePuzzle(&widget, BOTTOM,
					(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_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_RIGHT:
		case ACTION_LEFT:
		case ACTION_UP:
		case ACTION_DOWN:
		case ACTION_OUT:
		case ACTION_IN:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			(void) movePuzzle(&widget,
				(int) LOWORD(wParam) - ACTION_UP, FALSE);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_INCX:
		case ACTION_DECX:
		case ACTION_INCY:
		case ACTION_DECY:
		case ACTION_INCZ:
		case ACTION_DECZ:
			if (movePuzzle(&widget,
					(int) LOWORD(wParam) - ACTION_INCY,
					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 + 4, 512 + 10 + 4 + 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 *) "*cubes.mono", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nomono", (char *) "*cubes.mono", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-rv", (char *) "*cubes.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-reverse", (char *) "*cubes.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-norv", (char *) "*cubes.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-noreverse", (char *) "*cubes.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-fg", (char *) "*cubes.foreground", XrmoptionSepArg, NULL},
	{(char *) "-foreground", (char *) "*cubes.foreground", XrmoptionSepArg, NULL},
	{(char *) "-bg", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-background", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-block", (char *) "*cubes.blockColor", XrmoptionSepArg, NULL},
	{(char *) "-text", (char *) "*cubes.textColor", XrmoptionSepArg, NULL},
	{(char *) "-frame", (char *) "*cubes.frameColor", XrmoptionSepArg, NULL},
	{(char *) "-stippleFrame", (char *) "*cubes.stippleFrame", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nostippleFrame", (char *) "*cubes.stippleFrame", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-install", (char *) "*cubes.install", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-noinstall", (char *) "*cubes.install", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-picture", (char *) "*cubes.picture", XrmoptionSepArg, NULL},
	{(char *) "-delay", (char *) "*cubes.delay", XrmoptionSepArg, NULL},
	{(char *) "-sound", (char *) "*cubes.sound", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nosound", (char *) "*cubes.sound", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-bumpSound", (char *) "*cubes.bumpSound", XrmoptionSepArg, NULL},
	{(char *) "-dripSound", (char *) "*cubes.dripSound", XrmoptionSepArg, NULL},
	{(char *) "-base", (char *) "*cubes.base", XrmoptionSepArg, NULL},
	{(char *) "-fn", (char *) "*cubes.font", XrmoptionSepArg, NULL},
	{(char *) "-font", (char *) "*cubes.font", XrmoptionSepArg, NULL},
	{(char *) "-sizeX", (char *) "*cubes.sizeX", XrmoptionSepArg, NULL},
	{(char *) "-sizeY", (char *) "*cubes.sizeY", XrmoptionSepArg, NULL},
	{(char *) "-sizeZ", (char *) "*cubes.sizeZ", XrmoptionSepArg, NULL},
	{(char *) "-userName", (char *) "*cubes.userName", XrmoptionSepArg, NULL},
	{(char *) "-scoreFile", (char *) "*cubes.scoreFile", XrmoptionSepArg, NULL},
	{(char *) "-scores", (char *) "*cubes.scoreOnly", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-version", (char *) "*cubes.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
puzzleClearCancelCallback(Widget w, XtPointer clientData, XtPointer callData)
{
	XtPopdown(clearDialog);
}

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

	clearDialog = XtCreatePopupShell(title,
		transientShellWidgetClass, topLevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog",
		dialogWidgetClass, clearDialog,
		XtNlabel, text, NULL);
	okDialog = XtVaCreateManagedWidget("OK",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(okDialog, XtNcallback,
		puzzleClearCallback, dialog);
	cancelDialog = XtVaCreateManagedWidget("Cancel",
		commandWidgetClass, dialog, NULL);
	XtAddCallback(cancelDialog, XtNcallback,
		puzzleClearCancelCallback, dialog);
	XtRealizeWidget(clearDialog);
	XSetWMProtocols(XtDisplay(topLevel),
		XtWindow(clearDialog), &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, changerRowCol, speedChangerRowCol;
	Widget playMenu;
#endif
#ifdef HAVE_MOTIF
	Widget pullDownMenu, widget;
	Widget menuBarPanel;
	Widget blockXChangerRowCol, blockYChangerRowCol;
	Widget blockZChangerRowCol, messageRowCol;
	XmString fileString, playString;
	XmString getString, writeString, quitString;
	XmString undoString, redoString;
	XmString clearString, randomizeString, solveString;
#ifdef EXTRA
	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
	};
	Widget blockXBox, blockYBox, blockZBox, speedBox;
	Widget movesLabel, recordLabel;
	Widget w;
	Widget fileLabel, playLabel, helpLabel;
	int sizeX, sizeY, sizeZ, delay;
	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, "XCubes",
		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");
	randomizeString = XmStringCreateSimple((char *) "Randomize");
	solveString = XmStringCreateSimple((char *) "Auto-solve");
#ifdef EXTRA
	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,
		XmVaPUSHBUTTON, randomizeString, 'z', NULL, NULL,
		XmVaPUSHBUTTON, solveString, 's', NULL, NULL,
#ifdef EXTRA
		XmVaPUSHBUTTON, speedString, '>', NULL, NULL,
		XmVaPUSHBUTTON, slowString, '<', NULL, NULL,
#endif
		XmVaTOGGLEBUTTON, soundString, '@', NULL, NULL, NULL);
	XmStringFree(undoString);
	XmStringFree(redoString);
	XmStringFree(clearString);
	XmStringFree(randomizeString);
	XmStringFree(solveString);
#ifdef EXTRA
	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);
	clearDialog = createQuery(topLevel, "Clear Query",
		(char *) "Are you sure you want to start over?",
		(XtCallbackProc) puzzleClearCallback);
	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 block", 11, NULL);
		(void) XtVaCreateManagedWidget("mouseLeft",
			xmLabelGadgetClass, movesRowCol,
			XmNlabelType, XmPIXMAP,
			XmNlabelPixmap, mouseLeftCursor, NULL);
		(void) XtVaCreateManagedWidget("mouseRightText",
			xmLabelGadgetClass, movesRowCol,
			XtVaTypedArg, XmNlabelString,
			XmRString, "Clear", 6, 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);
	blockXChangerRowCol = XtVaCreateManagedWidget("blockXChangerRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef USE_SPIN
	createSpinner(blockXChangerRowCol, &blockXChanger,
		(char *) blockLabels[0], DEFAULT_BLOCKSX,
		MIN_BLOCKS, MAX_BLOCKS, 2,
		(XtCallbackProc) blockXChangeCallback);
#else
	createSlider(blockXChangerRowCol, &blockXChanger,
		(char *) blockLabels[0], DEFAULT_BLOCKSX,
		MIN_BLOCKS, MAX_BLOCKS, 2, SCROLL_SIZE,
		(XtCallbackProc) blockXChangeCallback);
#endif
	blockYChangerRowCol = XtVaCreateManagedWidget("blockYChangerRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef USE_SPIN
	createSpinner(blockYChangerRowCol, &blockYChanger,
		(char *) blockLabels[1], DEFAULT_BLOCKSY,
		MIN_BLOCKS, MAX_BLOCKS, 2,
		(XtCallbackProc) blockYChangeCallback);
#else
	createSlider(blockYChangerRowCol, &blockYChanger,
		(char *) blockLabels[1], DEFAULT_BLOCKSY,
		MIN_BLOCKS, MAX_BLOCKS, 2, SCROLL_SIZE,
		(XtCallbackProc) blockYChangeCallback);
#endif

	blockZChangerRowCol = XtVaCreateManagedWidget("blockZChangerRowCol",
		xmRowColumnWidgetClass, changerRowCol,
		XmNnumColumns, 2,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_TIGHT, NULL);
#ifdef USE_SPIN
	createSpinner(blockZChangerRowCol, &blockZChanger,
		(char *) blockLabels[2], DEFAULT_BLOCKSZ,
		MIN_BLOCKS, MAX_BLOCKS, 2,
		(XtCallbackProc) blockZChangeCallback);
#else
	createSlider(blockZChangerRowCol, &blockZChanger,
		(char *) blockLabels[2], DEFAULT_BLOCKSZ,
		MIN_BLOCKS, MAX_BLOCKS, 2, SCROLL_SIZE,
		(XtCallbackProc) blockZChangeCallback);
#endif
	speedChangerRowCol = XtVaCreateManagedWidget("speedChangerRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 2,
		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
	messageRowCol = XtVaCreateManagedWidget("messageRowCol",
		xmRowColumnWidgetClass, controlPanel, NULL);
	message = XtVaCreateManagedWidget("Play Cubes! (use mouse or keypad)",
		xmLabelWidgetClass, messageRowCol, NULL);
	puzzle = XtVaCreateManagedWidget("cubes",
		cubesWidgetClass, mainPanel, NULL);
#elif defined(HAVE_ATHENA)
	XtAppAddActions(appCon, actions, XtNumber(actions));
	createClearQuery((char *) "Clear Query",
		(char *) "Are you sure you want to start over?");
	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);
	changerRowCol = XtVaCreateManagedWidget("changerRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, movesRowCol, NULL);
	blockXBox = XtVaCreateManagedWidget("blockXBox",
		boxWidgetClass, changerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0, NULL);
	blockYBox = XtVaCreateManagedWidget("blockYBox",
		boxWidgetClass, changerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0,
		XtNfromHoriz, blockXBox, NULL);
	blockZBox = XtVaCreateManagedWidget("blockZBox",
		boxWidgetClass, changerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0,
		XtNfromHoriz, blockYBox, NULL);
	speedChangerRowCol = XtVaCreateManagedWidget("speedChangerRowCol",
		formWidgetClass, controlPanel,
		XtNborderWidth, 0,
		XtNfromVert, changerRowCol, NULL);
	speedBox = XtVaCreateManagedWidget("speedBox",
		boxWidgetClass, speedChangerRowCol,
		XtNorientation, XtorientHorizontal,
		XtNborderWidth, 0, NULL);
	message = XtVaCreateManagedWidget("Welcome",
		labelWidgetClass, controlPanel,
		XtNjustify,  XtJustifyLeft,
		XtNborderWidth, 0,
		XtNwidth, 180,
		XtNfromVert, speedChangerRowCol, NULL);
	puzzle = XtVaCreateManagedWidget("cubes",
		cubesWidgetClass, mainPanel,
		XtNfromVert, controlPanel, NULL);
       XtVaGetValues(puzzle,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY,
		XtNsizeZ, &sizeZ,
		XtNdelay, &delay, NULL);
#ifdef USE_SPIN
	createSpinner(blockXBox, &blockXSliderLabel,
		blockLabels[0], 0, sizeX, MIN_BLOCKS, MAX_BLOCKS, False,
		blockXUpCallback, blockXDownCallback);
	createSpinner(blockYBox, &blockYSliderLabel,
		blockLabels[1], 0, sizeY, MIN_BLOCKS, MAX_BLOCKS, False,
		blockYUpCallback, blockYDownCallback);
	createSpinner(blockZBox, &blockZSliderLabel,
		blockLabels[2], 0, sizeZ, MIN_BLOCKS, MAX_BLOCKS, False,
		blockZUpCallback, blockZDownCallback);
	createSpinner(speedBox, &speedSliderLabel,
		speedLabel, 0, getSpeed(delay), MIN_SPEED, MAX_SPEED, True,
		speedUpCallback, speedDownCallback);
#else
	createSlider(blockXBox, &blockXSliderLabel, &blockXSlider,
		blockLabels[0], 0, sizeX, MIN_BLOCKS, MAX_BLOCKS, False,
		SCROLL_SIZE, blockXChangeCallback, blockXChangeCallback);
	createSlider(blockYBox, &blockYSliderLabel, &blockYSlider,
		blockLabels[1], 0, sizeY, MIN_BLOCKS, MAX_BLOCKS, False,
		SCROLL_SIZE, blockYChangeCallback, blockYChangeCallback);
	createSlider(blockZBox, &blockZSliderLabel, &blockZSlider,
		blockLabels[2], 0, sizeZ, MIN_BLOCKS, MAX_BLOCKS, False,
		SCROLL_SIZE, blockZChangeCallback, blockZChangeCallback);
	createSlider(speedBox, &speedSliderLabel, &speedSlider,
		speedLabel, 0, getSpeed(delay), MIN_SPEED, MAX_SPEED, True,
		SCROLL_SIZE, speedChangeCallback, speedChangeCallback);
#endif
	XtRealizeWidget(topLevel);
	if (wmDeleteWindow == None)
		wmDeleteWindow = XInternAtom(XtDisplay(topLevel),
			"WM_DELETE_WINDOW", FALSE);
	XSetWMProtocols(XtDisplay(topLevel), XtWindow(topLevel),
		&wmDeleteWindow, 1);
#else
	puzzle = XtVaCreateManagedWidget("cubes",
		cubesWidgetClass, 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
		7,
#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
