/*
 * @(#)xhexagons.c
 *
 * Copyright 1993 - 2014  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 Hexagons */

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

static const char synopsisHelp[] = {
"[-geometry [{width}][x{height}][{+-}{xoff}[{+-}{yoff}]]]\n"
"[-display [{host}]:[{vs}]] [-[no]mono] [-[no]{reverse|rv}]\n"
"[-{foreground|fg} {color}] [-{background|bg} {color}]\n"
"[-tile {color}] [-text {color}] [-delay msecs]\n"
"[-[no]sound] [-bumpSound {filename}]\n"
"[-{font|fn} {fontname}] [-size{x|y} {int}] [-[no]corners]\n"
"[-base {int}] [-userName {string}] [-scoreFile {filename}]\n"
"[-scores] [-version]"
};
#endif

#if defined(HAVE_MOTIF) || defined(WINVER)
static const char descriptionHelp[] = {
"A sliding tile puzzle.  A hexagonal version of the "
"15 puzzle.  The 17 puzzle was conceived of by Alwin Vietor\n"
"and marketed in 1885 in Germany as \"Trilemma\" with "
"round pieces.  Sam Cornwell rediscovered this in 1989\n"
"with \"Clockblocks\" of which 12 were numbered using "
"hexagonal pieces.  Also he produced a smaller 12 block\n"
"puzzle with 9 that were numbered called \"Ninefield\".  Also "
"Bernhard Wiezorke came up with the similar 17 \n"
"puzzle, \"Hexafax, the New Fifteen Puzzle\", in 1991 and a "
"smaller 11 piece \"Counterfax\" of which 8 were\n"
"numbered."
};

static const char featuresHelp[] = {
"If in corners mode: Press \"mouse-left\" button to move "
"a tile, then release \"mouse-left\" button on a space.\n"
"It will not move if blocked.  One can only move one "
"tile at a time. The only tiles that can be moved are\n"
"the tile(s) next to both spaces.\n"
"If in nocorners mode: Click \"mouse-left\" button to "
"move a tile.  One can move more than one tile at a time\n"
"and one is not constrained by parity.\n"
"\n"
"Click \"mouse-right\" button, or press \"C\" or \"c\" "
"keys, to clear the puzzle.\n"
"\n"
"Press \"R\" or \"r\" keys to read 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 \"E\" or \"e\" 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"
"\"S\" or \"s\" keys reserved for the auto-solver "
"(not implemented).\n"
"\n"
"Press \"O\" or \"o\" keys to toggle corners mode.  "
"(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 Hexagons as:\n"
"7   9  Upper Left, Upper Right\n"
"  ^\n"
"4< >6  Left, Right\n"
"  v\n"
"1   3  Bottom Left, Bottom Right\n"
"\n"
"The control key allows you to change the complexity "
"of xhexagons.  Hold down control key and use the\n"
"keypad or arrow keys to reduce or enlarge puzzle complexity."
};

static const char referencesHelp[] = {
"Dieter Gebhardt, \"From Trilemma to Counterfax\", CFF 53, "
"October 2000, pp 8-10.\n"
"Sam Cornwell, \"Ninefield: a Sliding Block Puzzle\", "
"CFF 57, March 2002, pp 4-5.\n"
"Dieter Gebhardt, \"Ninefield Revisited\", CFF 58, "
"July 2002, p 21.\n"
"Bernhard Wiezorke, \"Hexafax, the New Fifteen Puzzle\" "
"brochure."
};
#endif

static const char solveHelp[] = {
"Auto-solver: sorry, not implemented."
};

#include "file.h"
#ifdef WINVER
#include "HexagonsP.h"
#define TITLE "whexagons"

static HexagonsRec widget;

#ifndef SCOREPATH
#ifdef UNIXDELIM
#define SCOREPATH "c:/WINDOWS"
#else
#define SCOREPATH "c:\\WINDOWS"
#endif
#endif
#define PRINT_MESSAGE(b) (void) MessageBox(widget.core.hWnd, (LPCSTR) b, "Warning", MB_OK);
#define SET_STARTED(w,b) w->hexagons.started = b
#else
#include "xwin.h"
#include <X11/Shell.h>
#include <X11/cursorfont.h>
#ifdef HAVE_MOTIF
#include <Xm/PanedW.h>
#include <Xm/RowColumn.h>
#include <Xm/Label.h>
#include <Xm/LabelG.h>
#include <Xm/MessageB.h>
#include <Xm/PushBG.h>
#include <Xm/CascadeB.h>
#include <Xm/Scale.h>
#include <Xm/ToggleB.h>
#include <Xm/Text.h>
#include <Xm/Form.h>
#ifdef MOUSEBITMAPS
#include "pixmaps/mouse-l.xbm"
#include "pixmaps/mouse-r.xbm"
#endif
#define PRINT_MESSAGE(b) printState(message, b)
#else
#define PRINT_MESSAGE(b) XtWarning(b)
#endif
#define SET_STARTED(w,b) XtVaSetValues(w, XtNstart, b, NULL)
#include "Hexagons.h"
#ifdef HAVE_XPM
#include <X11/xpm.h>
#ifdef CONSTPIXMAPS
#include "16x16/hexagons.xpm"
#include "22x22/hexagons.xpm"
#include "24x24/hexagons.xpm"
#include "32x32/hexagons.xpm"
#include "48x48/hexagons.xpm"
#include "64x64/hexagons.xpm"
#else
#include "pixmaps/16x16/hexagons.xpm"
#include "pixmaps/22x22/hexagons.xpm"
#include "pixmaps/24x24/hexagons.xpm"
#include "pixmaps/32x32/hexagons.xpm"
#include "pixmaps/48x48/hexagons.xpm"
#include "pixmaps/64x64/hexagons.xpm"
#endif
#define RESIZE_XPM(s) ((char **) (((s)<=32)?\
(((s)<=22)?(((s)<=16)?hexagons_16x16:hexagons_22x22):\
(((s)<=24)?hexagons_24x24:hexagons_32x32)):\
(((s)<=48)?hexagons_48x48:hexagons_64x64)))
#endif
#include "pixmaps/64x64/hexagons.xbm"
#define DEFINE_XBM (char *) hexagons_64x64_bits, hexagons_64x64_width, hexagons_64x64_height
#ifndef SCOREPATH
#ifdef VMS
#define SCOREPATH "SYS$LOGIN:"
#else
#define SCOREPATH "/var/games/xpuzzles"
#endif
#endif
#endif

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

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

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

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

#ifdef HAVE_MOTIF
#define SCROLL_SIZE 30		/* A page */
#define MIN_SPEED 1
#define MAX_SPEED 50
#ifdef ANIMATE
static Widget speedSlider;
#endif
static Widget movesText, recordText, message, cornersSwitch;
static Widget tileXSlider, tileYSlider;
static char buff[21];
static Widget descriptionDialog, featuresDialog;
static Widget synopsisDialog, referencesDialog, aboutDialog;
static Widget solveDialog, clearDialog;
static Arg args[10];
#else
static char titleDsp[TITLE_LENGTH] = "";
#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 *progDsp;
static char userNameDsp[USER_NAME_LENGTH] = "";

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

	if (!XtIsSubclass(w, xmLabelWidgetClass))
		XtError("printState() requires a Label Widget");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	XtVaSetValues(w, XmNlabelString, xmstr, NULL);
}
#endif

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

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

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

	for (i = 0; i < MAX_ORIENT; i++)
		for (j = 0; j < MAX_TILES - MIN_TILES + 1; j++)
			for (k = 0; k < MAX_TILES - MIN_TILES + 1; k++) {
				puzzleRecord[i][j][k].score = NEVER;
				(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, "Can not 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, "Can not 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_ORIENT; i++)
		for (j = 0; j < MAX_TILES - MIN_TILES + 1; j++)
			for (k = 0; k < MAX_TILES - MIN_TILES + 1; k++) {
				(void) fscanf(fp, "%d %s\n", &n, userName);
				if (n <= puzzleRecord[i][j][k].score ||
						puzzleRecord[i][j][k].score <= NEVER) {
					puzzleRecord[i][j][k].score = n;
					(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, "Can not 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) strcat(lockFile, ".lock");
		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_ORIENT; i++) {
			for (j = 0; j < MAX_TILES - MIN_TILES + 1; j++) {
				for (k = 0; k < MAX_TILES - MIN_TILES + 1; k++)
					(void) fprintf(fp, "%d %s\n",
						puzzleRecord[i][j][k].score,
						puzzleRecord[i][j][k].name);
				if (j < MAX_TILES - MIN_TILES || 
						i < MAX_ORIENT - 1)
					(void) fprintf(fp, "\n");
			}
			if (i < MAX_ORIENT - 1)
				(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, Boolean corners)
{
	int i = (corners) ? 1 : 0;
	int j = sizeX - MIN_TILES, k = sizeY - MIN_TILES;

	if (sizeX > MAX_TILES || sizeY > MAX_TILES) {
		(void) strncpy(recordDsp, "NOT RECORDED", MESSAGE_LENGTH);
	} else if (puzzleRecord[i][j][k].score <= NEVER) {
		(void) sprintf(recordDsp, "NEVER %s", NOACCESS);
	} else {
		(void) sprintf(recordDsp, "%d %s",
			puzzleRecord[i][j][k].score,
			puzzleRecord[i][j][k].name);
	}
#ifdef HAVE_MOTIF
	printState(recordText, recordDsp);
#endif
}

static void
printStatus(char *msg, int nMoves
#ifndef HAVE_MOTIF
		, int sizeX, int sizeY
#endif
		)
{
#ifdef HAVE_MOTIF
	printState(message, msg);
	(void) sprintf(buff, "%d", nMoves);
	printState(movesText, buff);
#else
	(void) sprintf(titleDsp, "%s: %dx%d@ (%d/%s) - %s",
		progDsp, sizeX, sizeY, nMoves, recordDsp, msg);
#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 corners)
{
	int i = (corners) ? 1 : 0;
	int j = sizeX - MIN_TILES, k = sizeY - MIN_TILES;

	if (sizeX <= MAX_TILES && sizeY <= MAX_TILES &&
			(counter < puzzleRecord[i][j][k].score ||
			puzzleRecord[i][j][k].score <= NEVER)) {
		readRecords();	/* Maybe its been updated by another */
		puzzleRecord[i][j][k].score = counter;
		(void) strncpy(puzzleRecord[i][j][k].name, userNameDsp,
			USER_NAME_LENGTH);
		writeRecords();
		printRecord(sizeX, sizeY, corners);
		return True;
	}
	return False;
}

static void
initialize(
#ifdef WINVER
HexagonsWidget w, HBRUSH brush
#else
Widget w
#endif
)
{
	int sizeX, sizeY;
	Boolean corners;
	char *userName, *scoreFile;

#ifdef WINVER
	initializePuzzle(w, brush);

	sizeX = w->hexagons.sizeX;
	sizeY = w->hexagons.sizeY;
	corners = w->hexagons.corners;
	userName = w->hexagons.userName;
	scoreFile = w->hexagons.scoreFile;
	if (strcmp(scoreFile, ""))
		(void) strncpy(scoreFileName, scoreFile, FILE_NAME_LENGTH);
#else
	Boolean scoreOnly, versionOnly;

	XtVaGetValues(w,
		XtNuserName, &userName,
		XtNscoreFile, &scoreFile,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY,
		XtNcorners, &corners,
		XtNscoreOnly, &scoreOnly,
		XtNversionOnly, &versionOnly, NULL);
	if (versionOnly) {
		(void) printf("%s\n", aboutHelp);
		exit(0);
	}
	if (strcmp(scoreFile, ""))
		(void) strncpy(scoreFileName, scoreFile, FILE_NAME_LENGTH);
	if (scoreOnly) {
		initRecords();
		readRecords();
		printRecords();
		exit(0);
	}
#ifdef HAVE_MOTIF
	if (sizeX > MAX_TILES)
		XtVaSetValues(tileXSlider, XmNmaximum, sizeX, NULL);
	XmScaleSetValue(tileXSlider, sizeX);
	if (sizeY > MAX_TILES)
		XtVaSetValues(tileYSlider, XmNmaximum, sizeY, NULL);
	XmScaleSetValue(tileYSlider, sizeY);
	XmToggleButtonSetState(cornersSwitch, corners, True);
#ifdef ANIMATE
	{
		int delay;

		XtVaGetValues(w, XtNdelay, &delay, NULL);
		XmScaleSetValue(speedSlider,
			MAX_SPEED + MIN_SPEED - delay - 1);
	}
#endif
#endif
#endif
	SET_STARTED(w, False);
	initRecords();
	readRecords();
#ifndef WINVER
	(void) strncpy(userNameDsp, userName, USER_NAME_LENGTH);
#endif
	if (!strcmp(userName, "") || !strcmp(userName, "(null)") ||
			!strcmp(userName, NOACCESS) ||
			!strcmp(userName, NOBODY)) {
#ifdef WINVER
		(void) strncpy(userNameDsp, userName, USER_NAME_LENGTH);
#else
		char *login = getlogin();

		if (login == NULL) {
			(void) strcpy(userNameDsp, "");
		} else {
			(void) sprintf(userNameDsp, "%s", login);
		}
		if (!strcmp(userNameDsp, "") ||
				!strcmp(userNameDsp, "(null)") ||
				!strcmp(userNameDsp, NOACCESS) ||
				!strcmp(userNameDsp, NOBODY))
			/* It really IS nobody */
			(void) sprintf(userNameDsp, "%s", "guest");
#endif
	}
	printRecord(sizeX, sizeY, corners);
	printStatus(messageDsp, movesDsp
#ifndef HAVE_MOTIF
		, sizeX, sizeY
#endif
		);
}

#ifdef WINVER
void
setPuzzle(HexagonsWidget w, int reason)
#else
static void
puzzleListener(Widget w, caddr_t clientData,
		hexagonsCallbackStruct *callData)
#endif
{
#ifndef WINVER
	int reason = callData->reason;
#endif
	int sizeX, sizeY;
	Boolean corners, cheat;

	(void) strcpy(messageDsp, "");
#ifdef WINVER
	sizeX = w->hexagons.sizeX;
	sizeY = w->hexagons.sizeY;
	corners = w->hexagons.corners;
	cheat = w->hexagons.cheat;
#else
	XtVaGetValues(w,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY,
		XtNcorners, &corners,
		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_CLEAR_QUERY:
#ifdef HAVE_MOTIF
		XtManageChild(clearDialog);
#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);
#else
		(void) strncpy(messageDsp, solveHelp, MESSAGE_LENGTH);
#endif
#endif
		break;
	case ACTION_RESTORE:
	case ACTION_RESET:
		movesDsp = 0;
		randomized = False;
		break;
	case ACTION_AMBIGUOUS:
		(void) strncpy(messageDsp, "Ambiguous move", MESSAGE_LENGTH);
		break;
	case ACTION_BLOCKED:
		(void) strncpy(messageDsp, "Blocked", MESSAGE_LENGTH);
		break;
	case ACTION_SPACE:
#if 0
		/* Too annoying */
		(void) sprintf(messageDsp, "%s can not slide",
			(corners) ? "Spaces" : "A space");
#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) sprintf(messageDsp,
				"No cheating %s!!", userNameDsp);
		else if (!randomized && handleSolved(movesDsp,
				sizeX, sizeY, corners))
			(void) sprintf(messageDsp,
				"Congratulations %s!!", userNameDsp);
		else
			(void) strncpy(messageDsp, "Solved!",
				MESSAGE_LENGTH);
		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++;
		printRecord(sizeX, sizeY, corners);
#ifdef WINVER
		w->hexagons.sizeX = sizeX;
#else
		XtVaSetValues(w, XtNsizeX, sizeX, NULL);
#ifdef HAVE_MOTIF
		if (sizeX > MAX_TILES)
			XtVaSetValues(tileXSlider, XmNmaximum, sizeX, NULL);
		XmScaleSetValue(tileXSlider, sizeX);
#endif
#endif
		break;
	case ACTION_DECX:
		movesDsp = 0;
		sizeX--;
		printRecord(sizeX, sizeY, corners);
#ifdef WINVER
		w->hexagons.sizeX = sizeX;
#else
		XtVaSetValues(w, XtNsizeX, sizeX, NULL);
#ifdef HAVE_MOTIF
		XmScaleSetValue(tileXSlider, sizeX);
		if (sizeX >= MAX_TILES)
			XtVaSetValues(tileXSlider, XmNmaximum, sizeX, NULL);
#endif
#endif
		break;
	case ACTION_INCY:
		movesDsp = 0;
		sizeY++;
		printRecord(sizeX, sizeY, corners);
#ifdef WINVER
		w->hexagons.sizeY = sizeY;
#else
		XtVaSetValues(w, XtNsizeY, sizeY, NULL);
#ifdef HAVE_MOTIF
		if (sizeY > MAX_TILES)
			XtVaSetValues(tileYSlider, XmNmaximum, sizeY, NULL);
		XmScaleSetValue(tileYSlider, sizeY);
#endif
#endif
		break;
	case ACTION_DECY:
		movesDsp = 0;
		sizeY--;
		printRecord(sizeX, sizeY, corners);
#ifdef WINVER
		w->hexagons.sizeY = sizeY;
#else
		XtVaSetValues(w, XtNsizeY, sizeY, NULL);
#ifdef HAVE_MOTIF
		XmScaleSetValue(tileYSlider, sizeY);
		if (sizeY >= MAX_TILES)
			XtVaSetValues(tileYSlider, XmNmaximum, sizeY, NULL);
#endif
#endif
		break;
	case ACTION_CORNERS:
		movesDsp = 0;
		corners = !corners;
		printRecord(sizeX, sizeY, corners);
#ifdef WINVER
		w->hexagons.corners = corners;
#else
		XtVaSetValues(w, XtNcorners, corners, NULL);
#ifdef HAVE_MOTIF
		XmToggleButtonSetState(cornersSwitch, corners, True);
#endif
#endif
		break;
	case ACTION_UNDO:
		movesDsp--;
		SET_STARTED(w, True);
		break;
	case ACTION_REDO:
		movesDsp++;
		SET_STARTED(w, True);
		break;
#if defined(HAVE_MOTIF) && defined(ANIMATE)
	case ACTION_SPEED:
		{
			int oldDelay, delay;

			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);
			}
			XmScaleSetValue(speedSlider,
				MAX_SPEED + MIN_SPEED - delay - 1);
		}
		return;
#endif
	}
	printStatus(messageDsp, movesDsp
#ifndef HAVE_MOTIF
		, sizeX, sizeY
#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.hexagons.focus) {
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_BRUSH));
			enterPuzzle(&widget);
			(void) EndPaint(hWnd, &paint);
		}
	} else {
		if (widget.hexagons.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, LOWORD(lParam), HIWORD(lParam));
		(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_READ:
			readPuzzle(&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_CORNERS:
			cornersPuzzle(&widget);
			sizePuzzle(&widget);
			(void) InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ACTION_TR:
		case ACTION_RIGHT:
		case ACTION_BR:
		case ACTION_BL:
		case ACTION_LEFT:
		case ACTION_TL:
			widget.core.hDC = GetDC(hWnd);
			(void) SelectObject(widget.core.hDC,
				GetStockObject(NULL_PEN));
			(void) movePuzzle(&widget,
				(int) LOWORD(wParam) - ACTION_TR, FALSE);
			(void) ReleaseDC(hWnd, widget.core.hDC);
			break;
		case ACTION_DECY:
		case ACTION_INCX:
		case ACTION_INCY:
		case ACTION_DECX:
			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,
		(signed) CW_USEDEFAULT,
		(signed) CW_USEDEFAULT,
		HWND_DESKTOP,
		(HMENU) NULL,
		hInstance,
		(XtPointer) NULL);
	if (!hWnd)
		return FALSE;
	hAccel = (HACCEL) LoadAccelerators(hInstance, TITLE);
	(void) ShowWindow(hWnd, numCmdShow);
	(void) UpdateWindow(hWnd);
	while (GetMessage(&msg, (HWND) NULL, 0, 0))
		if (!TranslateAccelerator(hWnd, hAccel, &msg)) {
			(void) TranslateMessage(&msg);
			(void) DispatchMessage(&msg);
		}
	return (int) msg.wParam;
}

#else

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

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

static XrmOptionDescRec options[] =
{
	{(char *) "-mono", (char *) "*hexagons.mono", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nomono", (char *) "*hexagons.mono", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-rv", (char *) "*hexagons.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-reverse", (char *) "*hexagons.reverseVideo", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-norv", (char *) "*hexagons.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-noreverse", (char *) "*hexagons.reverseVideo", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-fg", (char *) "*hexagons.Foreground", XrmoptionSepArg, NULL},
	{(char *) "-foreground", (char *) "*hexagons.Foreground", XrmoptionSepArg, NULL},
	{(char *) "-bg", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-background", (char *) "*Background", XrmoptionSepArg, NULL},
	{(char *) "-tile", (char *) "*hexagons.tileColor", XrmoptionSepArg, NULL},
	{(char *) "-text", (char *) "*hexagons.textColor", XrmoptionSepArg, NULL},
	{(char *) "-install", (char *) "*hexagons.install", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-noinstall", (char *) "*hexagons.install", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-picture", (char *) "*hexagons.picture", XrmoptionSepArg, NULL},
	{(char *) "-delay", (char *) "*hexagons.delay", XrmoptionSepArg, NULL},
	{(char *) "-sound", (char *) "*hexagons.sound", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nosound", (char *) "*hexagons.sound", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-bumpSound", (char *) "*hexagons.bumpSound", XrmoptionSepArg, NULL},
	{(char *) "-base", (char *) "*hexagons.base", XrmoptionSepArg, NULL},
	{(char *) "-fn", (char *) "*hexagons.font", XrmoptionSepArg, NULL},
	{(char *) "-font", (char *) "*hexagons.font", XrmoptionSepArg, NULL},
	{(char *) "-sizex", (char *) "*hexagons.sizeX", XrmoptionSepArg, NULL},
	{(char *) "-sizey", (char *) "*hexagons.sizeY", XrmoptionSepArg, NULL},
	{(char *) "-corners", (char *) "*hexagons.corners", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-nocorners", (char *) "*hexagons.corners", XrmoptionNoArg, (char *) "FALSE"},
	{(char *) "-userName", (char *) "*hexagons.userName", XrmoptionSepArg, NULL},
	{(char *) "-scoreFile", (char *) "*hexagons.scoreFile", XrmoptionSepArg, NULL},
	{(char *) "-scores", (char *) "*hexagons.scoreOnly", XrmoptionNoArg, (char *) "TRUE"},
	{(char *) "-version", (char *) "*hexagons.versionOnly", XrmoptionNoArg, (char *) "TRUE"}
};

#ifdef HAVE_MOTIF
static void
puzzleListenerClear(Widget w, XtPointer clientData,
		XmAnyCallbackStruct *cbs)
{
	if (cbs->reason == XmCR_OK) {
		XtVaSetValues(puzzle, XtNmenu, ACTION_CLEAR, NULL);
	}
}

static void
tileXChangeListener(Widget w, XtPointer clientData,
		XmScaleCallbackStruct *cbs)
{
	int sizeX = cbs->value, sizeY, oldX;
	Boolean corners;

	XtVaGetValues(puzzle,
		XtNcorners, &corners,
		XtNsizeX, &oldX,
		XtNsizeY, &sizeY, NULL);
	if (oldX == sizeX)
		return;
	XtVaSetValues(puzzle,
		XtNsizeX, sizeX, NULL);
	movesDsp = 0;
	(void) sprintf(buff, "%d", movesDsp);
	printState(movesText, buff);
	printRecord(sizeX, sizeY, corners);
	(void) strcpy(messageDsp, "");
	printState(message, messageDsp);
}

static void
tileYChangeListener(Widget w, XtPointer clientData,
		XmScaleCallbackStruct *cbs)
{
	int sizeX, sizeY = cbs->value, oldY;
	Boolean corners;

	XtVaGetValues(puzzle,
		XtNcorners, &corners,
		XtNsizeX, &sizeX,
		XtNsizeY, &oldY, NULL);
	if (oldY == sizeY)
		return;
	if (corners && sizeY == 1) {
		XmScaleSetValue(tileYSlider, oldY);
		return;
	}
	XtVaSetValues(puzzle,
		XtNsizeY, sizeY, NULL);
	movesDsp = 0;
	(void) sprintf(buff, "%d", movesDsp);
	printState(movesText, buff);
	printRecord(sizeX, sizeY, corners);
	(void) strcpy(messageDsp, "");
	printState(message, messageDsp);
}

static void
cornersToggle(Widget w, XtPointer clientData,
		XmToggleButtonCallbackStruct *cbs)
{
	int sizeX, sizeY;
	Boolean corners = cbs->set, oldCorn;

	XtVaGetValues(puzzle,
		XtNcorners, &oldCorn,
		XtNsizeX, &sizeX,
		XtNsizeY, &sizeY, NULL);
	if (oldCorn == corners)
		return;
	if (corners && sizeY == 1) {
		XmToggleButtonSetState(cornersSwitch, !corners, True);
		return;
	}
	XtVaSetValues(puzzle,
		XtNcorners, corners, NULL);
	movesDsp = 0;
	(void) sprintf(buff, "%d", movesDsp);
	printState(movesText, buff);
	printRecord(sizeX, sizeY, corners);
	(void) strcpy(messageDsp, "");
	printState(message, messageDsp);
}

#ifdef ANIMATE
static void
speedChangeListener(Widget w, XtPointer clientData, XmScaleCallbackStruct *cbs)
{
	int delay = MAX_SPEED + MIN_SPEED - cbs->value - 1, oldDelay;

	XtVaGetValues(puzzle,
		XtNdelay, &oldDelay, NULL);
	if (oldDelay != delay) {
		XtVaSetValues(puzzle, XtNdelay, delay, NULL);
	}
}
#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

int
main(int argc, char **argv)
{
	int pixmapSize;
#ifdef HAVE_MOTIF
	Widget menuBar, pullDownMenu, widget;
	Widget menuBarPanel, mainPanel, controlPanel;
	Widget movesRowCol, sliderRowCol, switchRowCol;
	Widget messageRowCol;
	XmString fileString, playString;
	XmString readString, writeString, quitString;
	XmString undoString, redoString;
	XmString clearString, randomizeString, solveString;
#ifdef EXTRA
	XmString modeString;
	XmString speedString, slowString;
#endif
	XmString soundString;
#endif

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

#ifdef HAVE_MOTIF
	menuBarPanel = XtVaCreateManagedWidget("menuBarPanel",
		xmPanedWindowWidgetClass, topLevel,
		XmNseparatorOn, False,
		XmNsashWidth, 1,
		XmNsashHeight, 1, NULL);
	fileString = XmStringCreateSimple((char *) "File");
	playString = XmStringCreateSimple((char *) "Play");
	menuBar = XmVaCreateSimpleMenuBar(menuBarPanel, (char *) "menuBar",
		XmVaCASCADEBUTTON, fileString, 'F',
		XmVaCASCADEBUTTON, playString, 'P',
		NULL);
	XmStringFree(fileString);
	XmStringFree(playString);
	readString = XmStringCreateSimple((char *) "Read");
	writeString = XmStringCreateSimple((char *) "Write");
	quitString = XmStringCreateSimple((char *) "Exit");
	(void) XmVaCreateSimplePulldownMenu(menuBar, (char *) "fileMenu",
		0, fileMenuListener,
		XmVaPUSHBUTTON, readString, 'R', NULL, NULL,
		XmVaPUSHBUTTON, writeString, 'W', NULL, NULL,
		XmVaSEPARATOR,
		XmVaPUSHBUTTON, quitString, 'x', NULL, NULL,
		NULL);
	XmStringFree(readString);
	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
	modeString = XmStringCreateSimple((char *) "Corners");
	speedString = XmStringCreateSimple((char *) "Speed >");
	slowString = XmStringCreateSimple((char *) "Slow <");
#endif
	soundString = XmStringCreateSimple((char *) "Sound @");
	(void) XmVaCreateSimplePulldownMenu(menuBar, (char *) "playMenu",
		1, playMenuListener,
		XmVaPUSHBUTTON, undoString, 'U', NULL, NULL,
		XmVaPUSHBUTTON, redoString, 'e', NULL, NULL,
		XmVaPUSHBUTTON, clearString, 'C', NULL, NULL,
		XmVaPUSHBUTTON, randomizeString, 'z', NULL, NULL,
		XmVaPUSHBUTTON, solveString, 's', NULL, NULL,
#ifdef EXTRA
		XmVaPUSHBUTTON, modeString, 'o', NULL, NULL,
		XmVaPUSHBUTTON, speedString, '>', NULL, NULL,
		XmVaPUSHBUTTON, slowString, '<', NULL, NULL,
#endif
		XmVaPUSHBUTTON, soundString, '@', NULL, NULL,
		NULL);
	XmStringFree(undoString);
	XmStringFree(redoString);
	XmStringFree(clearString);
	XmStringFree(randomizeString);
	XmStringFree(solveString);
#ifdef EXTRA
	XmStringFree(modeString);
	XmStringFree(speedString);
	XmStringFree(slowString);
#endif
	XmStringFree(soundString);
	pullDownMenu = XmCreatePulldownMenu(menuBar,
		(char *) "helpPullDown", NULL, 0);
	widget = XtVaCreateManagedWidget("Help",
		xmCascadeButtonWidgetClass, menuBar,
		XmNsubMenuId, pullDownMenu,
		XmNmnemonic, 'H', NULL);
	XtVaSetValues(menuBar, XmNmenuHelpWidget, widget, NULL);
	widget = XtVaCreateManagedWidget("Description",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'D', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 0);
	widget = XtVaCreateManagedWidget("Features",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'F', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 1);
	widget = XtVaCreateManagedWidget("Synopsis",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'S', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 2);
	widget = XtVaCreateManagedWidget("References",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'R', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 3);
	widget = XtVaCreateManagedWidget("About",
		xmPushButtonGadgetClass, pullDownMenu,
		XmNmnemonic, 'A', NULL);
	XtAddCallback(widget, XmNactivateCallback, helpMenuListener, (char *) 4);
	XtManageChild(menuBar);
	solveDialog = createHelp(menuBar, (char *) solveHelp,
		(char *) "Solve");
	clearDialog = createQuery(topLevel,
		(char *) "Are you sure you want to start over?",
		(char *) "Clear Query",
		(XtCallbackProc) puzzleListenerClear);
	mainPanel = XtCreateManagedWidget("mainPanel",
		xmPanedWindowWidgetClass, menuBarPanel,
		NULL, 0);
	controlPanel = XtVaCreateManagedWidget("controlPanel",
		xmPanedWindowWidgetClass, mainPanel,
		XmNseparatorOn, False,
		XmNsashWidth, 1,
		XmNsashHeight, 1, NULL);
	movesRowCol = XtVaCreateManagedWidget("movesRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_COLUMN, NULL);
#ifdef MOUSEBITMAPS
	{
		/* Takes up valuable real estate. */
		Pixmap mouseLeftCursor, mouseRightCursor;
		Pixel fg, bg;

		(void) XtVaGetValues(movesRowCol,
			XmNforeground, &fg,
			XmNbackground, &bg, NULL);
		mouseLeftCursor = XCreatePixmapFromBitmapData(
			XtDisplay(movesRowCol),
			RootWindowOfScreen(XtScreen(movesRowCol)),
			(char *) mouse_left_bits,
			mouse_left_width, mouse_left_height, fg, bg,
			DefaultDepthOfScreen(XtScreen(movesRowCol)));
		mouseRightCursor = XCreatePixmapFromBitmapData(
			XtDisplay(movesRowCol),
			RootWindowOfScreen(XtScreen(movesRowCol)),
			(char *) mouse_right_bits,
			mouse_right_width, mouse_right_height, fg, bg,
			DefaultDepthOfScreen(XtScreen(movesRowCol)));
		(void) XtVaCreateManagedWidget("mouseLeftText",
			xmLabelGadgetClass, movesRowCol,
			XtVaTypedArg, XmNlabelString,
			XmRString, "Move tile", 10, NULL);
		(void) XtVaCreateManagedWidget("mouseLeft",
			xmLabelGadgetClass, movesRowCol,
			XmNlabelType, XmPIXMAP,
			XmNlabelPixmap, mouseLeftCursor, NULL);
		(void) XtVaCreateManagedWidget("mouseRightText",
			xmLabelGadgetClass, movesRowCol,
			XtVaTypedArg, XmNlabelString,
			XmRString, "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("recordText",
		xmLabelGadgetClass, movesRowCol,
		XtVaTypedArg, XmNlabelString, XmRString, "Record", 7, NULL);
	recordText = XtVaCreateManagedWidget("0",
		xmLabelWidgetClass, movesRowCol, NULL);
	sliderRowCol = XtVaCreateManagedWidget("tilesRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_COLUMN, NULL);
	tileXSlider = XtVaCreateManagedWidget("tileX",
		xmScaleWidgetClass, sliderRowCol,
		XtVaTypedArg, XmNtitleString, XmRString, "Size X", 7,
		XmNminimum, MIN_TILES,
		XmNmaximum, MAX_TILES,
		XmNvalue, DEFAULT_TILESX,
		XmNshowValue, True,
		XmNorientation, XmHORIZONTAL, NULL);
	XtAddCallback(tileXSlider, XmNvalueChangedCallback,
		(XtCallbackProc) tileXChangeListener, (XtPointer) NULL);
	tileYSlider = XtVaCreateManagedWidget("tileY",
		xmScaleWidgetClass, sliderRowCol,
		XtVaTypedArg, XmNtitleString, XmRString, "Size Y", 7,
		XmNminimum, MIN_TILES,
		XmNmaximum, MAX_TILES,
		XmNvalue, DEFAULT_TILESY,
		XmNshowValue, True,
		XmNorientation, XmHORIZONTAL, NULL);
	XtAddCallback(tileYSlider, XmNvalueChangedCallback,
		(XtCallbackProc) tileYChangeListener, (XtPointer) NULL);
	switchRowCol = XtVaCreateManagedWidget("switchRowCol",
		xmRowColumnWidgetClass, controlPanel,
		XmNnumColumns, 1,
		XmNorientation, XmHORIZONTAL,
		XmNpacking, XmPACK_COLUMN, NULL);
	cornersSwitch = XtVaCreateManagedWidget("Corners",
		xmToggleButtonWidgetClass, switchRowCol,
		XmNset, DEFAULT_CORNERS, NULL);
	XtAddCallback(cornersSwitch, XmNvalueChangedCallback,
		(XtCallbackProc) cornersToggle, (XtPointer) NULL);
#ifdef ANIMATE
	speedSlider = XtVaCreateManagedWidget("speedSlider",
		xmScaleWidgetClass, switchRowCol,
		XtVaTypedArg, XmNtitleString, XmRString, "Animation Speed", 16,
		XmNminimum, MIN_SPEED,
		XmNmaximum, MAX_SPEED,
		XmNvalue, MAX_SPEED - DEFAULT_DELAY,
		XmNshowValue, True,
		XmNorientation, XmHORIZONTAL, NULL);
	XtAddCallback(speedSlider, XmNvalueChangedCallback,
		(XtCallbackProc) speedChangeListener, (XtPointer) NULL);
#endif
	messageRowCol = XtVaCreateManagedWidget("messageRowCol",
		xmRowColumnWidgetClass, controlPanel, NULL);
	message = XtVaCreateManagedWidget("Play Hexagons! (use mouse or keypad)",
		xmLabelWidgetClass, messageRowCol, NULL);
	puzzle = XtCreateManagedWidget("hexagons",
		hexagonsWidgetClass, mainPanel, NULL, 0);
#else
	puzzle = XtCreateManagedWidget("hexagons",
		hexagonsWidgetClass, topLevel, NULL, 0);
#endif
	XtVaGetValues(puzzle,
		XtNpixmapSize, &pixmapSize, NULL);
#ifdef HAVE_XPM
	{
		XpmAttributes xpmAttributes;
		XpmColorSymbol transparentColor[1] = {{NULL,
			(char *) "none", 0 }};
		Pixel bg;

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

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