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

/* Methods file for Skewb */

#include "file.h"
#include "rngs.h"
#include "sound.h"
#include "SkewbP.h"
#include "Skewb2dP.h"
#include "Skewb3dP.h"
#ifdef HAVE_OPENGL
#include "SkewbGLP.h"
#endif

#ifdef WINVER
#ifndef LOGPATH
#define LOGPATH "/usr/tmp"
#endif
#ifndef INIFILE
#define INIFILE "wskewb.ini"
#endif

#define SECTION "setup"

static const char *faceColorString[MAX_FACES] =
{
	"255 0 0",
	"0 0 255",
	"255 255 255",
	"0 255 0",
	"255 192 203",
	"255 255 0"
};

static const char faceColorChar[MAX_FACES] =
{'R', 'B', 'W', 'G', 'P', 'Y'};
#else

#if defined( USE_SOUND ) && defined( USE_NAS )
Display *dsp;
#endif

#ifndef LOGPATH
#ifdef VMS
#define LOGPATH "SYS$SCRATCH:"
#else
#define LOGPATH "/usr/tmp"
#endif
#endif

static Boolean setValuesPuzzle(Widget current, Widget request, Widget renew);
static void destroyPuzzle(Widget old);
static void initializePuzzle(Widget request, Widget renew);

SkewbClassRec skewbClassRec =
{
	{
		(WidgetClass) & widgetClassRec,		/* superclass */
		(char *) "Skewb",	/* class name */
		sizeof (SkewbRec),	/* widget size */
		NULL,		/* class initialize */
		NULL,		/* class part initialize */
		FALSE,		/* class inited */
		(XtInitProc) initializePuzzle,	/* initialize */
		NULL,		/* initialize hook */
		XtInheritRealize,	/* realize */
		NULL,		/* actions */
		0,		/* num actions */
		NULL,		/* resources */
		0,		/* num resources */
		NULLQUARK,	/* xrm class */
		TRUE,		/* compress motion */
		TRUE,		/* compress exposure */
		TRUE,		/* compress enterleave */
		TRUE,		/* visible interest */
		(XtWidgetProc) destroyPuzzle,	/* destroy */
		NULL,		/* resize */
		NULL,		/* expose */
		(XtSetValuesFunc) setValuesPuzzle,	/* set values */
		NULL,		/* set values hook */
		XtInheritSetValuesAlmost,	/* set values almost */
		NULL,		/* get values hook */
		NULL,		/* accept focus */
		XtVersion,	/* version */
		NULL,		/* callback private */
		NULL,		/* tm table */
		NULL,		/* query geometry */
		NULL,		/* display accelerator */
		NULL		/* extension */
	},
	{
		0		/* ignore */
	}
};

WidgetClass skewbWidgetClass = (WidgetClass) & skewbClassRec;

void
setPuzzle(SkewbWidget w, int reason)
{
	skewbCallbackStruct cb;

	cb.reason = reason;
	XtCallCallbacks((Widget) w, (char *) XtNselectCallback, &cb);
}

static void
setPuzzleMove(SkewbWidget w, int reason, int face, int position, int direction,
		int control, int fast)
{
	skewbCallbackStruct cb;

	cb.reason = reason;
	cb.face = face;
	cb.position = position;
	cb.direction = direction;
	cb.control = control;
	cb.fast = fast;
	XtCallCallbacks((Widget) w, (char *) XtNselectCallback, &cb);
}
#endif

static void
loadFont(SkewbWidget w)
{
#ifndef WINVER
	Display *display = XtDisplay(w);
	const char *altfontname = "-*-times-*-r-*-*-*-180-*";
	char buf[512];

	if (w->skewb.fontInfo) {
		XUnloadFont(XtDisplay(w), w->skewb.fontInfo->fid);
		XFreeFont(XtDisplay(w), w->skewb.fontInfo);
	}
	if (w->skewb.font && (w->skewb.fontInfo =
			XLoadQueryFont(display, w->skewb.font)) == NULL) {
#ifdef HAVE_SNPRINTF
		(void) snprintf(buf, 512,
			"Cannot open %s font.\nAttempting %s font as alternate\n",
			w->skewb.font, altfontname);
#else
		(void) sprintf(buf,
			"Cannot open %s font.\nAttempting %s font as alternate\n",
			w->skewb.font, altfontname);
#endif
		DISPLAY_WARNING(buf);
		if ((w->skewb.fontInfo = XLoadQueryFont(display,
				altfontname)) == NULL) {
#ifdef HAVE_SNPRINTF
			(void) snprintf(buf, 512,
				"Cannot open %s alternate font.\nUse the -font option to specify a font to use.\n",
				altfontname);
#else
			(void) sprintf(buf,
				"Cannot open %s alternate font.\nUse the -font option to specify a font to use.\n",
				altfontname);
#endif
			DISPLAY_WARNING(buf);
		}
	}
	if (w->skewb.fontInfo) {
		w->skewb.letterOffset.x = XTextWidth(w->skewb.fontInfo, "8", 1)
			/ 2;
		w->skewb.letterOffset.y = w->skewb.fontInfo->max_bounds.ascent
			/ 2;
	} else
#endif
	{
		w->skewb.letterOffset.x = 3;
		w->skewb.letterOffset.y = 4;
	}
}

#ifndef LOGFILE
#define LOGFILE "skewb.log"
#endif

static int facesToDirection[MAX_FACES][MAX_FACES] =
{
	{-1, BOTTOM, BOTTOM, BOTTOM, -1, TOP},
	{RIGHT, -1, RIGHT, -1, RIGHT, RIGHT},
	{TOP, LEFT, -1, RIGHT, BOTTOM, -1},
	{LEFT, -1, LEFT, -1, LEFT, LEFT},
	{-1, TOP, TOP, TOP, -1, BOTTOM},
	{BOTTOM, RIGHT, -1, LEFT, TOP, -1}
};
static int facestoPosition[MAX_FACES][MAX_FACES][MAX_ORIENT] =
{
	{
		{-1, -1, -1, -1},
		{-1, -1, 0, 3},
		{-1, 0, 3, -1},
		{0, 3, -1, -1},
		{-1, -1, -1, -1},
		{1, -1, -1, 2}
	},
	{
		{2, -1, -1, 3},
		{-1, -1, -1, -1},
		{3, 2, -1, -1},
		{-1, -1, -1, -1},
		{-1, 3, 2, -1},
		{-1, -1, 3, 2}
	},
	{
		{1, -1, -1, 2},
		{-1, -1, 1, 0},
		{-1, -1, -1, -1},
		{3, 2, -1, -1},
		{-1, 0, 3, -1},
		{-1, -1, -1, -1}
	},
	{
		{0, -1, -1, 1},
		{-1, -1, -1, -1},
		{-1, -1, 1, 0},
		{-1, -1, -1, -1},
		{-1, 1, 0, -1},
		{1, 0, -1, -1}
	},
	{
		{-1, -1, -1, -1},
		{-1, -1, 2, 1},
		{1, -1, -1, 2},
		{2, 1, -1, -1},
		{-1, -1, -1, -1},
		{-1, 0, 3, -1}
	},
	{
		{-1, 0, 3, -1},
		{-1, -1, 3, 2},
		{-1, -1, -1, -1},
		{1, 0, -1, -1},
		{1, -1, -1, 2},
		{-1, -1, -1, -1}
	}
};
static SkewbLoc slideNextRow[MAX_FACES][MAX_ORIENT][MAX_ORIENT / 2] =
{
	{
		{
			{2, CW},
			{1, HALF}
		},
		{
			{5, CCW},
			{1, STRT}
		},
		{
			{3, STRT},
			{5, CW}
		},
		{
			{3, HALF},
			{2, CCW}
		}
	},
	{
		{
			{4, STRT},
			{5, CW}
		},
		{
			{0, STRT},
			{5, CCW}
		},
		{
			{2, CCW},
			{0, HALF}
		},
		{
			{2, CW},
			{4, HALF}
		}
	},
	{
		{
			{4, CW},
			{1, CCW}
		},
		{
			{0, CCW},
			{1, CW}
		},
		{
			{3, CCW},
			{0, CW}
		},
		{
			{3, CW},
			{4, CCW}
		}
	},
	{
		{
			{4, HALF},
			{2, CCW}
		},
		{
			{0, HALF},
			{2, CW}
		},
		{
			{5, CW},
			{0, STRT}
		},
		{
			{5, CCW},
			{4, STRT}
		}
	},
	{
		{
			{5, CW},
			{1, STRT}
		},
		{
			{2, CCW},
			{1, HALF}
		},
		{
			{3, HALF},
			{2, CW}
		},
		{
			{3, STRT},
			{5, CCW}
		}
	},
	{
		{
			{0, CW},
			{1, CW}
		},
		{
			{4, CCW},
			{1, CCW}
		},
		{
			{3, CW},
			{4, CW}
		},
		{
			{3, CCW},
			{0, CCW}
		}
	}
};
static SkewbLoc minToMaj[MAX_FACES][MAX_ORIENT] =
{				/* other equivalent mappings possible */
	{
		{3, CW},
		{2, STRT},
		{1, CCW},
		{5, STRT}
	},
	{
		{2, STRT},
		{4, CCW},
		{5, HALF},
		{0, CW}
	},
	{
		{3, STRT},
		{4, STRT},
		{1, STRT},
		{0, STRT}
	},
	{
		{5, HALF},
		{4, CW},
		{2, STRT},
		{0, CCW}
	},
	{
		{3, CCW},
		{5, STRT},
		{1, CW},
		{2, STRT}
	},
	{
		{3, HALF},
		{0, STRT},
		{1, HALF},
		{4, STRT}
	}
};

static SkewbLoc slideNextFace[MAX_FACES][MAX_ORIENT] =
{
	{
		{5, STRT},
		{3, CW},
		{2, STRT},
		{1, CCW}
	},
	{
		{0, CW},
		{2, STRT},
		{4, CCW},
		{5, HALF}
	},
	{
		{0, STRT},
		{3, STRT},
		{4, STRT},
		{1, STRT}
	},
	{
		{0, CCW},
		{5, HALF},
		{4, CW},
		{2, STRT}
	},
	{
		{2, STRT},
		{3, CCW},
		{5, STRT},
		{1, CW}
	},
	{
		{4, STRT},
		{3, HALF},
		{0, STRT},
		{1, HALF}
	}
};

static int faceToRotate[MAX_FACES][MAX_ORIENT] =
{
	{3, 2, 1, 5},
	{2, 4, 5, 0},
	{3, 4, 1, 0},
	{5, 4, 2, 0},
	{3, 5, 1, 2},
	{3, 0, 1, 4}
};

static SkewbLocPos orthToDiag[MAX_FACES][MAX_ORIENT][MAX_ORIENT] =
{
	{
		{
			{3, 0, 1},
			{5, 1, 0},
			{3, 0, 3},
			{5, 1, 2}
		},
		{
			{3, 3, 0},
			{2, 0, 1},
			{3, 3, 2},
			{2, 0, 3}
		},
		{
			{1, 0, 3},
			{2, 3, 0},
			{1, 0, 1},
			{2, 3, 2}
		},
		{
			{1, 3, 2},
			{5, 2, 1},
			{1, 3, 0},
			{5, 2, 3}
		}
	},
	{
		{
			{2, 3, 0},
			{0, 2, 1},
			{2, 3, 2},
			{0, 2, 3}
		},
		{
			{2, 2, 3},
			{4, 3, 0},
			{2, 2, 1},
			{4, 3, 2}
		},
		{
			{5, 3, 2},
			{4, 2, 3},
			{5, 3, 0},
			{4, 2, 1}
		},
		{
			{5, 2, 1},
			{0, 3, 2},
			{5, 2, 3},
			{0, 3, 0}
		}
	},
	{
		{
			{3, 3, 0},
			{0, 1, 0},
			{3, 3, 2},
			{0, 1, 2}
		},
		{
			{3, 2, 3},
			{4, 0, 1},
			{3, 2, 1},
			{4, 0, 3}
		},
		{
			{1, 1, 0},
			{4, 3, 0},
			{1, 1, 2},
			{4, 3, 2}
		},
		{
			{1, 0, 3},
			{0, 2, 1},
			{1, 0, 1},
			{0, 2, 3}
		}
	},
	{
		{
			{5, 1, 2},
			{0, 0, 3},
			{5, 1, 0},
			{0, 0, 1}
		},
		{
			{5, 0, 1},
			{4, 1, 2},
			{5, 0, 3},
			{4, 1, 0}
		},
		{
			{2, 1, 0},
			{4, 0, 1},
			{2, 1, 2},
			{4, 0, 3}
		},
		{
			{2, 0, 3},
			{0, 1, 0},
			{2, 0, 1},
			{0, 1, 2}
		}
	},
	{
		{
			{3, 2, 3},
			{2, 1, 0},
			{3, 2, 1},
			{2, 1, 2}
		},
		{
			{3, 1, 2},
			{5, 0, 1},
			{3, 1, 0},
			{5, 0, 3}
		},
		{
			{1, 2, 1},
			{5, 3, 0},
			{1, 2, 3},
			{5, 3, 2}
		},
		{
			{1, 1, 0},
			{2, 2, 1},
			{1, 1, 2},
			{2, 2, 3}
		}
	},
	{
		{
			{3, 1, 2},
			{4, 1, 0},
			{3, 1, 0},
			{4, 1, 2}
		},
		{
			{3, 0, 1},
			{0, 0, 1},
			{3, 0, 3},
			{0, 0, 3}
		},
		{
			{1, 3, 2},
			{0, 3, 0},
			{1, 3, 0},
			{0, 3, 2}
		},
		{
			{1, 2, 1},
			{4, 2, 1},
			{1, 2, 3},
			{4, 2, 3}
		}
	}
};

static SkewbStack undo = {NULL, NULL, NULL, 0};
static SkewbStack redo = {NULL, NULL, NULL, 0};

static void
checkPieces(SkewbWidget w)
{
	char *buf1 = NULL, *buf2 = NULL;

	if (w->skewb.delay < 0) {
		intCat(&buf1, "Delay cannot be negative (",
			w->skewb.delay);
		stringCat(&buf2, buf1, "), taking absolute value");
		free(buf1);
		DISPLAY_WARNING(buf2);
		free(buf2);
		w->skewb.delay = -w->skewb.delay;
	}
}

Boolean
checkSolved(const SkewbWidget w)
{
	int face, position;
	SkewbLoc test = {0, FALSE};

	for (face = 0; face < MAX_FACES; face++)
		for (position = 0; position < MAX_CUBES; position++) {
			if (!position) {
				test.face = w->skewb.cubeLoc[face][position].face;
				test.rotation = w->skewb.cubeLoc[face][position].rotation;
			} else if (test.face !=		/*face */
				  w->skewb.cubeLoc[face][position].face ||
				  (w->skewb.orient && test.rotation !=		/*STRT - MAX_ORIENT */
				  w->skewb.cubeLoc[face][position].rotation)) {
				return False;
			}
		}
	return True;
}

#ifdef DEBUG
void
printCube(const SkewbWidget w)
{
	int face, position;

	for (face = 0; face < MAX_FACES; face++) {
		for (position = 0; position < MAX_CUBES; position++)
			(void) printf("%d %d  ", w->skewb.cubeLoc[face][position].face,
				w->skewb.cubeLoc[face][position].rotation);
		(void) printf("\n");
	}
	(void) printf("\n");
}
#endif

static void
drawDiamond(SkewbWidget w, int face, int offset)
{
	if (w->skewb.dim == 2)
		drawDiamond2D((Skewb2DWidget) w, face, offset);
	else if (w->skewb.dim == 3)
		drawDiamond3D((Skewb3DWidget) w, face, offset);
}

static void
drawDiamondAll(SkewbWidget w, int face, int offset)
{
	drawDiamond(w, face, offset);
#ifdef HAVE_OPENGL
	if (w->skewb.dim == 4)
		drawAllPiecesGL((SkewbGLWidget) w);
#endif
}

static void
drawTriangle(SkewbWidget w, int face, int position, int offset)
{
	if (w->skewb.dim == 2)
		drawTriangle2D((Skewb2DWidget) w, face, position, offset);
	else if (w->skewb.dim == 3)
		drawTriangle3D((Skewb3DWidget) w, face, position, offset);
}

static void
drawTriangleAll(SkewbWidget w, int face, int position, int offset)
{
	drawTriangle(w, face, position, offset);
#ifdef HAVE_OPENGL
	if (w->skewb.dim == 4)
		drawAllPiecesGL((SkewbGLWidget) w);
#endif
}

void
drawAllPieces(SkewbWidget w)
{
	int face, position;

#ifdef HAVE_OPENGL
	if (w->skewb.dim == 4) {
		drawAllPiecesGL((SkewbGLWidget) w);
		return;
	}
#endif
	for (face = 0; face < MAX_FACES; face++) {
		drawDiamond(w, face, FALSE);
		for (position = 0; position < MAX_ORIENT; position++)
			drawTriangle(w, face, position, FALSE);
	}
}

static void
drawFrame(const SkewbWidget w, const Boolean focus)
{
	if (w->skewb.dim == 2)
		drawFrame2D((Skewb2DWidget) w, focus);
	else if (w->skewb.dim == 3)
		drawFrame3D((Skewb3DWidget) w, focus);
/*#ifdef HAVE_OPENGL
	else if (w->skewb.dim == 4)
		drawFrameGL((SkewbGLWidget) w, focus);
#endif*/
}

static void
moveNoPieces(SkewbWidget w)
{
	setPuzzle(w, ACTION_ILLEGAL);
}

static void
rotateFace(SkewbWidget w, int face, int direction)
{
	int corner;

	/* Read Face */
	for (corner = 0; corner < MAX_ORIENT; corner++)
		w->skewb.faceLoc[corner] = w->skewb.cubeLoc[face][corner];
	/* Write Face */
	for (corner = 0; corner < MAX_ORIENT; corner++) {
		w->skewb.cubeLoc[face][corner] = (direction == CW) ?
			w->skewb.faceLoc[(corner + MAX_ORIENT - 1) % MAX_ORIENT] :
			w->skewb.faceLoc[(corner + 1) % MAX_ORIENT];
		w->skewb.cubeLoc[face][corner].rotation =
			(w->skewb.cubeLoc[face][corner].rotation + direction) %
			MAX_ORIENT;
		drawTriangle(w, face, corner, FALSE);
	}
	w->skewb.cubeLoc[face][MAX_ORIENT].rotation =
		(w->skewb.cubeLoc[face][MAX_ORIENT].rotation + direction) %
		MAX_ORIENT;
	drawDiamond(w, face, FALSE);
}

static void
readFace(SkewbWidget w, int face, int h)
{
	int position;

	for (position = 0; position < MAX_CUBES; position++)
		w->skewb.rowLoc[h][position] = w->skewb.cubeLoc[face][position];
}

static void
writeFace(SkewbWidget w, int face, int rotate, int h)
{
	int corner, newCorner;

	for (corner = 0; corner < MAX_ORIENT; corner++) {
		newCorner = (corner + rotate) % MAX_ORIENT;
		w->skewb.cubeLoc[face][newCorner] = w->skewb.rowLoc[h][corner];
		w->skewb.cubeLoc[face][newCorner].rotation =
			(w->skewb.cubeLoc[face][newCorner].rotation + rotate) %
			MAX_ORIENT;
		drawTriangle(w, face, (corner + rotate) % MAX_ORIENT, FALSE);
	}
	w->skewb.cubeLoc[face][MAX_ORIENT] = w->skewb.rowLoc[h][MAX_ORIENT];
	w->skewb.cubeLoc[face][MAX_ORIENT].rotation =
		(w->skewb.cubeLoc[face][MAX_ORIENT].rotation + rotate) %
		MAX_ORIENT;
	drawDiamond(w, face, FALSE);
}

static void
readDiagonal(SkewbWidget w, int face, int corner, int orient, int size)
{
	int g;

	if (size == MINOR)
		w->skewb.minorLoc[orient] = w->skewb.cubeLoc[face][corner];
	else {			/* size == MAJOR */
		for (g = 1; g < MAX_ORIENT; g++)
			w->skewb.majorLoc[orient][g - 1] =
				w->skewb.cubeLoc[face][(corner + g) %
				MAX_ORIENT];
		w->skewb.majorLoc[orient][MAX_ORIENT - 1] =
			w->skewb.cubeLoc[face][MAX_ORIENT];
	}
}

static void
rotateDiagonal(SkewbWidget w, int rotate, int orient, int size)
{
	int g;

	if (size == MINOR)
		w->skewb.minorLoc[orient].rotation =
			(w->skewb.minorLoc[orient].rotation + rotate) % MAX_ORIENT;
	else			/* size == MAJOR */
		for (g = 0; g < MAX_ORIENT; g++)
			w->skewb.majorLoc[orient][g].rotation =
				(w->skewb.majorLoc[orient][g].rotation + rotate) %
				MAX_ORIENT;
}

static void
writeDiagonal(SkewbWidget w, int face, int corner, int orient, int size)
{
	int g, h;

	if (size == MINOR) {
		w->skewb.cubeLoc[face][corner] = w->skewb.minorLoc[orient];
		drawTriangle(w, face, corner, FALSE);
	} else {		/* size == MAJOR */
		w->skewb.cubeLoc[face][MAX_ORIENT] =
			w->skewb.majorLoc[orient][MAX_ORIENT - 1];
		drawDiamond(w, face, FALSE);
		for (g = 1; g < MAX_ORIENT; g++) {
			h = (corner + g) % MAX_ORIENT;
			w->skewb.cubeLoc[face][h] = w->skewb.majorLoc[orient][g - 1];
			drawTriangle(w, face, h, FALSE);
		}
	}
}

static void
movePieces(SkewbWidget w, int face, int position, int direction,
		int control, int fast)
{
	int oldFace = face, pos = position, dir = direction;
	int newFace, newDirection, newCorner, k, size, rotate;

	if ((direction + position) % 2 == 0 && direction < MAX_ORIENT)
		(void) printf("wrong face %d, position %d, direction %d\n",
			face, position, direction);
#ifdef HAVE_OPENGL
	if (control != 2 && fast != INSTANT && w->skewb.dim == 4) {
		movePiecesGL((SkewbGLWidget) w, oldFace, position, dir,
			(control == 1), fast);
	}
#endif
	if (dir < 2 * MAX_ORIENT) {
		/* position as MAX_ORIENT is ambiguous */
		for (size = MINOR; size <= MAJOR; size++) {
			readDiagonal((SkewbWidget) w, oldFace, pos, 0, size);
			for (k = 1; k <= MAX_ROTATE; k++) {
				newFace = slideNextRow[oldFace][pos][dir / 2].face;
				rotate = slideNextRow[oldFace][pos][dir / 2].rotation %
					MAX_ORIENT;
				newDirection = (rotate + dir) % MAX_ORIENT;
				newCorner = (rotate + pos) % MAX_ORIENT;
				if (k != MAX_ROTATE)
					readDiagonal((SkewbWidget) w, newFace, newCorner, k, size);
				rotateDiagonal((SkewbWidget) w, rotate, k - 1, size);
				writeDiagonal(w, newFace, newCorner, k - 1, size);
				oldFace = newFace;
				pos = newCorner;
				dir = newDirection;
			}
			if (size == MINOR) {
				newFace = minToMaj[oldFace][pos].face;
				rotate = minToMaj[oldFace][pos].rotation % MAX_ORIENT;
				dir = (rotate + dir) % MAX_ORIENT;
				pos = (pos + rotate + 2) % MAX_ORIENT;
				oldFace = newFace;
			}
		}
	} else {
		rotateFace(w, faceToRotate[oldFace][dir % MAX_ORIENT], CW);
		rotateFace(w, faceToRotate[oldFace][(dir + 2) % MAX_ORIENT], CCW);
		readFace((SkewbWidget) w, oldFace, 0);
		for (k = 1; k <= MAX_ORIENT; k++) {
			newFace = slideNextFace[oldFace][dir % MAX_ORIENT].face;
			rotate = slideNextFace[oldFace][dir % MAX_ORIENT].rotation;
			newDirection = (rotate + dir) % MAX_ORIENT;
			if (k != MAX_ORIENT)
				readFace((SkewbWidget) w, newFace, k);
			writeFace(w, newFace, rotate, k - 1);
			oldFace = newFace;
			dir = newDirection;
		}
	}
#ifdef HAVE_OPENGL
	if (!control && fast == INSTANT && w->skewb.dim == 4) {
		drawAllPiecesGL((SkewbGLWidget) w);
	}
#endif
#ifdef DEBUG
	printCube(w);
#endif

}

static void
moveControlCb(SkewbWidget w, int face, int position, int direction, int fast)
{
	int oldFace = face, pos = position, dir = direction;
	int newFace, rotate;

	if (dir >= 2 * MAX_ORIENT) {
		SkewbLocPos newpos;

		newpos = orthToDiag[oldFace][pos][dir % MAX_ORIENT];
		oldFace = newpos.face;
		pos = newpos.position;
		dir = newpos.direction;
	}
	movePieces(w, oldFace, pos, dir, 1, fast);
	setPuzzleMove(w, ACTION_CONTROL, oldFace, pos, dir, 1, fast);
	newFace = minToMaj[oldFace][pos].face;
	rotate = minToMaj[oldFace][pos].rotation % MAX_ORIENT;
	dir = (rotate + dir) % MAX_ORIENT;
	pos = (pos + rotate + 2) % MAX_ORIENT;
	movePieces(w, newFace, pos, dir, 2, fast);
	setPuzzleMove(w, ACTION_CONTROL, newFace, pos, dir, 2, fast);
}

static void
moveAltCb(SkewbWidget w, int face, int position, int direction, int fast)
{
	movePieces(w, face, position, direction, 0, fast);
	setPuzzleMove(w, ACTION_CONTROL, face, position, direction, 0, fast);
}

void
movePuzzle(SkewbWidget w, int face, int position, int direction, int control,
		int fast)
{
	if (control == 2)
		moveAltCb(w, face, position, direction, fast);
	else if (control == 1)
		moveControlCb(w, face, position, direction, fast);
	else {
		SkewbLocPos newpos;

		newpos.face = face;
		newpos.position = position;
		newpos.direction = direction;
		if (direction >= 2 * MAX_ORIENT)
			newpos = orthToDiag[face][position][direction % MAX_ORIENT];
		movePieces(w, newpos.face, newpos.position, newpos.direction,
			0, fast);
		w->skewb.currentFace = IGNORE_DIR;
		w->skewb.currentPosition = IGNORE_DIR;
		setPuzzleMove(w, ACTION_MOVED, newpos.face, newpos.position,
			newpos.direction, 0, fast);
	}
#ifdef USE_SOUND
	if (w->skewb.sound) {
		playSound(MOVESOUND);
	}
#endif
	setMove(&undo, direction, control, face, position);
	flushMoves(w, &redo, FALSE);
}

void
movePuzzleDelay(SkewbWidget w, const int face, const int position,
		const int direction, const int control)
{
	movePuzzle(w, face, position, direction, control, NORMAL);
	Sleep((unsigned int) w->skewb.delay);
}

static Boolean
selectPieces(SkewbWidget w, int x, int y, int *face, int *position)
{
	if (w->skewb.dim == 2)
		return selectPieces2D((Skewb2DWidget) w, x, y,
			face, position);
	else if (w->skewb.dim == 3)
		return selectPieces3D((Skewb3DWidget) w, x, y,
			face, position);
#ifdef HAVE_OPENGL
	else if (w->skewb.dim == 4)
		return selectPiecesGL((SkewbGLWidget) w, x, y,
			face, position);
#endif
	return False;
}

static int
checkMoveDir(int position1, int position2, int *direction)
{
	if (position1 == position2)
		return 2;
	if (!((position1 - position2 + MAX_ORIENT) % 2))
		return 0;
	switch (position1) {
	case 0:
		*direction = (position2 == 1) ? 2 : 3;
		break;
	case 1:
		*direction = (position2 == 2) ? 3 : 0;
		break;
	case 2:
		*direction = (position2 == 3) ? 0 : 1;
		break;
	case 3:
		*direction = (position2 == 0) ? 1 : 2;
		break;
	default:
		return 0;
	}
	*direction += 2 * MAX_ORIENT;
	return 1;
}

static Boolean
narrowSelection(SkewbWidget w, int *face, int *position, int *direction)
{
	if (w->skewb.dim == 2)
		return narrowSelection2D((Skewb2DWidget) w, face, position, direction);
	else if (w->skewb.dim == 3)
		return narrowSelection3D((Skewb3DWidget) w, face, position, direction);
#ifdef HAVE_OPENGL
	else if (w->skewb.dim == 4)
		return narrowSelectionGL((SkewbGLWidget) w, face, position, direction);
#endif
	return False;
}

static Boolean
positionPieces(SkewbWidget w, int x, int y, int *face, int *position, int *direction)
{
	if (!selectPieces(w, x, y, face, position))
		return False;
	return narrowSelection(w, face, position, direction);
}

void
movePuzzleInput(SkewbWidget w, int x, int y, int direction, int control,
		int alt)
{
	int face, position;

	if (!w->skewb.practice && !control && !alt && checkSolved(w)) {
		moveNoPieces(w);
		return;
	}
	if (!positionPieces(w, x, y, &face, &position, &direction))
		return;
	if (alt)
		control = 2;
	else
		control = (control) ? 1 : 0;
	if (position == MAX_ORIENT)
		return;
	movePuzzle(w, face, position, direction, control, NORMAL);
	if (!control && checkSolved(w)) {
		setPuzzle(w, ACTION_SOLVED);
	}
}

static void
resetPieces(SkewbWidget w)
{
	int face, position;

	for (face = 0; face < MAX_FACES; face++)
		for (position = 0; position < MAX_CUBES; position++) {
			w->skewb.cubeLoc[face][position].face = face;
			w->skewb.cubeLoc[face][position].rotation = STRT - MAX_ORIENT;
		}
	flushMoves(w, &undo, TRUE);
	flushMoves(w, &redo, FALSE);
	w->skewb.started = False;
	w->skewb.currentFace = IGNORE_DIR;
	w->skewb.currentDirection = IGNORE_DIR;
}

static void
readFile(SkewbWidget w, FILE *fp, char *name)
{
	int c, orient, practice, moves;

	while ((c = getc(fp)) != EOF && c != SYMBOL);
	if (fscanf(fp, "%d", &orient) != 1) {
		(void) fprintf(stderr,
			"corrupt record, expecting an integer for orient\n");
		return;
	}
	if (w->skewb.orient != (Boolean) orient) {
		setPuzzle(w, ACTION_ORIENTIZE);
	}
	while ((c = getc(fp)) != EOF && c != SYMBOL);
	if (fscanf(fp, "%d", &practice) != 1) {
		(void) fprintf(stderr,
			"corrupt record, expecting an integer for practice\n");
		return;
	}
	if (w->skewb.practice != (Boolean) practice) {
		setPuzzle(w, ACTION_PRACTICE);
	}
#ifdef WINVER
	resetPieces(w);
#endif
	while ((c = getc(fp)) != EOF && c != SYMBOL);
	if (fscanf(fp, "%d", &moves) != 1) {
		(void) fprintf(stderr,
			"corrupt record, expecting an integer for moves\n");
		return;
	}
	if (!scanStartPosition(fp, w))
		return;
	setPuzzle(w, ACTION_RESTORE);
#ifdef WINVER
	setStartPosition(w);
#endif
	if (!scanMoves(fp, w, moves))
		return;
	(void) printf("%s: orient %s, practice %s, moves %d\n",
		name, BOOL_STRING(orient), BOOL_STRING(practice), moves);
}

static void
getPieces(SkewbWidget w)
{
	FILE *fp;
	char *buf1 = NULL, *buf2 = NULL;
	char *fname, *lname, *name;

	stringCat(&buf1, CURRENTDELIM, LOGFILE);
	lname = buf1;
	stringCat(&buf1, LOGPATH, FINALDELIM);
	stringCat(&buf2, buf1, LOGFILE);
	free(buf1);
	fname = buf2;
	/* Try current directory first. */
	name = lname;
	if ((fp = fopen(name, "r")) == NULL) {
		name = fname;
		if ((fp = fopen(name, "r")) == NULL) {
			stringCat(&buf1, "Cannot read ", lname);
			stringCat(&buf2, buf1, " or ");
			free(buf1);
			stringCat(&buf1, buf2, fname);
			free(buf2);
			DISPLAY_WARNING(buf1);
			free(buf1);
			free(lname);
			free(fname);
			return;
		}
/* Probably annoying */
#if 0
		else {
			stringCat(&buf1, "Cannot read ", lname);
			stringCat(&buf2, buf1, ", falling back to ");
			free(buf1);
			stringCat(&buf1, buf2, fname);
			free(buf2);
			DISPLAY_WARNING(buf1);
			free(buf1);
			return;
		}
#endif
	}
	flushMoves(w, &undo, TRUE);
	flushMoves(w, &redo, FALSE);
	readFile(w, fp, name);
	(void) fclose(fp);
	free(lname);
	free(fname);
	w->skewb.cheat = True; /* Assume the worst. */
	setPuzzle(w, ACTION_CHEAT);
}

static void
writePieces(SkewbWidget w)
{
	FILE *fp;
	char *buf1 = NULL, *buf2 = NULL;
	char *fname, *lname, *name;

	stringCat(&buf1, CURRENTDELIM, LOGFILE);
	lname = buf1;
	stringCat(&buf1, LOGPATH, FINALDELIM);
	stringCat(&buf2, buf1, LOGFILE);
	free(buf1);
	fname = buf2;
	/* Try current directory first. */
	name = lname;
	if ((fp = fopen(name, "w")) == NULL) {
		name = fname;
		if ((fp = fopen(name, "w")) == NULL) {
			stringCat(&buf1, "Cannot write to ", lname);
			stringCat(&buf2, buf1, " or ");
			free(buf1);
			stringCat(&buf1, buf2, fname);
			free(buf2);
			DISPLAY_WARNING(buf1);
			free(buf1);
			free(lname);
			free(fname);
			return;
		}
/* Probably annoying */
#if 0
		else {
			stringCat(&buf1, "Cannot write to ", lname);
			stringCat(&buf2, buf1, ", falling back to ");
			free(buf1);
			stringCat(&buf1, buf2, fname);
			free(buf2);
			DISPLAY_WARNING(buf1);
			free(buf1);
			return;
		}
#endif
	}
	(void) fprintf(fp, "orient%c %d\n", SYMBOL,
		(w->skewb.orient) ? 1 : 0);
	(void) fprintf(fp, "practice%c %d\n", SYMBOL,
		(w->skewb.practice) ? 1 : 0);
	(void) fprintf(fp, "moves%c %d\n", SYMBOL,
		numMoves(&undo));
	printStartPosition(fp, w);
	printMoves(fp, &undo);
	(void) fclose(fp);
	(void) printf("Saved to %s\n", name);
	free(lname);
	free(fname);
}

static void
undoPieces(SkewbWidget w)
{
	if (madeMoves(&undo)) {
		int face, position, direction, control;

		getMove(&undo, &direction, &control,
			&face, &position);
		setMove(&redo, direction, control,
			face, position);
		if (direction < 2 * MAX_ORIENT) {
			direction = (direction < MAX_ORIENT) ?
				(direction + MAX_ORIENT / 2) % MAX_ORIENT :
				3 * MAX_ORIENT - direction;
		} else {
			direction = (direction + MAX_ORIENT / 2) % MAX_ORIENT +
				2 * MAX_ORIENT;
		}
		if (control == 2)
			moveAltCb(w, face, position, direction, DOUBLE);
		else if (control == 1)
			moveControlCb(w, face, position, direction, DOUBLE);
		else {
			if (direction >= 2 * MAX_ORIENT) {
				SkewbLocPos newpos;

				newpos = orthToDiag[face][position][direction % MAX_ORIENT];
				face = newpos.face;
				position = newpos.position;
				direction = newpos.direction;
			}
			movePieces(w, face, position, direction, 0, DOUBLE);
			setPuzzleMove(w, ACTION_UNDO, face, position, direction, 0, DOUBLE);
			if (checkSolved(w)) {
				setPuzzle(w, ACTION_SOLVED);
			}
		}
	}
}

static void
redoPieces(SkewbWidget w)
{
	if (madeMoves(&redo)) {
		int face, position, direction, control;

		getMove(&redo, &direction, &control,
			&face, &position);
		setMove(&undo, direction, control,
			face, position);
		if (control == 2)
			moveAltCb(w, face, position, direction, DOUBLE);
		else if (control == 1)
			moveControlCb(w, face, position, direction, DOUBLE);
		else {
			if (direction >= 2 * MAX_ORIENT) {
				SkewbLocPos newpos;

				newpos = orthToDiag[face][position][direction % MAX_ORIENT];
				face = newpos.face;
				position = newpos.position;
				direction = newpos.direction;
			}
			movePieces(w, face, position, direction, 0, DOUBLE);
			setPuzzleMove(w, ACTION_REDO, face, position, direction, 0, DOUBLE);
			if (checkSolved(w)) {
				setPuzzle(w, ACTION_SOLVED);
			}
		}
	}
}

static void
clearPieces(SkewbWidget w)
{
	setPuzzle(w, ACTION_CLEAR);
}

static void
practicePieces(SkewbWidget w)
{
	setPuzzle(w, ACTION_PRACTICE);
}

static void
randomizePieces(SkewbWidget w)
{
	int face, position, direction;
	int big = MAX_CUBES * 3 + NRAND(2);

	w->skewb.cheat = False;
	setPuzzle(w, ACTION_CHEAT);
	if (w->skewb.practice)
		practicePieces(w);
	setPuzzle(w, ACTION_RESET);

#ifdef DEBUG
	big = 3;
#endif

	while (big--) {
		face = NRAND(MAX_FACES);
		position = NRAND(MAX_ORIENT);
		direction = ((NRAND(2)) ? position + 1 : position + 3) % MAX_ORIENT;
		movePuzzle(w, face, position, direction, FALSE, INSTANT);
	}
	flushMoves(w, &undo, TRUE);
	flushMoves(w, &redo, FALSE);
	setPuzzle(w, ACTION_RANDOMIZE);
	if (checkSolved(w)) {
		setPuzzle(w, ACTION_SOLVED);
	}
}

static void
solvePieces(SkewbWidget w)
{
	if (checkSolved(w))
		return;
	solveSomePieces(w);
}

static void
orientizePieces(SkewbWidget w)
{
	setPuzzle(w, ACTION_ORIENTIZE);
}

static void
viewPieces(SkewbWidget w)
{
	setPuzzle(w, ACTION_VIEW);
}

static void
speedPieces(SkewbWidget w)
{
	w->skewb.delay -= 5;
	if (w->skewb.delay < 0)
		w->skewb.delay = 0;
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	setPuzzle(w, ACTION_SPEED);
#endif
}

static void
slowPieces(SkewbWidget w)
{
	w->skewb.delay += 5;
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	setPuzzle(w, ACTION_SPEED);
#endif
}

static void
soundPieces(SkewbWidget w)
{
	w->skewb.sound = !w->skewb.sound;
	setPuzzle(w, ACTION_SOUND);
}

#ifdef WINVER
static void
setValuesPuzzle(SkewbWidget w)
{
	struct tagColor {
		int red, green, blue;
	} color;
	char szBuf[80], buf[20], charbuf[2];
	int face;

	w->skewb.orient = (BOOL) GetPrivateProfileInt(SECTION,
		"orient", DEFAULT_ORIENT, INIFILE);
	w->skewb.practice = (BOOL) GetPrivateProfileInt(SECTION,
		"practice", DEFAULT_PRACTICE, INIFILE);
#ifdef HAVE_OPENGL
	w->skewb.dim = (int) GetPrivateProfileInt(SECTION, "dim", 4, INIFILE);
#else
	w->skewb.dim = (int) GetPrivateProfileInt(SECTION, "dim", 3, INIFILE);
#endif
	w->skewb.view = (int) GetPrivateProfileInt(SECTION, "view", 1, INIFILE);
	w->skewb.mono = (BOOL) GetPrivateProfileInt(SECTION,
		"mono", DEFAULT_MONO, INIFILE);
	w->skewb.reverse = (BOOL) GetPrivateProfileInt(SECTION,
		"reverseVideo", DEFAULT_REVERSE, INIFILE);
	/* Cyan */
	(void) GetPrivateProfileString(SECTION,
		"frameColor", "0 255 255", szBuf, sizeof (szBuf), INIFILE);
	(void) sscanf(szBuf, "%d %d %d",
		&(color.red), &(color.green), &(color.blue));
	w->skewb.frameGC = RGB(color.red, color.green, color.blue);
	/* gray25 */
	(void) GetPrivateProfileString(SECTION,
		"pieceBorder", "64 64 64", szBuf, sizeof (szBuf), INIFILE);
	(void) sscanf(szBuf, "%d %d %d",
		&(color.red), &(color.green), &(color.blue));
	w->skewb.borderGC = RGB(color.red, color.green, color.blue);
	/* #AEB2C3 */
	(void) GetPrivateProfileString(SECTION,
		"background", "174 178 195", szBuf, sizeof (szBuf), INIFILE);
	(void) sscanf(szBuf, "%d %d %d",
		&(color.red), &(color.green), &(color.blue));
	w->skewb.inverseGC = RGB(color.red, color.green, color.blue);
	for (face = 0; face < MAX_FACES; face++) {
#ifdef HAVE_SNPRINTF
		(void) snprintf(buf, 20, "faceColor%d", face);
#else
		(void) sprintf(buf, "faceColor%d", face);
#endif
		(void) GetPrivateProfileString(SECTION,
			buf, faceColorString[face],
			szBuf, sizeof (szBuf), INIFILE);
		(void) sscanf(szBuf, "%d %d %d",
			&(color.red), &(color.green), &(color.blue));
		w->skewb.faceGC[face] =
			RGB(color.red, color.green, color.blue);
#ifdef HAVE_SNPRINTF
		(void) snprintf(buf, 20, "faceChar%d", face);
#else
		(void) sprintf(buf, "faceChar%d", face);
#endif
		charbuf[0] = faceColorChar[face];
		charbuf[1] = '\0';
		(void) GetPrivateProfileString(SECTION,
			buf, charbuf, szBuf, sizeof (szBuf), INIFILE);
		w->skewb.faceChar[face] = szBuf[0];
	}
	w->skewb.delay = (int) GetPrivateProfileInt(SECTION,
		"delay", 10, INIFILE);
	w->skewb.sound = (BOOL) GetPrivateProfileInt(SECTION,
		"sound", FALSE, INIFILE);
	(void) GetPrivateProfileString(SECTION,
		"moveSound", MOVESOUND, szBuf, sizeof (szBuf), INIFILE);
	(void) strncpy(w->skewb.moveSound, szBuf, 80);
	(void) GetPrivateProfileString(SECTION,
		"userName", "guest", szBuf, sizeof (szBuf), INIFILE);
	(void) strncpy(w->skewb.userName, szBuf, 80);
	(void) GetPrivateProfileString(SECTION,
		"scoreFile", "", szBuf, sizeof (szBuf), INIFILE);
	(void) strncpy(w->skewb.scoreFile, szBuf, 80);
}

void
destroyPuzzle(HBRUSH brush)
{
	deleteMoves(&undo);
	deleteMoves(&redo);
	(void) DeleteObject(brush);
	PostQuitMessage(0);
}

void
resizePuzzle(SkewbWidget w)
{
	if (w->skewb.dim == 2)
		resizePuzzle2D((Skewb2DWidget) w);
	else if (w->skewb.dim == 3)
		resizePuzzle3D((Skewb3DWidget) w);
#ifdef HAVE_OPENGL
	else if (w->skewb.dim == 4)
		resizePuzzleGL((SkewbGLWidget) w);
#endif
}

void
sizePuzzle(SkewbWidget w)
{
	resetPieces(w);
	resizePuzzle(w);
}

void
exposePuzzle(SkewbWidget w)
{
	if (w->skewb.dim == 2)
		exposePuzzle2D((Skewb2DWidget) w);
	else if (w->skewb.dim == 3)
		exposePuzzle3D((Skewb3DWidget) w);
#ifdef HAVE_OPENGL
	else if (w->skewb.dim == 4)
		exposePuzzleGL((SkewbGLWidget) w);
#endif
}

#else
static void
getColor(SkewbWidget w, int face)
{
	XGCValues values;
	XtGCMask valueMask;
	XColor colorCell, rgb;

	valueMask = GCForeground | GCBackground;
	if (w->skewb.reverse) {
		values.background = w->skewb.foreground;
	} else {
		values.background = w->skewb.background;
	}
	if (!w->skewb.mono || w->skewb.dim == 4) {
		if (!w->skewb.faceName[face]) {
			char *buf1;

			intCat(&buf1, "Color name null for face ", face);
			DISPLAY_WARNING(buf1);
			free(buf1);
		} else if (XAllocNamedColor(XtDisplay(w),
				DefaultColormapOfScreen(XtScreen(w)),
				w->skewb.faceName[face], &colorCell, &rgb)) {
			values.foreground = w->skewb.faceColor[face] = colorCell.pixel;
			if (w->skewb.faceGC[face])
				XtReleaseGC((Widget) w, w->skewb.faceGC[face]);
			w->skewb.faceGC[face] = XtGetGC((Widget) w, valueMask, &values);
			return;
		} else {
			char *buf1, *buf2;

			stringCat(&buf1, "Color name \"",
				w->skewb.faceName[face]);
			stringCat(&buf2, buf1, "\" is not defined for face ");
			free(buf1);
			intCat(&buf1, buf2, face);
			free(buf2);
			DISPLAY_WARNING(buf1);
			free(buf1);
		}
	}
	if (w->skewb.reverse) {
		values.background = w->skewb.foreground;
		values.foreground = w->skewb.background;
	} else {
		values.background = w->skewb.background;
		values.foreground = w->skewb.foreground;
	}
	if (w->skewb.faceGC[face])
		XtReleaseGC((Widget) w, w->skewb.faceGC[face]);
	w->skewb.faceGC[face] = XtGetGC((Widget) w, valueMask, &values);
}

void
setAllColors(SkewbWidget w)
{
	XGCValues values;
	XtGCMask valueMask;
	int face;

	valueMask = GCForeground | GCBackground;

	if (w->skewb.reverse) {
		values.background = w->skewb.background;
		values.foreground = w->skewb.foreground;
	} else {
		values.foreground = w->skewb.background;
		values.background = w->skewb.foreground;
	}
	if (w->skewb.inverseGC)
		XtReleaseGC((Widget) w, w->skewb.inverseGC);
	w->skewb.inverseGC = XtGetGC((Widget) w, valueMask, &values);
	if (w->skewb.mono) {
		if (w->skewb.reverse) {
			values.background = w->skewb.foreground;
			values.foreground = w->skewb.background;
		} else {
			values.foreground = w->skewb.foreground;
			values.background = w->skewb.background;
		}
	} else {
		values.foreground = w->skewb.frameColor;
		values.background = w->skewb.background;
	}
	if (w->skewb.frameGC)
		XtReleaseGC((Widget) w, w->skewb.frameGC);
	w->skewb.frameGC = XtGetGC((Widget) w, valueMask, &values);
	if (w->skewb.mono) {
		if (w->skewb.reverse) {
			values.background = w->skewb.foreground;
			values.foreground = w->skewb.background;
		} else {
			values.foreground = w->skewb.foreground;
			values.background = w->skewb.background;
		}
	} else {
		values.foreground = w->skewb.borderColor;
		values.background = w->skewb.background;
	}
	if (w->skewb.borderGC)
		XtReleaseGC((Widget) w, w->skewb.borderGC);
	w->skewb.borderGC = XtGetGC((Widget) w, valueMask, &values);
	for (face = 0; face < MAX_FACES; face++)
		getColor(w, face);
	if (w->skewb.fontInfo)
		XSetFont(XtDisplay(w), w->skewb.borderGC,
			w->skewb.fontInfo->fid);
}

static Boolean
setValuesPuzzle(Widget current, Widget request, Widget renew)
{
	SkewbWidget c = (SkewbWidget) current, w = (SkewbWidget) renew;
	Boolean redraw = False, setColors = False;
	int face;

	checkPieces(w);
	for (face = 0; face < MAX_FACES; face++) {
		if (strcmp(w->skewb.faceName[face], c->skewb.faceName[face])) {
			setColors = True;
			break;
		}
	}
	if (w->skewb.font != c->skewb.font ||
			w->skewb.borderColor != c->skewb.borderColor ||
			w->skewb.reverse != c->skewb.reverse ||
			w->skewb.mono != c->skewb.mono) {
		loadFont(w);
		setAllColors(w);
		redraw = True;
	} else if (w->skewb.background != c->skewb.background ||
			w->skewb.foreground != c->skewb.foreground ||
			setColors) {
		setAllColors(w);
		redraw = True;
	}
	if (w->skewb.orient != c->skewb.orient) {
		resetPieces(w);
		redraw = True;
	} else if (w->skewb.practice != c->skewb.practice) {
		resetPieces(w);
		redraw = True;
	}
	if (w->skewb.menu != ACTION_IGNORE) {
		int menu = w->skewb.menu;

		w->skewb.menu = ACTION_IGNORE;
		switch (menu) {
		case ACTION_GET:
			getPieces(w);
			break;
		case ACTION_WRITE:
			writePieces(w);
			break;
		case ACTION_UNDO:
			undoPieces(w);
			break;
		case ACTION_REDO:
			redoPieces(w);
			break;
		case ACTION_CLEAR:
			clearPieces(w);
			break;
		case ACTION_PRACTICE:
			practicePieces(w);
			break;
		case ACTION_RANDOMIZE:
			randomizePieces(w);
			break;
		case ACTION_SOLVE:
			solvePieces(w);
			break;
		case ACTION_ORIENTIZE:
			orientizePieces(w);
			break;
		case ACTION_SPEED:
			speedPieces(w);
			break;
		case ACTION_SLOW:
			slowPieces(w);
			break;
		case ACTION_SOUND:
			soundPieces(w);
			break;
		case ACTION_VIEW:
			viewPieces(w);
			break;
		default:
			break;
		}
	}
	if (w->skewb.currentDirection == RESTORE_DIR) {
		setStartPosition(w);
		w->skewb.currentDirection = IGNORE_DIR;
	} else if (w->skewb.currentDirection == CLEAR_DIR) {
		resetPieces(w);
		redraw = True;
		w->skewb.currentDirection = IGNORE_DIR;
	} else if (w->skewb.currentDirection > IGNORE_DIR) {
		int face = w->skewb.currentFace;
		int position = w->skewb.currentPosition;
		int direction = w->skewb.currentDirection;

		w->skewb.currentFace = IGNORE_DIR;
		w->skewb.currentPosition = IGNORE_DIR;
		w->skewb.currentDirection = IGNORE_DIR;
		movePieces(w, face, position, direction,
			w->skewb.currentControl, w->skewb.currentFast);
	}
	return redraw;
}

static void
destroyPuzzle(Widget old)
{
	SkewbWidget w = (SkewbWidget) old;
	Display *display = XtDisplay(w);
	int face;

#if defined( USE_SOUND ) && defined( USE_ESOUND )
	if (w->skewb.dim == 2)
		(void) shutdown_sound();
#endif
	for (face = 0; face < MAX_FACES; face++)
		XtReleaseGC(old, w->skewb.faceGC[face]);
	XtReleaseGC(old, w->skewb.borderGC);
	XtReleaseGC(old, w->skewb.frameGC);
	XtReleaseGC(old, w->skewb.inverseGC);
	XtRemoveCallbacks(old, XtNselectCallback, w->skewb.select);
	if (w->skewb.fontInfo) {
		XUnloadFont(display, w->skewb.fontInfo->fid);
		XFreeFont(display, w->skewb.fontInfo);
	}
	deleteMoves(&undo);
	deleteMoves(&redo);
}

void
quitPuzzle(SkewbWidget w, XEvent *event, char **args, int nArgs)
{
	XtCloseDisplay(XtDisplay(w));
	exit(0);
}
#endif

#ifndef WINVER
static
#endif
void
initializePuzzle(
#ifdef WINVER
SkewbWidget w, HBRUSH brush
#else
Widget request, Widget renew
#endif
)
{
#ifdef WINVER
	setValuesPuzzle(w);
#else
	SkewbWidget w = (SkewbWidget) renew;
	int face;

	w->skewb.mono = (DefaultDepthOfScreen(XtScreen(w)) < 2 ||
		w->skewb.mono);
	w->skewb.fontInfo = NULL;
	for (face = 0; face < MAX_FACES; face++)
		w->skewb.faceGC[face] = NULL;
	w->skewb.borderGC = NULL;
	w->skewb.frameGC = NULL;
	w->skewb.inverseGC = NULL;
#endif
	w->skewb.focus = False;
	loadFont(w);
	checkPieces(w);
	newMoves(&undo);
	newMoves(&redo);
	w->skewb.cheat = False;
	resetPieces(w);
#ifdef WINVER
	brush = CreateSolidBrush(w->skewb.inverseGC);
	SETBACK(w->core.hWnd, brush);
	(void) SRAND(time(NULL));
#else
	(void) SRAND(getpid());
#endif
#ifdef USE_SOUND
#ifdef USE_NAS
	dsp = XtDisplay(w);
#endif
#ifdef USE_ESOUND
	if (w->skewb.dim == 2)
		(void) init_sound();
#endif
#endif
}

void
hidePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	setPuzzle(w, ACTION_HIDE);
}

void
selectPuzzle(SkewbWidget w
#ifdef WINVER
, const int x, const int y, const int control, const int alt
#else
, XEvent *event, char **args, int nArgs
#endif
)
{
#ifndef WINVER
	int x = event->xbutton.x, y = event->xbutton.y;
	int control = (int) (event->xkey.state & ControlMask);
	int alt = (int) (event->xkey.state & (Mod1Mask | Mod3Mask | Mod4Mask | Mod5Mask));
#endif

	if (selectPieces(w, x, y, &(w->skewb.currentFace),
			&(w->skewb.currentPosition))) {
		if (w->skewb.currentPosition == MAX_ORIENT) {
			if (control || alt || w->skewb.practice || !checkSolved(w)) {
				drawDiamondAll(w, w->skewb.currentFace, TRUE);
				FLUSH(w);
				Sleep(100);
				drawDiamond(w, w->skewb.currentFace, FALSE);
				w->skewb.currentFace = IGNORE_DIR;
				w->skewb.currentDirection = IGNORE_DIR;
#ifdef HAVE_OPENGL
				if (w->skewb.dim == 4)
					drawAllPiecesGL((SkewbGLWidget) w);
#endif
			}
		} else if (control || alt || w->skewb.practice || !checkSolved(w)) {
			drawTriangleAll(w, w->skewb.currentFace, w->skewb.currentPosition,
				TRUE);
		}
	} else {
		w->skewb.currentFace = IGNORE_DIR;
		w->skewb.currentDirection = IGNORE_DIR;
#ifdef HAVE_OPENGL
		if (w->skewb.dim == 4)
			drawAllPiecesGL((SkewbGLWidget) w);
#endif
	}
}

void
releasePuzzle(SkewbWidget w
#ifdef WINVER
, const int x, const int y, const int control, const int alt
#else
, XEvent *event, char **args, int nArgs
#endif
)
{
#ifndef WINVER
	int x = event->xbutton.x, y = event->xbutton.y;
	int control = (int) (event->xkey.state & ControlMask);
	int alt = (int) (event->xkey.state & (Mod1Mask | Mod3Mask | Mod4Mask | Mod5Mask));
#endif
	int face, position, count = -1, direction = 0, ctrl = control;

	if (w->skewb.currentFace <= IGNORE_DIR)
		return;
	if (w->skewb.currentPosition != MAX_ORIENT)
		drawTriangle(w, w->skewb.currentFace, w->skewb.currentPosition,
			FALSE);
	if (!control && !alt && !w->skewb.practice && checkSolved(w))
		moveNoPieces(w);
	else if (selectPieces(w, x, y, &face, &position)) {
		if (alt)
			ctrl = 2;
		else
			ctrl = (ctrl) ? 1 : 0;
		if (face == w->skewb.currentFace) {
			if (position == MAX_ORIENT)
				count = -1;
			else
				count = checkMoveDir(w->skewb.currentPosition,
					position, &direction);
			/* count == 2 too annoying */
			if (count == 2)
				count = -1;
		} else {
			direction = facesToDirection[w->skewb.currentFace][face];
			w->skewb.currentPosition =
				facestoPosition[w->skewb.currentFace][face][w->skewb.currentPosition];
			count = face;
			face = w->skewb.currentFace;
			w->skewb.currentFace = count;
			if (w->skewb.currentPosition >= 0)
				count = 1;
			else
				count = 0;
		}
		if (count == 1) {
			face = w->skewb.currentFace;
			position = w->skewb.currentPosition;
			w->skewb.currentFace = IGNORE_DIR;
			w->skewb.currentPosition = IGNORE_DIR;
			movePuzzle(w, face, position, direction, ctrl, NORMAL);
			if (!ctrl && checkSolved(w)) {
				setPuzzle(w, ACTION_SOLVED);
			}
		} else if (count == 0) {
			moveNoPieces(w);
		}
	}
	w->skewb.currentFace = IGNORE_DIR;
	w->skewb.currentDirection = IGNORE_DIR;
#ifdef HAVE_OPENGL
	if (w->skewb.dim == 4 && count != 1) {
		drawAllPiecesGL((SkewbGLWidget) w);
	}
#endif
}

#ifndef WINVER
void
practicePuzzleWithQuery(SkewbWidget w
, XEvent *event, char **args, int nArgs
)
{
	if (!w->skewb.started)
		practicePieces(w);
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	else {
		setPuzzle(w, ACTION_PRACTICE_QUERY);
	}
#endif
}

void
practicePuzzleWithDoubleClick(SkewbWidget w
, XEvent *event, char **args, int nArgs
)
{
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	if (!w->skewb.started)
#endif
		practicePieces(w);
}

void
randomizePuzzleWithQuery(SkewbWidget w
, XEvent *event, char **args, int nArgs
)
{
	if (!w->skewb.started)
		randomizePieces(w);
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	else {
		setPuzzle(w, ACTION_RANDOMIZE_QUERY);
	}
#endif
}

void
randomizePuzzleWithDoubleClick(SkewbWidget w
, XEvent *event, char **args, int nArgs
)
{
#if defined(HAVE_MOTIF) || defined(HAVE_ATHENA)
	if (!w->skewb.started)
#endif
		randomizePieces(w);
}
#endif

void
getPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	getPieces(w);
}

void
writePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	writePieces(w);
}

void
undoPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	undoPieces(w);
}

void
redoPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	redoPieces(w);
}

void
clearPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	clearPieces(w);
}

void
randomizePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	randomizePieces(w);
}

void
solvePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	solvePieces(w);
}

void
practicePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	practicePieces(w);
}

void
orientizePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	orientizePieces(w);
}

void
viewPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	viewPieces(w);
}

void
speedUpPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	speedPieces(w);
}

void
slowDownPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	slowPieces(w);
}

void
toggleSoundPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	soundPieces(w);
}

void
enterPuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	w->skewb.focus = True;
	drawFrame(w, w->skewb.focus);
}

void
leavePuzzle(SkewbWidget w
#ifndef WINVER
, XEvent *event, char **args, int nArgs
#endif
)
{
	w->skewb.focus = False;
	drawFrame(w, w->skewb.focus);
}

#ifdef WINVER
void
dimPuzzle(SkewbWidget w)
{
	setPuzzle(w, ACTION_DIM);
}

#else
void
movePuzzleCcw(SkewbWidget w, XEvent *event, char **args, int nArgs)
{
	movePuzzleInput(w, event->xbutton.x, event->xbutton.y, CCW,
		(int) (event->xbutton.state & ControlMask), FALSE);
}

void
movePuzzleCw(SkewbWidget w, XEvent *event, char **args, int nArgs)
{
	movePuzzleInput(w, event->xbutton.x, event->xbutton.y, CW,
		(int) (event->xkey.state & ControlMask), FALSE);
}
#endif
