Also update engine list when saving engine settings
[xboard.git] / backend.c
1 /*
2  * backend.c -- Common back end for X and Windows NT versions of
3  *
4  * Copyright 1991 by Digital Equipment Corporation, Maynard,
5  * Massachusetts.
6  *
7  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8  * 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free
9  * Software Foundation, Inc.
10  *
11  * Enhancements Copyright 2005 Alessandro Scotti
12  *
13  * The following terms apply to Digital Equipment Corporation's copyright
14  * interest in XBoard:
15  * ------------------------------------------------------------------------
16  * All Rights Reserved
17  *
18  * Permission to use, copy, modify, and distribute this software and its
19  * documentation for any purpose and without fee is hereby granted,
20  * provided that the above copyright notice appear in all copies and that
21  * both that copyright notice and this permission notice appear in
22  * supporting documentation, and that the name of Digital not be
23  * used in advertising or publicity pertaining to distribution of the
24  * software without specific, written prior permission.
25  *
26  * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
27  * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
28  * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
29  * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
31  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
32  * SOFTWARE.
33  * ------------------------------------------------------------------------
34  *
35  * The following terms apply to the enhanced version of XBoard
36  * distributed by the Free Software Foundation:
37  * ------------------------------------------------------------------------
38  *
39  * GNU XBoard is free software: you can redistribute it and/or modify
40  * it under the terms of the GNU General Public License as published by
41  * the Free Software Foundation, either version 3 of the License, or (at
42  * your option) any later version.
43  *
44  * GNU XBoard is distributed in the hope that it will be useful, but
45  * WITHOUT ANY WARRANTY; without even the implied warranty of
46  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47  * General Public License for more details.
48  *
49  * You should have received a copy of the GNU General Public License
50  * along with this program. If not, see http://www.gnu.org/licenses/.  *
51  *
52  *------------------------------------------------------------------------
53  ** See the file ChangeLog for a revision history.  */
54
55 /* [AS] Also useful here for debugging */
56 #ifdef WIN32
57 #include <windows.h>
58
59     int flock(int f, int code);
60 #   define LOCK_EX 2
61 #   define SLASH '\\'
62
63 #   ifdef ARC_64BIT
64 #       define EGBB_NAME "egbbdll64.dll"
65 #   else
66 #       define EGBB_NAME "egbbdll.dll"
67 #   endif
68
69 #else
70
71 #   include <sys/file.h>
72 #   define SLASH '/'
73
74 #   include <dlfcn.h>
75 #   ifdef ARC_64BIT
76 #       define EGBB_NAME "egbbso64.so"
77 #   else
78 #       define EGBB_NAME "egbbso.so"
79 #   endif
80     // kludge to allow Windows code in back-end by converting it to corresponding Linux code 
81 #   define CDECL
82 #   define HMODULE void *
83 #   define LoadLibrary(x) dlopen(x, RTLD_LAZY)
84 #   define GetProcAddress dlsym
85
86 #endif
87
88 #include "config.h"
89
90 #include <assert.h>
91 #include <stdio.h>
92 #include <ctype.h>
93 #include <errno.h>
94 #include <sys/types.h>
95 #include <sys/stat.h>
96 #include <math.h>
97 #include <ctype.h>
98
99 #if STDC_HEADERS
100 # include <stdlib.h>
101 # include <string.h>
102 # include <stdarg.h>
103 #else /* not STDC_HEADERS */
104 # if HAVE_STRING_H
105 #  include <string.h>
106 # else /* not HAVE_STRING_H */
107 #  include <strings.h>
108 # endif /* not HAVE_STRING_H */
109 #endif /* not STDC_HEADERS */
110
111 #if HAVE_SYS_FCNTL_H
112 # include <sys/fcntl.h>
113 #else /* not HAVE_SYS_FCNTL_H */
114 # if HAVE_FCNTL_H
115 #  include <fcntl.h>
116 # endif /* HAVE_FCNTL_H */
117 #endif /* not HAVE_SYS_FCNTL_H */
118
119 #if TIME_WITH_SYS_TIME
120 # include <sys/time.h>
121 # include <time.h>
122 #else
123 # if HAVE_SYS_TIME_H
124 #  include <sys/time.h>
125 # else
126 #  include <time.h>
127 # endif
128 #endif
129
130 #if defined(_amigados) && !defined(__GNUC__)
131 struct timezone {
132     int tz_minuteswest;
133     int tz_dsttime;
134 };
135 extern int gettimeofday(struct timeval *, struct timezone *);
136 #endif
137
138 #if HAVE_UNISTD_H
139 # include <unistd.h>
140 #endif
141
142 #include "common.h"
143 #include "frontend.h"
144 #include "backend.h"
145 #include "parser.h"
146 #include "moves.h"
147 #if ZIPPY
148 # include "zippy.h"
149 #endif
150 #include "backendz.h"
151 #include "evalgraph.h"
152 #include "engineoutput.h"
153 #include "gettext.h"
154
155 #ifdef ENABLE_NLS
156 # define _(s) gettext (s)
157 # define N_(s) gettext_noop (s)
158 # define T_(s) gettext(s)
159 #else
160 # ifdef WIN32
161 #   define _(s) T_(s)
162 #   define N_(s) s
163 # else
164 #   define _(s) (s)
165 #   define N_(s) s
166 #   define T_(s) s
167 # endif
168 #endif
169
170
171 int establish P((void));
172 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
173                          char *buf, int count, int error));
174 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
175                       char *buf, int count, int error));
176 void SendToICS P((char *s));
177 void SendToICSDelayed P((char *s, long msdelay));
178 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
179 void HandleMachineMove P((char *message, ChessProgramState *cps));
180 int AutoPlayOneMove P((void));
181 int LoadGameOneMove P((ChessMove readAhead));
182 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
183 int LoadPositionFromFile P((char *filename, int n, char *title));
184 int SavePositionToFile P((char *filename));
185 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
186 void ShowMove P((int fromX, int fromY, int toX, int toY));
187 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
188                    /*char*/int promoChar));
189 void BackwardInner P((int target));
190 void ForwardInner P((int target));
191 int Adjudicate P((ChessProgramState *cps));
192 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
193 void EditPositionDone P((Boolean fakeRights));
194 void PrintOpponents P((FILE *fp));
195 void PrintPosition P((FILE *fp, int move));
196 void SendToProgram P((char *message, ChessProgramState *cps));
197 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
198 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
199                            char *buf, int count, int error));
200 void SendTimeControl P((ChessProgramState *cps,
201                         int mps, long tc, int inc, int sd, int st));
202 char *TimeControlTagValue P((void));
203 void Attention P((ChessProgramState *cps));
204 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
205 int ResurrectChessProgram P((void));
206 void DisplayComment P((int moveNumber, char *text));
207 void DisplayMove P((int moveNumber));
208
209 void ParseGameHistory P((char *game));
210 void ParseBoard12 P((char *string));
211 void KeepAlive P((void));
212 void StartClocks P((void));
213 void SwitchClocks P((int nr));
214 void StopClocks P((void));
215 void ResetClocks P((void));
216 char *PGNDate P((void));
217 void SetGameInfo P((void));
218 int RegisterMove P((void));
219 void MakeRegisteredMove P((void));
220 void TruncateGame P((void));
221 int looking_at P((char *, int *, char *));
222 void CopyPlayerNameIntoFileName P((char **, char *));
223 char *SavePart P((char *));
224 int SaveGameOldStyle P((FILE *));
225 int SaveGamePGN P((FILE *));
226 int CheckFlags P((void));
227 long NextTickLength P((long));
228 void CheckTimeControl P((void));
229 void show_bytes P((FILE *, char *, int));
230 int string_to_rating P((char *str));
231 void ParseFeatures P((char* args, ChessProgramState *cps));
232 void InitBackEnd3 P((void));
233 void FeatureDone P((ChessProgramState* cps, int val));
234 void InitChessProgram P((ChessProgramState *cps, int setup));
235 void OutputKibitz(int window, char *text);
236 int PerpetualChase(int first, int last);
237 int EngineOutputIsUp();
238 void InitDrawingSizes(int x, int y);
239 void NextMatchGame P((void));
240 int NextTourneyGame P((int nr, int *swap));
241 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
242 FILE *WriteTourneyFile P((char *results, FILE *f));
243 void DisplayTwoMachinesTitle P(());
244 static void ExcludeClick P((int index));
245 void ToggleSecond P((void));
246 void PauseEngine P((ChessProgramState *cps));
247 static int NonStandardBoardSize P((VariantClass v, int w, int h, int s));
248
249 #ifdef WIN32
250        extern void ConsoleCreate();
251 #endif
252
253 ChessProgramState *WhitePlayer();
254 int VerifyDisplayMode P(());
255
256 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
257 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
258 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
259 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
260 void ics_update_width P((int new_width));
261 extern char installDir[MSG_SIZ];
262 VariantClass startVariant; /* [HGM] nicks: initial variant */
263 Boolean abortMatch;
264 int deadRanks, handSize, handOffsets;
265
266 extern int tinyLayout, smallLayout;
267 ChessProgramStats programStats;
268 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
269 int endPV = -1;
270 static int exiting = 0; /* [HGM] moved to top */
271 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
272 int startedFromPositionFile = FALSE; Board filePosition;       /* [HGM] loadPos */
273 Board partnerBoard;     /* [HGM] bughouse: for peeking at partner game          */
274 int partnerHighlight[2];
275 Boolean partnerBoardValid = 0;
276 char partnerStatus[MSG_SIZ];
277 Boolean partnerUp;
278 Boolean originalFlip;
279 Boolean twoBoards = 0;
280 char endingGame = 0;    /* [HGM] crash: flag to prevent recursion of GameEnds() */
281 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS     */
282 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
283 int lastIndex = 0;      /* [HGM] autoinc: last game/position used in match mode */
284 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing      */
285 int opponentKibitzes;
286 int lastSavedGame; /* [HGM] save: ID of game */
287 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
288 extern int chatCount;
289 int chattingPartner;
290 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
291 char legal[BOARD_RANKS][BOARD_FILES];  /* [HGM] legal target squares */
292 char lastMsg[MSG_SIZ];
293 char lastTalker[MSG_SIZ];
294 ChessSquare pieceSweep = EmptySquare;
295 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
296 int promoDefaultAltered;
297 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
298 static int initPing = -1;
299 int border;       /* [HGM] width of board rim, needed to size seek graph  */
300 char bestMove[MSG_SIZ], avoidMove[MSG_SIZ];
301 int solvingTime, totalTime;
302
303 /* States for ics_getting_history */
304 #define H_FALSE 0
305 #define H_REQUESTED 1
306 #define H_GOT_REQ_HEADER 2
307 #define H_GOT_UNREQ_HEADER 3
308 #define H_GETTING_MOVES 4
309 #define H_GOT_UNWANTED_HEADER 5
310
311 /* whosays values for GameEnds */
312 #define GE_ICS 0
313 #define GE_ENGINE 1
314 #define GE_PLAYER 2
315 #define GE_FILE 3
316 #define GE_XBOARD 4
317 #define GE_ENGINE1 5
318 #define GE_ENGINE2 6
319
320 /* Maximum number of games in a cmail message */
321 #define CMAIL_MAX_GAMES 20
322
323 /* Different types of move when calling RegisterMove */
324 #define CMAIL_MOVE   0
325 #define CMAIL_RESIGN 1
326 #define CMAIL_DRAW   2
327 #define CMAIL_ACCEPT 3
328
329 /* Different types of result to remember for each game */
330 #define CMAIL_NOT_RESULT 0
331 #define CMAIL_OLD_RESULT 1
332 #define CMAIL_NEW_RESULT 2
333
334 /* Telnet protocol constants */
335 #define TN_WILL 0373
336 #define TN_WONT 0374
337 #define TN_DO   0375
338 #define TN_DONT 0376
339 #define TN_IAC  0377
340 #define TN_ECHO 0001
341 #define TN_SGA  0003
342 #define TN_PORT 23
343
344 char*
345 safeStrCpy (char *dst, const char *src, size_t count)
346 { // [HGM] made safe
347   int i;
348   assert( dst != NULL );
349   assert( src != NULL );
350   assert( count > 0 );
351
352   for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
353   if(  i == count && dst[count-1] != NULLCHAR)
354     {
355       dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
356       if(appData.debugMode)
357         fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
358     }
359
360   return dst;
361 }
362
363 /* Some compiler can't cast u64 to double
364  * This function do the job for us:
365
366  * We use the highest bit for cast, this only
367  * works if the highest bit is not
368  * in use (This should not happen)
369  *
370  * We used this for all compiler
371  */
372 double
373 u64ToDouble (u64 value)
374 {
375   double r;
376   u64 tmp = value & u64Const(0x7fffffffffffffff);
377   r = (double)(s64)tmp;
378   if (value & u64Const(0x8000000000000000))
379        r +=  9.2233720368547758080e18; /* 2^63 */
380  return r;
381 }
382
383 /* Fake up flags for now, as we aren't keeping track of castling
384    availability yet. [HGM] Change of logic: the flag now only
385    indicates the type of castlings allowed by the rule of the game.
386    The actual rights themselves are maintained in the array
387    castlingRights, as part of the game history, and are not probed
388    by this function.
389  */
390 int
391 PosFlags (int index)
392 {
393   int flags = F_ALL_CASTLE_OK;
394   if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
395   switch (gameInfo.variant) {
396   case VariantSuicide:
397     flags &= ~F_ALL_CASTLE_OK;
398   case VariantGiveaway:         // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
399     flags |= F_IGNORE_CHECK;
400   case VariantLosers:
401     flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
402     break;
403   case VariantAtomic:
404     flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
405     break;
406   case VariantKriegspiel:
407     flags |= F_KRIEGSPIEL_CAPTURE;
408     break;
409   case VariantCapaRandom:
410   case VariantFischeRandom:
411     flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
412   case VariantNoCastle:
413   case VariantShatranj:
414   case VariantCourier:
415   case VariantMakruk:
416   case VariantASEAN:
417   case VariantGrand:
418     flags &= ~F_ALL_CASTLE_OK;
419     break;
420   case VariantChu:
421   case VariantChuChess:
422   case VariantLion:
423     flags |= F_NULL_MOVE;
424     break;
425   default:
426     break;
427   }
428   if(appData.fischerCastling) flags |= F_FRC_TYPE_CASTLING, flags &= ~F_ALL_CASTLE_OK; // [HGM] fischer
429   return flags;
430 }
431
432 FILE *gameFileFP, *debugFP, *serverFP;
433 char *currentDebugFile; // [HGM] debug split: to remember name
434
435 /*
436     [AS] Note: sometimes, the sscanf() function is used to parse the input
437     into a fixed-size buffer. Because of this, we must be prepared to
438     receive strings as long as the size of the input buffer, which is currently
439     set to 4K for Windows and 8K for the rest.
440     So, we must either allocate sufficiently large buffers here, or
441     reduce the size of the input buffer in the input reading part.
442 */
443
444 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
445 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
446 char thinkOutput1[MSG_SIZ*10];
447 char promoRestrict[MSG_SIZ];
448
449 ChessProgramState first, second, pairing;
450
451 /* premove variables */
452 int premoveToX = 0;
453 int premoveToY = 0;
454 int premoveFromX = 0;
455 int premoveFromY = 0;
456 int premovePromoChar = 0;
457 int gotPremove = 0;
458 Boolean alarmSounded;
459 /* end premove variables */
460
461 char *ics_prefix = "$";
462 enum ICS_TYPE ics_type = ICS_GENERIC;
463
464 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
465 int pauseExamForwardMostMove = 0;
466 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
467 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
468 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
469 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
470 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
471 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
472 int whiteFlag = FALSE, blackFlag = FALSE;
473 int userOfferedDraw = FALSE;
474 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
475 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
476 int cmailMoveType[CMAIL_MAX_GAMES];
477 long ics_clock_paused = 0;
478 ProcRef icsPR = NoProc, cmailPR = NoProc;
479 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
480 GameMode gameMode = BeginningOfGame;
481 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
482 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
483 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
484 int hiddenThinkOutputState = 0; /* [AS] */
485 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
486 int adjudicateLossPlies = 6;
487 char white_holding[64], black_holding[64];
488 TimeMark lastNodeCountTime;
489 long lastNodeCount=0;
490 int shiftKey, controlKey; // [HGM] set by mouse handler
491
492 int have_sent_ICS_logon = 0;
493 int movesPerSession;
494 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
495 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
496 Boolean adjustedClock;
497 long timeControl_2; /* [AS] Allow separate time controls */
498 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
499 long timeRemaining[2][MAX_MOVES];
500 int matchGame = 0, nextGame = 0, roundNr = 0;
501 Boolean waitingForGame = FALSE, startingEngine = FALSE;
502 TimeMark programStartTime, pauseStart;
503 char ics_handle[MSG_SIZ];
504 int have_set_title = 0;
505
506 /* animateTraining preserves the state of appData.animate
507  * when Training mode is activated. This allows the
508  * response to be animated when appData.animate == TRUE and
509  * appData.animateDragging == TRUE.
510  */
511 Boolean animateTraining;
512
513 GameInfo gameInfo;
514
515 AppData appData;
516
517 Board boards[MAX_MOVES];
518 /* [HGM] Following 7 needed for accurate legality tests: */
519 signed char  castlingRank[BOARD_FILES]; // and corresponding ranks
520 unsigned char initialRights[BOARD_FILES];
521 int   nrCastlingRights; // For TwoKings, or to implement castling-unknown status
522 int   initialRulePlies, FENrulePlies;
523 FILE  *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
524 int loadFlag = 0;
525 Boolean shuffleOpenings;
526 int mute; // mute all sounds
527
528 // [HGM] vari: next 12 to save and restore variations
529 #define MAX_VARIATIONS 10
530 int framePtr = MAX_MOVES-1; // points to free stack entry
531 int storedGames = 0;
532 int savedFirst[MAX_VARIATIONS];
533 int savedLast[MAX_VARIATIONS];
534 int savedFramePtr[MAX_VARIATIONS];
535 char *savedDetails[MAX_VARIATIONS];
536 ChessMove savedResult[MAX_VARIATIONS];
537
538 void PushTail P((int firstMove, int lastMove));
539 Boolean PopTail P((Boolean annotate));
540 void PushInner P((int firstMove, int lastMove));
541 void PopInner P((Boolean annotate));
542 void CleanupTail P((void));
543
544 ChessSquare  FIDEArray[2][BOARD_FILES] = {
545     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
546         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
547     { BlackRook, BlackKnight, BlackBishop, BlackQueen,
548         BlackKing, BlackBishop, BlackKnight, BlackRook }
549 };
550
551 ChessSquare twoKingsArray[2][BOARD_FILES] = {
552     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
553         WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
554     { BlackRook, BlackKnight, BlackBishop, BlackQueen,
555         BlackKing, BlackKing, BlackKnight, BlackRook }
556 };
557
558 ChessSquare  KnightmateArray[2][BOARD_FILES] = {
559     { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
560         WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
561     { BlackRook, BlackMan, BlackBishop, BlackQueen,
562         BlackUnicorn, BlackBishop, BlackMan, BlackRook }
563 };
564
565 ChessSquare SpartanArray[2][BOARD_FILES] = {
566     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
567         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
568     { BlackAlfil, BlackDragon, BlackKing, BlackTower,
569         BlackTower, BlackKing, BlackAngel, BlackAlfil }
570 };
571
572 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
573     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
574         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
575     { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
576         BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
577 };
578
579 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
580     { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
581         WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
582     { BlackRook, BlackKnight, BlackAlfil, BlackKing,
583         BlackFerz, BlackAlfil, BlackKnight, BlackRook }
584 };
585
586 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
587     { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
588         WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
589     { BlackRook, BlackKnight, BlackMan, BlackFerz,
590         BlackKing, BlackMan, BlackKnight, BlackRook }
591 };
592
593 ChessSquare aseanArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
594     { WhiteRook, WhiteKnight, WhiteMan, WhiteFerz,
595         WhiteKing, WhiteMan, WhiteKnight, WhiteRook },
596     { BlackRook, BlackKnight, BlackMan, BlackFerz,
597         BlackKing, BlackMan, BlackKnight, BlackRook }
598 };
599
600 ChessSquare  lionArray[2][BOARD_FILES] = {
601     { WhiteRook, WhiteLion, WhiteBishop, WhiteQueen,
602         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
603     { BlackRook, BlackLion, BlackBishop, BlackQueen,
604         BlackKing, BlackBishop, BlackKnight, BlackRook }
605 };
606
607
608 #if (BOARD_FILES>=10)
609 ChessSquare ShogiArray[2][BOARD_FILES] = {
610     { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
611         WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
612     { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
613         BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
614 };
615
616 ChessSquare XiangqiArray[2][BOARD_FILES] = {
617     { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
618         WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
619     { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
620         BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
621 };
622
623 ChessSquare CapablancaArray[2][BOARD_FILES] = {
624     { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
625         WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
626     { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
627         BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
628 };
629
630 ChessSquare GreatArray[2][BOARD_FILES] = {
631     { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
632         WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
633     { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
634         BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
635 };
636
637 ChessSquare JanusArray[2][BOARD_FILES] = {
638     { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
639         WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
640     { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
641         BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
642 };
643
644 ChessSquare GrandArray[2][BOARD_FILES] = {
645     { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
646         WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
647     { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
648         BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
649 };
650
651 ChessSquare ChuChessArray[2][BOARD_FILES] = {
652     { WhiteMan, WhiteKnight, WhiteBishop, WhiteCardinal, WhiteLion,
653         WhiteQueen, WhiteDragon, WhiteBishop, WhiteKnight, WhiteMan },
654     { BlackMan, BlackKnight, BlackBishop, BlackDragon, BlackQueen,
655         BlackLion, BlackCardinal, BlackBishop, BlackKnight, BlackMan }
656 };
657
658 #ifdef GOTHIC
659 ChessSquare GothicArray[2][BOARD_FILES] = {
660     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
661         WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
662     { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
663         BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
664 };
665 #else // !GOTHIC
666 #define GothicArray CapablancaArray
667 #endif // !GOTHIC
668
669 #ifdef FALCON
670 ChessSquare FalconArray[2][BOARD_FILES] = {
671     { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
672         WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
673     { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
674         BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
675 };
676 #else // !FALCON
677 #define FalconArray CapablancaArray
678 #endif // !FALCON
679
680 #else // !(BOARD_FILES>=10)
681 #define XiangqiPosition FIDEArray
682 #define CapablancaArray FIDEArray
683 #define GothicArray FIDEArray
684 #define GreatArray FIDEArray
685 #endif // !(BOARD_FILES>=10)
686
687 #if (BOARD_FILES>=12)
688 ChessSquare CourierArray[2][BOARD_FILES] = {
689     { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
690         WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
691     { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
692         BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
693 };
694 ChessSquare ChuArray[6][BOARD_FILES] = {
695     { WhiteLance, WhiteCat, WhiteCopper, WhiteFerz, WhiteWazir, WhiteKing,
696       WhiteAlfil, WhiteWazir, WhiteFerz, WhiteCopper, WhiteCat, WhiteLance },
697     { BlackLance, BlackCat, BlackCopper, BlackFerz, BlackWazir, BlackAlfil,
698       BlackKing, BlackWazir, BlackFerz, BlackCopper, BlackCat, BlackLance },
699     { WhiteAxe, EmptySquare, WhiteBishop, EmptySquare, WhiteClaw, WhiteMarshall,
700       WhiteAngel, WhiteClaw, EmptySquare, WhiteBishop, EmptySquare, WhiteAxe },
701     { BlackAxe, EmptySquare, BlackBishop, EmptySquare, BlackClaw, BlackAngel,
702       BlackMarshall, BlackClaw, EmptySquare, BlackBishop, EmptySquare, BlackAxe },
703     { WhiteDagger, WhiteSword, WhiteRook, WhiteCardinal, WhiteDragon, WhiteLion,
704       WhiteQueen, WhiteDragon, WhiteCardinal, WhiteRook, WhiteSword, WhiteDagger },
705     { BlackDagger, BlackSword, BlackRook, BlackCardinal, BlackDragon, BlackQueen,
706       BlackLion, BlackDragon, BlackCardinal, BlackRook, BlackSword, BlackDagger }
707 };
708 #else // !(BOARD_FILES>=12)
709 #define CourierArray CapablancaArray
710 #define ChuArray CapablancaArray
711 #endif // !(BOARD_FILES>=12)
712
713
714 Board initialPosition;
715
716
717 /* Convert str to a rating. Checks for special cases of "----",
718
719    "++++", etc. Also strips ()'s */
720 int
721 string_to_rating (char *str)
722 {
723   while(*str && !isdigit(*str)) ++str;
724   if (!*str)
725     return 0;   /* One of the special "no rating" cases */
726   else
727     return atoi(str);
728 }
729
730 void
731 ClearProgramStats ()
732 {
733     /* Init programStats */
734     programStats.movelist[0] = 0;
735     programStats.depth = 0;
736     programStats.nr_moves = 0;
737     programStats.moves_left = 0;
738     programStats.nodes = 0;
739     programStats.time = -1;        // [HGM] PGNtime: make invalid to recognize engine output
740     programStats.score = 0;
741     programStats.got_only_move = 0;
742     programStats.got_fail = 0;
743     programStats.line_is_book = 0;
744 }
745
746 void
747 CommonEngineInit ()
748 {   // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
749     if (appData.firstPlaysBlack) {
750         first.twoMachinesColor = "black\n";
751         second.twoMachinesColor = "white\n";
752     } else {
753         first.twoMachinesColor = "white\n";
754         second.twoMachinesColor = "black\n";
755     }
756
757     first.other = &second;
758     second.other = &first;
759
760     { float norm = 1;
761         if(appData.timeOddsMode) {
762             norm = appData.timeOdds[0];
763             if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
764         }
765         first.timeOdds  = appData.timeOdds[0]/norm;
766         second.timeOdds = appData.timeOdds[1]/norm;
767     }
768
769     if(programVersion) free(programVersion);
770     if (appData.noChessProgram) {
771         programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
772         sprintf(programVersion, "%s", PACKAGE_STRING);
773     } else {
774       /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
775       programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
776       sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
777     }
778 }
779
780 void
781 UnloadEngine (ChessProgramState *cps)
782 {
783         /* Kill off first chess program */
784         if (cps->isr != NULL)
785           RemoveInputSource(cps->isr);
786         cps->isr = NULL;
787
788         if (cps->pr != NoProc) {
789             ExitAnalyzeMode();
790             DoSleep( appData.delayBeforeQuit );
791             SendToProgram("quit\n", cps);
792             DestroyChildProcess(cps->pr, 4 + cps->useSigterm);
793         }
794         cps->pr = NoProc;
795         if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
796 }
797
798 void
799 ClearOptions (ChessProgramState *cps)
800 {
801     int i;
802     cps->nrOptions = cps->comboCnt = 0;
803     for(i=0; i<MAX_OPTIONS; i++) {
804         cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
805         cps->option[i].textValue = 0;
806     }
807 }
808
809 char *engineNames[] = {
810   /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
811      such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
812 N_("first"),
813   /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
814      such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
815 N_("second")
816 };
817
818 void
819 InitEngine (ChessProgramState *cps, int n)
820 {   // [HGM] all engine initialiation put in a function that does one engine
821
822     ClearOptions(cps);
823
824     cps->which = engineNames[n];
825     cps->maybeThinking = FALSE;
826     cps->pr = NoProc;
827     cps->isr = NULL;
828     cps->sendTime = 2;
829     cps->sendDrawOffers = 1;
830
831     cps->program = appData.chessProgram[n];
832     cps->host = appData.host[n];
833     cps->dir = appData.directory[n];
834     cps->initString = appData.engInitString[n];
835     cps->computerString = appData.computerString[n];
836     cps->useSigint  = TRUE;
837     cps->useSigterm = TRUE;
838     cps->reuse = appData.reuse[n];
839     cps->nps = appData.NPS[n];   // [HGM] nps: copy nodes per second
840     cps->useSetboard = FALSE;
841     cps->useSAN = FALSE;
842     cps->usePing = FALSE;
843     cps->lastPing = 0;
844     cps->lastPong = 0;
845     cps->usePlayother = FALSE;
846     cps->useColors = TRUE;
847     cps->useUsermove = FALSE;
848     cps->sendICS = FALSE;
849     cps->sendName = appData.icsActive;
850     cps->sdKludge = FALSE;
851     cps->stKludge = FALSE;
852     if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
853     TidyProgramName(cps->program, cps->host, cps->tidy);
854     cps->matchWins = 0;
855     ASSIGN(cps->variants, appData.noChessProgram ? "" : appData.variant);
856     cps->analysisSupport = 2; /* detect */
857     cps->analyzing = FALSE;
858     cps->initDone = FALSE;
859     cps->reload = FALSE;
860     cps->pseudo = appData.pseudo[n];
861
862     /* New features added by Tord: */
863     cps->useFEN960 = FALSE;
864     cps->useOOCastle = TRUE;
865     /* End of new features added by Tord. */
866     cps->fenOverride  = appData.fenOverride[n];
867
868     /* [HGM] time odds: set factor for each machine */
869     cps->timeOdds  = appData.timeOdds[n];
870
871     /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
872     cps->accumulateTC = appData.accumulateTC[n];
873     cps->maxNrOfSessions = 1;
874
875     /* [HGM] debug */
876     cps->debug = FALSE;
877
878     cps->drawDepth = appData.drawDepth[n];
879     cps->supportsNPS = UNKNOWN;
880     cps->memSize = FALSE;
881     cps->maxCores = FALSE;
882     ASSIGN(cps->egtFormats, "");
883
884     /* [HGM] options */
885     cps->optionSettings  = appData.engOptions[n];
886
887     cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
888     cps->isUCI = appData.isUCI[n]; /* [AS] */
889     cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
890     cps->highlight = 0;
891
892     if (appData.protocolVersion[n] > PROTOVER
893         || appData.protocolVersion[n] < 1)
894       {
895         char buf[MSG_SIZ];
896         int len;
897
898         len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
899                        appData.protocolVersion[n]);
900         if( (len >= MSG_SIZ) && appData.debugMode )
901           fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
902
903         DisplayFatalError(buf, 0, 2);
904       }
905     else
906       {
907         cps->protocolVersion = appData.protocolVersion[n];
908       }
909
910     InitEngineUCI( installDir, cps );  // [HGM] moved here from winboard.c, to make available in xboard
911     ParseFeatures(appData.featureDefaults, cps);
912 }
913
914 ChessProgramState *savCps;
915
916 GameMode oldMode, tryNr;
917
918 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
919 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
920 char *insert, *wbOptions, *currentEngine[2]; // point in ChessProgramNames were we should insert new engine
921 static char newEngineCommand[MSG_SIZ];
922
923 void
924 FloatToFront(char **list, char *engineLine)
925 {
926     char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
927     int i=0;
928     if(appData.recentEngines <= 0) return;
929     TidyProgramName(engineLine, "localhost", tidy+1);
930     tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
931     strncpy(buf+1, *list, MSG_SIZ-50);
932     if(p = strstr(buf, tidy)) { // tidy name appears in list
933         q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
934         while(*p++ = *++q); // squeeze out
935     }
936     strcat(tidy, buf+1); // put list behind tidy name
937     p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
938     if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
939     ASSIGN(*list, tidy+1);
940 }
941
942 void
943 SaveEngineList ()
944 {
945         FILE *f;
946         if(*engineListFile && (f = fopen(engineListFile, "w"))) {
947           fprintf(f, "-firstChessProgramNames {%s}\n", firstChessProgramNames);
948           fclose(f);
949         }
950 }
951
952 void
953 AddToEngineList (int i)
954 {
955         int len;
956         char quote, buf[MSG_SIZ];
957         char *q = firstChessProgramNames, *p = newEngineCommand;
958         if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
959         quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
960         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s",
961                         quote, p, quote, appData.directory[i],
962                         useNick ? " -fn \"" : "",
963                         useNick ? nickName : "",
964                         useNick ? "\"" : "",
965                         v1 ? " -firstProtocolVersion 1" : "",
966                         hasBook ? "" : " -fNoOwnBookUCI",
967                         isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
968                         storeVariant ? " -variant " : "",
969                         storeVariant ? VariantName(gameInfo.variant) : "");
970         if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " %s", wbOptions);
971         firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 2);
972         if(insert != q) insert[-1] = NULLCHAR;
973         snprintf(firstChessProgramNames, len, "%s\n%s\n%s", q, buf, insert);
974         if(q)   free(q);
975         SaveEngineList();
976         FloatToFront(&appData.recentEngineList, buf);
977         ASSIGN(currentEngine[i], buf);
978 }
979
980 void
981 LoadEngine ()
982 {
983     int i;
984     if(WaitForEngine(savCps, LoadEngine)) return;
985     if(tryNr == 1 && !isUCI) { SendToProgram("uci\n", savCps); tryNr = 2; ScheduleDelayedEvent(LoadEngine, FEATURE_TIMEOUT); return; }
986     if(tryNr) v1 = (tryNr == 2), tryNr = 0, AddToEngineList(0); // deferred to after protocol determination
987     CommonEngineInit(); // recalculate time odds
988     if(gameInfo.variant != StringToVariant(appData.variant)) {
989         // we changed variant when loading the engine; this forces us to reset
990         Reset(TRUE, savCps != &first);
991         oldMode = BeginningOfGame; // to prevent restoring old mode
992     }
993     InitChessProgram(savCps, FALSE);
994     if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
995     DisplayMessage("", "");
996     if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
997     for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
998     ThawUI();
999     SetGNUMode();
1000     if(oldMode == AnalyzeMode) AnalyzeModeEvent();
1001 }
1002
1003 void
1004 ReplaceEngine (ChessProgramState *cps, int n)
1005 {
1006     oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
1007     keepInfo = 1;
1008     if(oldMode != BeginningOfGame) EditGameEvent();
1009     keepInfo = 0;
1010     UnloadEngine(cps);
1011     appData.noChessProgram = FALSE;
1012     appData.clockMode = TRUE;
1013     InitEngine(cps, n);
1014     UpdateLogos(TRUE);
1015     if(n) return; // only startup first engine immediately; second can wait
1016     savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
1017     LoadEngine();
1018 }
1019
1020 static char resetOptions[] =
1021         "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
1022         "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
1023         "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 -fd \".\" "
1024         "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
1025
1026 void
1027 Load (ChessProgramState *cps, int i)
1028 {
1029     char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ], buf3[MSG_SIZ], jar;
1030     if(engineLine && engineLine[0]) { // an engine was selected from the combo box
1031         ASSIGN(currentEngine[i], engineLine);
1032         snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
1033         SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
1034         ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
1035         FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
1036         appData.firstProtocolVersion = PROTOVER;
1037         ParseArgsFromString(buf);
1038         SwapEngines(i);
1039         ReplaceEngine(cps, i);
1040         FloatToFront(&appData.recentEngineList, engineLine);
1041         if(gameMode == BeginningOfGame) Reset(TRUE, TRUE);
1042         return;
1043     }
1044     p = engineName;
1045     while(q = strchr(p, SLASH)) p = q+1;
1046     if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
1047     if(engineDir[0] != NULLCHAR) {
1048         ASSIGN(appData.directory[i], engineDir); p = engineName;
1049     } else if(p != engineName) { // derive directory from engine path, when not given
1050         p[-1] = 0;
1051         ASSIGN(appData.directory[i], engineName);
1052         p[-1] = SLASH;
1053         if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
1054     } else { ASSIGN(appData.directory[i], "."); }
1055     jar = (strstr(p, ".jar") == p + strlen(p) - 4);
1056     if(params[0]) {
1057         if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
1058         snprintf(command, MSG_SIZ, "%s %s", p, params);
1059         p = command;
1060     }
1061     if(jar) { snprintf(buf3, MSG_SIZ, "java -jar %s", p); p = buf3; }
1062     ASSIGN(appData.chessProgram[i], p);
1063     appData.isUCI[i] = isUCI;
1064     appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
1065     appData.hasOwnBookUCI[i] = hasBook;
1066     if(!nickName[0]) useNick = FALSE;
1067     if(useNick) ASSIGN(appData.pgnName[i], nickName);
1068     safeStrCpy(newEngineCommand, p, MSG_SIZ);
1069     tryNr = 1;
1070     ReplaceEngine(cps, i);
1071 }
1072
1073 void
1074 InitTimeControls ()
1075 {
1076     int matched, min, sec;
1077     /*
1078      * Parse timeControl resource
1079      */
1080     if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
1081                           appData.movesPerSession)) {
1082         char buf[MSG_SIZ];
1083         snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
1084         DisplayFatalError(buf, 0, 2);
1085     }
1086
1087     /*
1088      * Parse searchTime resource
1089      */
1090     if (*appData.searchTime != NULLCHAR) {
1091         matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
1092         if (matched == 1) {
1093             searchTime = min * 60;
1094         } else if (matched == 2) {
1095             searchTime = min * 60 + sec;
1096         } else {
1097             char buf[MSG_SIZ];
1098             snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
1099             DisplayFatalError(buf, 0, 2);
1100         }
1101     }
1102 }
1103
1104 void
1105 InitBackEnd1 ()
1106 {
1107
1108     ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1109     startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1110
1111     GetTimeMark(&programStartTime);
1112     srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1113     appData.seedBase = random() + (random()<<15);
1114     pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1115
1116     ClearProgramStats();
1117     programStats.ok_to_send = 1;
1118     programStats.seen_stat = 0;
1119
1120     /*
1121      * Initialize game list
1122      */
1123     ListNew(&gameList);
1124
1125
1126     /*
1127      * Internet chess server status
1128      */
1129     if (appData.icsActive) {
1130         appData.matchMode = FALSE;
1131         appData.matchGames = 0;
1132 #if ZIPPY
1133         appData.noChessProgram = !appData.zippyPlay;
1134 #else
1135         appData.zippyPlay = FALSE;
1136         appData.zippyTalk = FALSE;
1137         appData.noChessProgram = TRUE;
1138 #endif
1139         if (*appData.icsHelper != NULLCHAR) {
1140             appData.useTelnet = TRUE;
1141             appData.telnetProgram = appData.icsHelper;
1142         }
1143     } else {
1144         appData.zippyTalk = appData.zippyPlay = FALSE;
1145     }
1146
1147     /* [AS] Initialize pv info list [HGM] and game state */
1148     {
1149         int i, j;
1150
1151         for( i=0; i<=framePtr; i++ ) {
1152             pvInfoList[i].depth = -1;
1153             boards[i][EP_STATUS] = EP_NONE;
1154             for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1155         }
1156     }
1157
1158     InitTimeControls();
1159
1160     /* [AS] Adjudication threshold */
1161     adjudicateLossThreshold = appData.adjudicateLossThreshold;
1162
1163     InitEngine(&first, 0);
1164     InitEngine(&second, 1);
1165     CommonEngineInit();
1166
1167     pairing.which = "pairing"; // pairing engine
1168     pairing.pr = NoProc;
1169     pairing.isr = NULL;
1170     pairing.program = appData.pairingEngine;
1171     pairing.host = "localhost";
1172     pairing.dir = ".";
1173
1174     if (appData.icsActive) {
1175         appData.clockMode = TRUE;  /* changes dynamically in ICS mode */
1176     } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1177         appData.clockMode = FALSE;
1178         first.sendTime = second.sendTime = 0;
1179     }
1180
1181 #if ZIPPY
1182     /* Override some settings from environment variables, for backward
1183        compatibility.  Unfortunately it's not feasible to have the env
1184        vars just set defaults, at least in xboard.  Ugh.
1185     */
1186     if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1187       ZippyInit();
1188     }
1189 #endif
1190
1191     if (!appData.icsActive) {
1192       char buf[MSG_SIZ];
1193       int len;
1194
1195       /* Check for variants that are supported only in ICS mode,
1196          or not at all.  Some that are accepted here nevertheless
1197          have bugs; see comments below.
1198       */
1199       VariantClass variant = StringToVariant(appData.variant);
1200       switch (variant) {
1201       case VariantBughouse:     /* need four players and two boards */
1202       case VariantKriegspiel:   /* need to hide pieces and move details */
1203         /* case VariantFischeRandom: (Fabien: moved below) */
1204         len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1205         if( (len >= MSG_SIZ) && appData.debugMode )
1206           fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1207
1208         DisplayFatalError(buf, 0, 2);
1209         return;
1210
1211       case VariantUnknown:
1212       case VariantLoadable:
1213       case Variant29:
1214       case Variant30:
1215       case Variant31:
1216       case Variant32:
1217       case Variant33:
1218       case Variant34:
1219       case Variant35:
1220       case Variant36:
1221       default:
1222         len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1223         if( (len >= MSG_SIZ) && appData.debugMode )
1224           fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1225
1226         DisplayFatalError(buf, 0, 2);
1227         return;
1228
1229       case VariantNormal:     /* definitely works! */
1230         if(strcmp(appData.variant, "normal") && !appData.noChessProgram) { // [HGM] hope this is an engine-defined variant
1231           safeStrCpy(engineVariant, appData.variant, MSG_SIZ);
1232           return;
1233         }
1234       case VariantXiangqi:    /* [HGM] repetition rules not implemented */
1235       case VariantFairy:      /* [HGM] TestLegality definitely off! */
1236       case VariantGothic:     /* [HGM] should work */
1237       case VariantCapablanca: /* [HGM] should work */
1238       case VariantCourier:    /* [HGM] initial forced moves not implemented */
1239       case VariantShogi:      /* [HGM] could still mate with pawn drop */
1240       case VariantChu:        /* [HGM] experimental */
1241       case VariantKnightmate: /* [HGM] should work */
1242       case VariantCylinder:   /* [HGM] untested */
1243       case VariantFalcon:     /* [HGM] untested */
1244       case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1245                                  offboard interposition not understood */
1246       case VariantWildCastle: /* pieces not automatically shuffled */
1247       case VariantNoCastle:   /* pieces not automatically shuffled */
1248       case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1249       case VariantLosers:     /* should work except for win condition,
1250                                  and doesn't know captures are mandatory */
1251       case VariantSuicide:    /* should work except for win condition,
1252                                  and doesn't know captures are mandatory */
1253       case VariantGiveaway:   /* should work except for win condition,
1254                                  and doesn't know captures are mandatory */
1255       case VariantTwoKings:   /* should work */
1256       case VariantAtomic:     /* should work except for win condition */
1257       case Variant3Check:     /* should work except for win condition */
1258       case VariantShatranj:   /* should work except for all win conditions */
1259       case VariantMakruk:     /* should work except for draw countdown */
1260       case VariantASEAN :     /* should work except for draw countdown */
1261       case VariantBerolina:   /* might work if TestLegality is off */
1262       case VariantCapaRandom: /* should work */
1263       case VariantJanus:      /* should work */
1264       case VariantSuper:      /* experimental */
1265       case VariantGreat:      /* experimental, requires legality testing to be off */
1266       case VariantSChess:     /* S-Chess, should work */
1267       case VariantGrand:      /* should work */
1268       case VariantSpartan:    /* should work */
1269       case VariantLion:       /* should work */
1270       case VariantChuChess:   /* should work */
1271         break;
1272       }
1273     }
1274
1275 }
1276
1277 int
1278 NextIntegerFromString (char ** str, long * value)
1279 {
1280     int result = -1;
1281     char * s = *str;
1282
1283     while( *s == ' ' || *s == '\t' ) {
1284         s++;
1285     }
1286
1287     *value = 0;
1288
1289     if( *s >= '0' && *s <= '9' ) {
1290         while( *s >= '0' && *s <= '9' ) {
1291             *value = *value * 10 + (*s - '0');
1292             s++;
1293         }
1294
1295         result = 0;
1296     }
1297
1298     *str = s;
1299
1300     return result;
1301 }
1302
1303 int
1304 NextTimeControlFromString (char ** str, long * value)
1305 {
1306     long temp;
1307     int result = NextIntegerFromString( str, &temp );
1308
1309     if( result == 0 ) {
1310         *value = temp * 60; /* Minutes */
1311         if( **str == ':' ) {
1312             (*str)++;
1313             result = NextIntegerFromString( str, &temp );
1314             *value += temp; /* Seconds */
1315         }
1316     }
1317
1318     return result;
1319 }
1320
1321 int
1322 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1323 {   /* [HGM] routine added to read '+moves/time' for secondary time control. */
1324     int result = -1, type = 0; long temp, temp2;
1325
1326     if(**str != ':') return -1; // old params remain in force!
1327     (*str)++;
1328     if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1329     if( NextIntegerFromString( str, &temp ) ) return -1;
1330     if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1331
1332     if(**str != '/') {
1333         /* time only: incremental or sudden-death time control */
1334         if(**str == '+') { /* increment follows; read it */
1335             (*str)++;
1336             if(**str == '!') type = *(*str)++; // Bronstein TC
1337             if(result = NextIntegerFromString( str, &temp2)) return -1;
1338             *inc = temp2 * 1000;
1339             if(**str == '.') { // read fraction of increment
1340                 char *start = ++(*str);
1341                 if(result = NextIntegerFromString( str, &temp2)) return -1;
1342                 temp2 *= 1000;
1343                 while(start++ < *str) temp2 /= 10;
1344                 *inc += temp2;
1345             }
1346         } else *inc = 0;
1347         *moves = 0; *tc = temp * 1000; *incType = type;
1348         return 0;
1349     }
1350
1351     (*str)++; /* classical time control */
1352     result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1353
1354     if(result == 0) {
1355         *moves = temp;
1356         *tc    = temp2 * 1000;
1357         *inc   = 0;
1358         *incType = type;
1359     }
1360     return result;
1361 }
1362
1363 int
1364 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1365 {   /* [HGM] get time to add from the multi-session time-control string */
1366     int incType, moves=1; /* kludge to force reading of first session */
1367     long time, increment;
1368     char *s = tcString;
1369
1370     if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1371     do {
1372         if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1373         nextSession = s; suddenDeath = moves == 0 && increment == 0;
1374         if(movenr == -1) return time;    /* last move before new session     */
1375         if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1376         if(incType == '!' && lastUsed < increment) increment = lastUsed;
1377         if(!moves) return increment;     /* current session is incremental   */
1378         if(movenr >= 0) movenr -= moves; /* we already finished this session */
1379     } while(movenr >= -1);               /* try again for next session       */
1380
1381     return 0; // no new time quota on this move
1382 }
1383
1384 int
1385 ParseTimeControl (char *tc, float ti, int mps)
1386 {
1387   long tc1;
1388   long tc2;
1389   char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1390   int min, sec=0;
1391
1392   if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1393   if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1394       sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1395   if(ti > 0) {
1396
1397     if(mps)
1398       snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1399     else
1400       snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1401   } else {
1402     if(mps)
1403       snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1404     else
1405       snprintf(buf, MSG_SIZ, ":%s", mytc);
1406   }
1407   fullTimeControlString = StrSave(buf); // this should now be in PGN format
1408
1409   if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1410     return FALSE;
1411   }
1412
1413   if( *tc == '/' ) {
1414     /* Parse second time control */
1415     tc++;
1416
1417     if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1418       return FALSE;
1419     }
1420
1421     if( tc2 == 0 ) {
1422       return FALSE;
1423     }
1424
1425     timeControl_2 = tc2 * 1000;
1426   }
1427   else {
1428     timeControl_2 = 0;
1429   }
1430
1431   if( tc1 == 0 ) {
1432     return FALSE;
1433   }
1434
1435   timeControl = tc1 * 1000;
1436
1437   if (ti >= 0) {
1438     timeIncrement = ti * 1000;  /* convert to ms */
1439     movesPerSession = 0;
1440   } else {
1441     timeIncrement = 0;
1442     movesPerSession = mps;
1443   }
1444   return TRUE;
1445 }
1446
1447 void
1448 InitBackEnd2 ()
1449 {
1450     if (appData.debugMode) {
1451 #    ifdef __GIT_VERSION
1452       fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
1453 #    else
1454       fprintf(debugFP, "Version: %s\n", programVersion);
1455 #    endif
1456     }
1457     ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1458
1459     set_cont_sequence(appData.wrapContSeq);
1460     if (appData.matchGames > 0) {
1461         appData.matchMode = TRUE;
1462     } else if (appData.matchMode) {
1463         appData.matchGames = 1;
1464     }
1465     if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1466         appData.matchGames = appData.sameColorGames;
1467     if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1468         if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1469         if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1470     }
1471     Reset(TRUE, FALSE);
1472     if (appData.noChessProgram || first.protocolVersion == 1) {
1473       InitBackEnd3();
1474     } else {
1475       /* kludge: allow timeout for initial "feature" commands */
1476       FreezeUI();
1477       DisplayMessage("", _("Starting chess program"));
1478       ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1479     }
1480 }
1481
1482 int
1483 CalculateIndex (int index, int gameNr)
1484 {   // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1485     int res;
1486     if(index > 0) return index; // fixed nmber
1487     if(index == 0) return 1;
1488     res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1489     if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1490     return res;
1491 }
1492
1493 int
1494 LoadGameOrPosition (int gameNr)
1495 {   // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1496     if (*appData.loadGameFile != NULLCHAR) {
1497         if (!LoadGameFromFile(appData.loadGameFile,
1498                 CalculateIndex(appData.loadGameIndex, gameNr),
1499                               appData.loadGameFile, FALSE)) {
1500             DisplayFatalError(_("Bad game file"), 0, 1);
1501             return 0;
1502         }
1503     } else if (*appData.loadPositionFile != NULLCHAR) {
1504         if (!LoadPositionFromFile(appData.loadPositionFile,
1505                 CalculateIndex(appData.loadPositionIndex, gameNr),
1506                                   appData.loadPositionFile)) {
1507             DisplayFatalError(_("Bad position file"), 0, 1);
1508             return 0;
1509         }
1510     }
1511     return 1;
1512 }
1513
1514 void
1515 ReserveGame (int gameNr, char resChar)
1516 {
1517     FILE *tf = fopen(appData.tourneyFile, "r+");
1518     char *p, *q, c, buf[MSG_SIZ];
1519     if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1520     safeStrCpy(buf, lastMsg, MSG_SIZ);
1521     DisplayMessage(_("Pick new game"), "");
1522     flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1523     ParseArgsFromFile(tf);
1524     p = q = appData.results;
1525     if(appData.debugMode) {
1526       char *r = appData.participants;
1527       fprintf(debugFP, "results = '%s'\n", p);
1528       while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1529       fprintf(debugFP, "\n");
1530     }
1531     while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1532     nextGame = q - p;
1533     q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1534     safeStrCpy(q, p, strlen(p) + 2);
1535     if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1536     if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1537     if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1538         if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1539         q[nextGame] = '*';
1540     }
1541     fseek(tf, -(strlen(p)+4), SEEK_END);
1542     c = fgetc(tf);
1543     if(c != '"') // depending on DOS or Unix line endings we can be one off
1544          fseek(tf, -(strlen(p)+2), SEEK_END);
1545     else fseek(tf, -(strlen(p)+3), SEEK_END);
1546     fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1547     DisplayMessage(buf, "");
1548     free(p); appData.results = q;
1549     if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1550        (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1551       int round = appData.defaultMatchGames * appData.tourneyType;
1552       if(gameNr < 0 || appData.tourneyType < 1 ||  // gauntlet engine can always stay loaded as first engine
1553          appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1554         UnloadEngine(&first);  // next game belongs to other pairing;
1555         UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1556     }
1557     if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1558 }
1559
1560 void
1561 MatchEvent (int mode)
1562 {       // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1563         int dummy;
1564         if(matchMode) { // already in match mode: switch it off
1565             abortMatch = TRUE;
1566             if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1567             return;
1568         }
1569 //      if(gameMode != BeginningOfGame) {
1570 //          DisplayError(_("You can only start a match from the initial position."), 0);
1571 //          return;
1572 //      }
1573         abortMatch = FALSE;
1574         if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1575         /* Set up machine vs. machine match */
1576         nextGame = 0;
1577         NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1578         if(appData.tourneyFile[0]) {
1579             ReserveGame(-1, 0);
1580             if(nextGame > appData.matchGames) {
1581                 char buf[MSG_SIZ];
1582                 if(strchr(appData.results, '*') == NULL) {
1583                     FILE *f;
1584                     appData.tourneyCycles++;
1585                     if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1586                         fclose(f);
1587                         NextTourneyGame(-1, &dummy);
1588                         ReserveGame(-1, 0);
1589                         if(nextGame <= appData.matchGames) {
1590                             DisplayNote(_("You restarted an already completed tourney.\nOne more cycle will now be added to it.\nGames commence in 10 sec."));
1591                             matchMode = mode;
1592                             ScheduleDelayedEvent(NextMatchGame, 10000);
1593                             return;
1594                         }
1595                     }
1596                 }
1597                 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1598                 DisplayError(buf, 0);
1599                 appData.tourneyFile[0] = 0;
1600                 return;
1601             }
1602         } else
1603         if (appData.noChessProgram) {  // [HGM] in tourney engines are loaded automatically
1604             DisplayFatalError(_("Can't have a match with no chess programs"),
1605                               0, 2);
1606             return;
1607         }
1608         matchMode = mode;
1609         matchGame = roundNr = 1;
1610         first.matchWins = second.matchWins = totalTime = 0; // [HGM] match: needed in later matches
1611         NextMatchGame();
1612 }
1613
1614 void
1615 InitBackEnd3 P((void))
1616 {
1617     GameMode initialMode;
1618     char buf[MSG_SIZ];
1619     int err, len;
1620
1621     ParseFeatures(appData.features[0], &first);
1622     if(!appData.icsActive && !appData.noChessProgram && !appData.matchMode &&                         // mode involves only first engine
1623        !strcmp(appData.variant, "normal") &&                                                          // no explicit variant request
1624         appData.NrRanks == -1 && appData.NrFiles == -1 && appData.holdingsSize == -1 &&               // no size overrides requested
1625        !SupportedVariant(first.variants, VariantNormal, 8, 8, 0, first.protocolVersion, "") &&        // but 'normal' won't work with engine
1626        !SupportedVariant(first.variants, VariantFischeRandom, 8, 8, 0, first.protocolVersion, "") ) { // nor will Chess960
1627         char c, *q = first.variants, *p = strchr(q, ',');
1628         if(p) *p = NULLCHAR;
1629         if(StringToVariant(q) != VariantUnknown) { // the engine can play a recognized variant, however
1630             int w, h, s;
1631             if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
1632                 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
1633             ASSIGN(appData.variant, q); // fake user requested the first variant played by the engine
1634             Reset(TRUE, FALSE);         // and re-initialize
1635         }
1636         if(p) *p = ',';
1637     }
1638
1639     InitChessProgram(&first, startedFromSetupPosition);
1640
1641     if(!appData.noChessProgram) {  /* [HGM] tidy: redo program version to use name from myname feature */
1642         free(programVersion);
1643         programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1644         sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1645         FloatToFront(&appData.recentEngineList, currentEngine[0] ? currentEngine[0] : appData.firstChessProgram);
1646     }
1647
1648     if (appData.icsActive) {
1649 #ifdef WIN32
1650         /* [DM] Make a console window if needed [HGM] merged ifs */
1651         ConsoleCreate();
1652 #endif
1653         err = establish();
1654         if (err != 0)
1655           {
1656             if (*appData.icsCommPort != NULLCHAR)
1657               len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1658                              appData.icsCommPort);
1659             else
1660               len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1661                         appData.icsHost, appData.icsPort);
1662
1663             if( (len >= MSG_SIZ) && appData.debugMode )
1664               fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1665
1666             DisplayFatalError(buf, err, 1);
1667             return;
1668         }
1669         SetICSMode();
1670         telnetISR =
1671           AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1672         fromUserISR =
1673           AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1674         if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1675             ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1676     } else if (appData.noChessProgram) {
1677         SetNCPMode();
1678     } else {
1679         SetGNUMode();
1680     }
1681
1682     if (*appData.cmailGameName != NULLCHAR) {
1683         SetCmailMode();
1684         OpenLoopback(&cmailPR);
1685         cmailISR =
1686           AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1687     }
1688
1689     ThawUI();
1690     DisplayMessage("", "");
1691     if (StrCaseCmp(appData.initialMode, "") == 0) {
1692       initialMode = BeginningOfGame;
1693       if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1694         gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1695         ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1696         gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1697         ModeHighlight();
1698       }
1699     } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1700       initialMode = TwoMachinesPlay;
1701     } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1702       initialMode = AnalyzeFile;
1703     } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1704       initialMode = AnalyzeMode;
1705     } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1706       initialMode = MachinePlaysWhite;
1707     } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1708       initialMode = MachinePlaysBlack;
1709     } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1710       initialMode = EditGame;
1711     } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1712       initialMode = EditPosition;
1713     } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1714       initialMode = Training;
1715     } else {
1716       len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1717       if( (len >= MSG_SIZ) && appData.debugMode )
1718         fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1719
1720       DisplayFatalError(buf, 0, 2);
1721       return;
1722     }
1723
1724     if (appData.matchMode) {
1725         if(appData.tourneyFile[0]) { // start tourney from command line
1726             FILE *f;
1727             if(f = fopen(appData.tourneyFile, "r")) {
1728                 ParseArgsFromFile(f); // make sure tourney parmeters re known
1729                 fclose(f);
1730                 appData.clockMode = TRUE;
1731                 SetGNUMode();
1732             } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1733         }
1734         MatchEvent(TRUE);
1735     } else if (*appData.cmailGameName != NULLCHAR) {
1736         /* Set up cmail mode */
1737         ReloadCmailMsgEvent(TRUE);
1738     } else {
1739         /* Set up other modes */
1740         if (initialMode == AnalyzeFile) {
1741           if (*appData.loadGameFile == NULLCHAR) {
1742             DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1743             return;
1744           }
1745         }
1746         if (*appData.loadGameFile != NULLCHAR) {
1747             (void) LoadGameFromFile(appData.loadGameFile,
1748                                     appData.loadGameIndex,
1749                                     appData.loadGameFile, TRUE);
1750         } else if (*appData.loadPositionFile != NULLCHAR) {
1751             (void) LoadPositionFromFile(appData.loadPositionFile,
1752                                         appData.loadPositionIndex,
1753                                         appData.loadPositionFile);
1754             /* [HGM] try to make self-starting even after FEN load */
1755             /* to allow automatic setup of fairy variants with wtm */
1756             if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1757                 gameMode = BeginningOfGame;
1758                 setboardSpoiledMachineBlack = 1;
1759             }
1760             /* [HGM] loadPos: make that every new game uses the setup */
1761             /* from file as long as we do not switch variant          */
1762             if(!blackPlaysFirst) {
1763                 startedFromPositionFile = TRUE;
1764                 CopyBoard(filePosition, boards[0]);
1765                 CopyBoard(initialPosition, boards[0]);
1766             }
1767         } else if(*appData.fen != NULLCHAR) {
1768             if(ParseFEN(filePosition, &blackPlaysFirst, appData.fen, TRUE) && !blackPlaysFirst) {
1769                 startedFromPositionFile = TRUE;
1770                 Reset(TRUE, TRUE);
1771             }
1772         }
1773         if (initialMode == AnalyzeMode) {
1774           if (appData.noChessProgram) {
1775             DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1776             return;
1777           }
1778           if (appData.icsActive) {
1779             DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1780             return;
1781           }
1782           AnalyzeModeEvent();
1783         } else if (initialMode == AnalyzeFile) {
1784           appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1785           ShowThinkingEvent();
1786           AnalyzeFileEvent();
1787           AnalysisPeriodicEvent(1);
1788         } else if (initialMode == MachinePlaysWhite) {
1789           if (appData.noChessProgram) {
1790             DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1791                               0, 2);
1792             return;
1793           }
1794           if (appData.icsActive) {
1795             DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1796                               0, 2);
1797             return;
1798           }
1799           MachineWhiteEvent();
1800         } else if (initialMode == MachinePlaysBlack) {
1801           if (appData.noChessProgram) {
1802             DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1803                               0, 2);
1804             return;
1805           }
1806           if (appData.icsActive) {
1807             DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1808                               0, 2);
1809             return;
1810           }
1811           MachineBlackEvent();
1812         } else if (initialMode == TwoMachinesPlay) {
1813           if (appData.noChessProgram) {
1814             DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1815                               0, 2);
1816             return;
1817           }
1818           if (appData.icsActive) {
1819             DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1820                               0, 2);
1821             return;
1822           }
1823           TwoMachinesEvent();
1824         } else if (initialMode == EditGame) {
1825           EditGameEvent();
1826         } else if (initialMode == EditPosition) {
1827           EditPositionEvent();
1828         } else if (initialMode == Training) {
1829           if (*appData.loadGameFile == NULLCHAR) {
1830             DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1831             return;
1832           }
1833           TrainingEvent();
1834         }
1835     }
1836 }
1837
1838 void
1839 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1840 {
1841     DisplayBook(current+1);
1842
1843     MoveHistorySet( movelist, first, last, current, pvInfoList );
1844
1845     EvalGraphSet( first, last, current, pvInfoList );
1846
1847     MakeEngineOutputTitle();
1848 }
1849
1850 /*
1851  * Establish will establish a contact to a remote host.port.
1852  * Sets icsPR to a ProcRef for a process (or pseudo-process)
1853  *  used to talk to the host.
1854  * Returns 0 if okay, error code if not.
1855  */
1856 int
1857 establish ()
1858 {
1859     char buf[MSG_SIZ];
1860
1861     if (*appData.icsCommPort != NULLCHAR) {
1862         /* Talk to the host through a serial comm port */
1863         return OpenCommPort(appData.icsCommPort, &icsPR);
1864
1865     } else if (*appData.gateway != NULLCHAR) {
1866         if (*appData.remoteShell == NULLCHAR) {
1867             /* Use the rcmd protocol to run telnet program on a gateway host */
1868             snprintf(buf, sizeof(buf), "%s %s %s",
1869                     appData.telnetProgram, appData.icsHost, appData.icsPort);
1870             return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1871
1872         } else {
1873             /* Use the rsh program to run telnet program on a gateway host */
1874             if (*appData.remoteUser == NULLCHAR) {
1875                 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1876                         appData.gateway, appData.telnetProgram,
1877                         appData.icsHost, appData.icsPort);
1878             } else {
1879                 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1880                         appData.remoteShell, appData.gateway,
1881                         appData.remoteUser, appData.telnetProgram,
1882                         appData.icsHost, appData.icsPort);
1883             }
1884             return StartChildProcess(buf, "", &icsPR);
1885
1886         }
1887     } else if (appData.useTelnet) {
1888         return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1889
1890     } else {
1891         /* TCP socket interface differs somewhat between
1892            Unix and NT; handle details in the front end.
1893            */
1894         return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1895     }
1896 }
1897
1898 void
1899 EscapeExpand (char *p, char *q)
1900 {       // [HGM] initstring: routine to shape up string arguments
1901         while(*p++ = *q++) if(p[-1] == '\\')
1902             switch(*q++) {
1903                 case 'n': p[-1] = '\n'; break;
1904                 case 'r': p[-1] = '\r'; break;
1905                 case 't': p[-1] = '\t'; break;
1906                 case '\\': p[-1] = '\\'; break;
1907                 case 0: *p = 0; return;
1908                 default: p[-1] = q[-1]; break;
1909             }
1910 }
1911
1912 void
1913 show_bytes (FILE *fp, char *buf, int count)
1914 {
1915     while (count--) {
1916         if (*buf < 040 || *(unsigned char *) buf > 0177) {
1917             fprintf(fp, "\\%03o", *buf & 0xff);
1918         } else {
1919             putc(*buf, fp);
1920         }
1921         buf++;
1922     }
1923     fflush(fp);
1924 }
1925
1926 /* Returns an errno value */
1927 int
1928 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1929 {
1930     char buf[8192], *p, *q, *buflim;
1931     int left, newcount, outcount;
1932
1933     if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1934         *appData.gateway != NULLCHAR) {
1935         if (appData.debugMode) {
1936             fprintf(debugFP, ">ICS: ");
1937             show_bytes(debugFP, message, count);
1938             fprintf(debugFP, "\n");
1939         }
1940         return OutputToProcess(pr, message, count, outError);
1941     }
1942
1943     buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1944     p = message;
1945     q = buf;
1946     left = count;
1947     newcount = 0;
1948     while (left) {
1949         if (q >= buflim) {
1950             if (appData.debugMode) {
1951                 fprintf(debugFP, ">ICS: ");
1952                 show_bytes(debugFP, buf, newcount);
1953                 fprintf(debugFP, "\n");
1954             }
1955             outcount = OutputToProcess(pr, buf, newcount, outError);
1956             if (outcount < newcount) return -1; /* to be sure */
1957             q = buf;
1958             newcount = 0;
1959         }
1960         if (*p == '\n') {
1961             *q++ = '\r';
1962             newcount++;
1963         } else if (((unsigned char) *p) == TN_IAC) {
1964             *q++ = (char) TN_IAC;
1965             newcount ++;
1966         }
1967         *q++ = *p++;
1968         newcount++;
1969         left--;
1970     }
1971     if (appData.debugMode) {
1972         fprintf(debugFP, ">ICS: ");
1973         show_bytes(debugFP, buf, newcount);
1974         fprintf(debugFP, "\n");
1975     }
1976     outcount = OutputToProcess(pr, buf, newcount, outError);
1977     if (outcount < newcount) return -1; /* to be sure */
1978     return count;
1979 }
1980
1981 void
1982 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1983 {
1984     int outError, outCount;
1985     static int gotEof = 0;
1986     static FILE *ini;
1987
1988     /* Pass data read from player on to ICS */
1989     if (count > 0) {
1990         gotEof = 0;
1991         outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1992         if (outCount < count) {
1993             DisplayFatalError(_("Error writing to ICS"), outError, 1);
1994         }
1995         if(have_sent_ICS_logon == 2) {
1996           if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
1997             fprintf(ini, "%s", message);
1998             have_sent_ICS_logon = 3;
1999           } else
2000             have_sent_ICS_logon = 1;
2001         } else if(have_sent_ICS_logon == 3) {
2002             fprintf(ini, "%s", message);
2003             fclose(ini);
2004           have_sent_ICS_logon = 1;
2005         }
2006     } else if (count < 0) {
2007         RemoveInputSource(isr);
2008         DisplayFatalError(_("Error reading from keyboard"), error, 1);
2009     } else if (gotEof++ > 0) {
2010         RemoveInputSource(isr);
2011         DisplayFatalError(_("Got end of file from keyboard"), 0, 666); // [HGM] 666 is kludge to alert front end
2012     }
2013 }
2014
2015 void
2016 KeepAlive ()
2017 {   // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
2018     if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
2019     connectionAlive = FALSE; // only sticks if no response to 'date' command.
2020     SendToICS("date\n");
2021     if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
2022 }
2023
2024 /* added routine for printf style output to ics */
2025 void
2026 ics_printf (char *format, ...)
2027 {
2028     char buffer[MSG_SIZ];
2029     va_list args;
2030
2031     va_start(args, format);
2032     vsnprintf(buffer, sizeof(buffer), format, args);
2033     buffer[sizeof(buffer)-1] = '\0';
2034     SendToICS(buffer);
2035     va_end(args);
2036 }
2037
2038 void
2039 SendToICS (char *s)
2040 {
2041     int count, outCount, outError;
2042
2043     if (icsPR == NoProc) return;
2044
2045     count = strlen(s);
2046     outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
2047     if (outCount < count) {
2048         DisplayFatalError(_("Error writing to ICS"), outError, 1);
2049     }
2050 }
2051
2052 /* This is used for sending logon scripts to the ICS. Sending
2053    without a delay causes problems when using timestamp on ICC
2054    (at least on my machine). */
2055 void
2056 SendToICSDelayed (char *s, long msdelay)
2057 {
2058     int count, outCount, outError;
2059
2060     if (icsPR == NoProc) return;
2061
2062     count = strlen(s);
2063     if (appData.debugMode) {
2064         fprintf(debugFP, ">ICS: ");
2065         show_bytes(debugFP, s, count);
2066         fprintf(debugFP, "\n");
2067     }
2068     outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
2069                                       msdelay);
2070     if (outCount < count) {
2071         DisplayFatalError(_("Error writing to ICS"), outError, 1);
2072     }
2073 }
2074
2075
2076 /* Remove all highlighting escape sequences in s
2077    Also deletes any suffix starting with '('
2078    */
2079 char *
2080 StripHighlightAndTitle (char *s)
2081 {
2082     static char retbuf[MSG_SIZ];
2083     char *p = retbuf;
2084
2085     while (*s != NULLCHAR) {
2086         while (*s == '\033') {
2087             while (*s != NULLCHAR && !isalpha(*s)) s++;
2088             if (*s != NULLCHAR) s++;
2089         }
2090         while (*s != NULLCHAR && *s != '\033') {
2091             if (*s == '(' || *s == '[') {
2092                 *p = NULLCHAR;
2093                 return retbuf;
2094             }
2095             *p++ = *s++;
2096         }
2097     }
2098     *p = NULLCHAR;
2099     return retbuf;
2100 }
2101
2102 /* Remove all highlighting escape sequences in s */
2103 char *
2104 StripHighlight (char *s)
2105 {
2106     static char retbuf[MSG_SIZ];
2107     char *p = retbuf;
2108
2109     while (*s != NULLCHAR) {
2110         while (*s == '\033') {
2111             while (*s != NULLCHAR && !isalpha(*s)) s++;
2112             if (*s != NULLCHAR) s++;
2113         }
2114         while (*s != NULLCHAR && *s != '\033') {
2115             *p++ = *s++;
2116         }
2117     }
2118     *p = NULLCHAR;
2119     return retbuf;
2120 }
2121
2122 char engineVariant[MSG_SIZ];
2123 char *variantNames[] = VARIANT_NAMES;
2124 char *
2125 VariantName (VariantClass v)
2126 {
2127     if(v == VariantUnknown || *engineVariant) return engineVariant;
2128     return variantNames[v];
2129 }
2130
2131
2132 /* Identify a variant from the strings the chess servers use or the
2133    PGN Variant tag names we use. */
2134 VariantClass
2135 StringToVariant (char *e)
2136 {
2137     char *p;
2138     int wnum = -1;
2139     VariantClass v = VariantNormal;
2140     int i, found = FALSE;
2141     char buf[MSG_SIZ], c;
2142     int len;
2143
2144     if (!e) return v;
2145
2146     /* [HGM] skip over optional board-size prefixes */
2147     if( sscanf(e, "%dx%d_%c", &i, &i, &c) == 3 ||
2148         sscanf(e, "%dx%d+%d_%c", &i, &i, &i, &c) == 4 ) {
2149         while( *e++ != '_');
2150     }
2151
2152     if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2153         v = VariantNormal;
2154         found = TRUE;
2155     } else
2156     for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2157       if (p = StrCaseStr(e, variantNames[i])) {
2158         if(p && i >= VariantShogi && (p != e && !appData.icsActive || isalpha(p[strlen(variantNames[i])]))) continue;
2159         v = (VariantClass) i;
2160         found = TRUE;
2161         break;
2162       }
2163     }
2164
2165     if (!found) {
2166       if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2167           || StrCaseStr(e, "wild/fr")
2168           || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2169         v = VariantFischeRandom;
2170       } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2171                  (i = 1, p = StrCaseStr(e, "w"))) {
2172         p += i;
2173         while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2174         if (isdigit(*p)) {
2175           wnum = atoi(p);
2176         } else {
2177           wnum = -1;
2178         }
2179         switch (wnum) {
2180         case 0: /* FICS only, actually */
2181         case 1:
2182           /* Castling legal even if K starts on d-file */
2183           v = VariantWildCastle;
2184           break;
2185         case 2:
2186         case 3:
2187         case 4:
2188           /* Castling illegal even if K & R happen to start in
2189              normal positions. */
2190           v = VariantNoCastle;
2191           break;
2192         case 5:
2193         case 7:
2194         case 8:
2195         case 10:
2196         case 11:
2197         case 12:
2198         case 13:
2199         case 14:
2200         case 15:
2201         case 18:
2202         case 19:
2203           /* Castling legal iff K & R start in normal positions */
2204           v = VariantNormal;
2205           break;
2206         case 6:
2207         case 20:
2208         case 21:
2209           /* Special wilds for position setup; unclear what to do here */
2210           v = VariantLoadable;
2211           break;
2212         case 9:
2213           /* Bizarre ICC game */
2214           v = VariantTwoKings;
2215           break;
2216         case 16:
2217           v = VariantKriegspiel;
2218           break;
2219         case 17:
2220           v = VariantLosers;
2221           break;
2222         case 22:
2223           v = VariantFischeRandom;
2224           break;
2225         case 23:
2226           v = VariantCrazyhouse;
2227           break;
2228         case 24:
2229           v = VariantBughouse;
2230           break;
2231         case 25:
2232           v = Variant3Check;
2233           break;
2234         case 26:
2235           /* Not quite the same as FICS suicide! */
2236           v = VariantGiveaway;
2237           break;
2238         case 27:
2239           v = VariantAtomic;
2240           break;
2241         case 28:
2242           v = VariantShatranj;
2243           break;
2244
2245         /* Temporary names for future ICC types.  The name *will* change in
2246            the next xboard/WinBoard release after ICC defines it. */
2247         case 29:
2248           v = Variant29;
2249           break;
2250         case 30:
2251           v = Variant30;
2252           break;
2253         case 31:
2254           v = Variant31;
2255           break;
2256         case 32:
2257           v = Variant32;
2258           break;
2259         case 33:
2260           v = Variant33;
2261           break;
2262         case 34:
2263           v = Variant34;
2264           break;
2265         case 35:
2266           v = Variant35;
2267           break;
2268         case 36:
2269           v = Variant36;
2270           break;
2271         case 37:
2272           v = VariantShogi;
2273           break;
2274         case 38:
2275           v = VariantXiangqi;
2276           break;
2277         case 39:
2278           v = VariantCourier;
2279           break;
2280         case 40:
2281           v = VariantGothic;
2282           break;
2283         case 41:
2284           v = VariantCapablanca;
2285           break;
2286         case 42:
2287           v = VariantKnightmate;
2288           break;
2289         case 43:
2290           v = VariantFairy;
2291           break;
2292         case 44:
2293           v = VariantCylinder;
2294           break;
2295         case 45:
2296           v = VariantFalcon;
2297           break;
2298         case 46:
2299           v = VariantCapaRandom;
2300           break;
2301         case 47:
2302           v = VariantBerolina;
2303           break;
2304         case 48:
2305           v = VariantJanus;
2306           break;
2307         case 49:
2308           v = VariantSuper;
2309           break;
2310         case 50:
2311           v = VariantGreat;
2312           break;
2313         case -1:
2314           /* Found "wild" or "w" in the string but no number;
2315              must assume it's normal chess. */
2316           v = VariantNormal;
2317           break;
2318         default:
2319           len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2320           if( (len >= MSG_SIZ) && appData.debugMode )
2321             fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2322
2323           DisplayError(buf, 0);
2324           v = VariantUnknown;
2325           break;
2326         }
2327       }
2328     }
2329     if (appData.debugMode) {
2330       fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
2331               e, wnum, VariantName(v));
2332     }
2333     return v;
2334 }
2335
2336 static int leftover_start = 0, leftover_len = 0;
2337 char star_match[STAR_MATCH_N][MSG_SIZ];
2338
2339 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2340    advance *index beyond it, and set leftover_start to the new value of
2341    *index; else return FALSE.  If pattern contains the character '*', it
2342    matches any sequence of characters not containing '\r', '\n', or the
2343    character following the '*' (if any), and the matched sequence(s) are
2344    copied into star_match.
2345    */
2346 int
2347 looking_at ( char *buf, int *index, char *pattern)
2348 {
2349     char *bufp = &buf[*index], *patternp = pattern;
2350     int star_count = 0;
2351     char *matchp = star_match[0];
2352
2353     for (;;) {
2354         if (*patternp == NULLCHAR) {
2355             *index = leftover_start = bufp - buf;
2356             *matchp = NULLCHAR;
2357             return TRUE;
2358         }
2359         if (*bufp == NULLCHAR) return FALSE;
2360         if (*patternp == '*') {
2361             if (*bufp == *(patternp + 1)) {
2362                 *matchp = NULLCHAR;
2363                 matchp = star_match[++star_count];
2364                 patternp += 2;
2365                 bufp++;
2366                 continue;
2367             } else if (*bufp == '\n' || *bufp == '\r') {
2368                 patternp++;
2369                 if (*patternp == NULLCHAR)
2370                   continue;
2371                 else
2372                   return FALSE;
2373             } else {
2374                 *matchp++ = *bufp++;
2375                 continue;
2376             }
2377         }
2378         if (*patternp != *bufp) return FALSE;
2379         patternp++;
2380         bufp++;
2381     }
2382 }
2383
2384 void
2385 SendToPlayer (char *data, int length)
2386 {
2387     int error, outCount;
2388     outCount = OutputToProcess(NoProc, data, length, &error);
2389     if (outCount < length) {
2390         DisplayFatalError(_("Error writing to display"), error, 1);
2391     }
2392 }
2393
2394 void
2395 PackHolding (char packed[], char *holding)
2396 {
2397     char *p = holding;
2398     char *q = packed;
2399     int runlength = 0;
2400     int curr = 9999;
2401     do {
2402         if (*p == curr) {
2403             runlength++;
2404         } else {
2405             switch (runlength) {
2406               case 0:
2407                 break;
2408               case 1:
2409                 *q++ = curr;
2410                 break;
2411               case 2:
2412                 *q++ = curr;
2413                 *q++ = curr;
2414                 break;
2415               default:
2416                 sprintf(q, "%d", runlength);
2417                 while (*q) q++;
2418                 *q++ = curr;
2419                 break;
2420             }
2421             runlength = 1;
2422             curr = *p;
2423         }
2424     } while (*p++);
2425     *q = NULLCHAR;
2426 }
2427
2428 /* Telnet protocol requests from the front end */
2429 void
2430 TelnetRequest (unsigned char ddww, unsigned char option)
2431 {
2432     unsigned char msg[3];
2433     int outCount, outError;
2434
2435     if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2436
2437     if (appData.debugMode) {
2438         char buf1[8], buf2[8], *ddwwStr, *optionStr;
2439         switch (ddww) {
2440           case TN_DO:
2441             ddwwStr = "DO";
2442             break;
2443           case TN_DONT:
2444             ddwwStr = "DONT";
2445             break;
2446           case TN_WILL:
2447             ddwwStr = "WILL";
2448             break;
2449           case TN_WONT:
2450             ddwwStr = "WONT";
2451             break;
2452           default:
2453             ddwwStr = buf1;
2454             snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2455             break;
2456         }
2457         switch (option) {
2458           case TN_ECHO:
2459             optionStr = "ECHO";
2460             break;
2461           default:
2462             optionStr = buf2;
2463             snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2464             break;
2465         }
2466         fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2467     }
2468     msg[0] = TN_IAC;
2469     msg[1] = ddww;
2470     msg[2] = option;
2471     outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2472     if (outCount < 3) {
2473         DisplayFatalError(_("Error writing to ICS"), outError, 1);
2474     }
2475 }
2476
2477 void
2478 DoEcho ()
2479 {
2480     if (!appData.icsActive) return;
2481     TelnetRequest(TN_DO, TN_ECHO);
2482 }
2483
2484 void
2485 DontEcho ()
2486 {
2487     if (!appData.icsActive) return;
2488     TelnetRequest(TN_DONT, TN_ECHO);
2489 }
2490
2491 void
2492 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2493 {
2494     /* put the holdings sent to us by the server on the board holdings area */
2495     int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2496     char p;
2497     ChessSquare piece;
2498
2499     if(gameInfo.holdingsWidth < 2)  return;
2500     if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2501         return; // prevent overwriting by pre-board holdings
2502
2503     if( (int)lowestPiece >= BlackPawn ) {
2504         holdingsColumn = 0;
2505         countsColumn = 1;
2506         holdingsStartRow = handSize-1;
2507         direction = -1;
2508     } else {
2509         holdingsColumn = BOARD_WIDTH-1;
2510         countsColumn = BOARD_WIDTH-2;
2511         holdingsStartRow = 0;
2512         direction = 1;
2513     }
2514
2515     for(i=0; i<BOARD_RANKS-1; i++) { /* clear holdings */
2516         board[i][holdingsColumn] = EmptySquare;
2517         board[i][countsColumn]   = (ChessSquare) 0;
2518     }
2519     while( (p=*holdings++) != NULLCHAR ) {
2520         piece = CharToPiece( ToUpper(p) );
2521         if(piece == EmptySquare) continue;
2522         /*j = (int) piece - (int) WhitePawn;*/
2523         j = PieceToNumber(piece);
2524         if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2525         if(j < 0) continue;               /* should not happen */
2526         piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2527         board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2528         board[holdingsStartRow+j*direction][countsColumn]++;
2529     }
2530 }
2531
2532
2533 void
2534 VariantSwitch (Board board, VariantClass newVariant)
2535 {
2536    int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2537    static Board oldBoard;
2538
2539    startedFromPositionFile = FALSE;
2540    if(gameInfo.variant == newVariant) return;
2541
2542    /* [HGM] This routine is called each time an assignment is made to
2543     * gameInfo.variant during a game, to make sure the board sizes
2544     * are set to match the new variant. If that means adding or deleting
2545     * holdings, we shift the playing board accordingly
2546     * This kludge is needed because in ICS observe mode, we get boards
2547     * of an ongoing game without knowing the variant, and learn about the
2548     * latter only later. This can be because of the move list we requested,
2549     * in which case the game history is refilled from the beginning anyway,
2550     * but also when receiving holdings of a crazyhouse game. In the latter
2551     * case we want to add those holdings to the already received position.
2552     */
2553
2554
2555    if (appData.debugMode) {
2556      fprintf(debugFP, "Switch board from %s to %s\n",
2557              VariantName(gameInfo.variant), VariantName(newVariant));
2558      setbuf(debugFP, NULL);
2559    }
2560    shuffleOpenings = 0;       /* [HGM] shuffle */
2561    gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2562    switch(newVariant)
2563      {
2564      case VariantShogi:
2565        newWidth = 9;  newHeight = 9;
2566        gameInfo.holdingsSize = 7;
2567      case VariantBughouse:
2568      case VariantCrazyhouse:
2569        newHoldingsWidth = 2; break;
2570      case VariantGreat:
2571        newWidth = 10;
2572      case VariantSuper:
2573        newHoldingsWidth = 2;
2574        gameInfo.holdingsSize = 8;
2575        break;
2576      case VariantGothic:
2577      case VariantCapablanca:
2578      case VariantCapaRandom:
2579        newWidth = 10;
2580      default:
2581        newHoldingsWidth = gameInfo.holdingsSize = 0;
2582      };
2583
2584    if(newWidth  != gameInfo.boardWidth  ||
2585       newHeight != gameInfo.boardHeight ||
2586       newHoldingsWidth != gameInfo.holdingsWidth ) {
2587
2588      /* shift position to new playing area, if needed */
2589      if(newHoldingsWidth > gameInfo.holdingsWidth) {
2590        for(i=0; i<BOARD_HEIGHT; i++)
2591          for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2592            board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2593              board[i][j];
2594        for(i=0; i<newHeight; i++) {
2595          board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2596          board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2597        }
2598      } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2599        for(i=0; i<BOARD_HEIGHT; i++)
2600          for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2601            board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2602              board[i][j];
2603      }
2604      board[HOLDINGS_SET] = 0;
2605      gameInfo.boardWidth  = newWidth;
2606      gameInfo.boardHeight = newHeight;
2607      gameInfo.holdingsWidth = newHoldingsWidth;
2608      gameInfo.variant = newVariant;
2609      InitDrawingSizes(-2, 0);
2610    } else gameInfo.variant = newVariant;
2611    CopyBoard(oldBoard, board);   // remember correctly formatted board
2612      InitPosition(FALSE);          /* this sets up board[0], but also other stuff        */
2613    DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2614 }
2615
2616 static int loggedOn = FALSE;
2617
2618 /*-- Game start info cache: --*/
2619 int gs_gamenum;
2620 char gs_kind[MSG_SIZ];
2621 static char player1Name[128] = "";
2622 static char player2Name[128] = "";
2623 static char cont_seq[] = "\n\\   ";
2624 static int player1Rating = -1;
2625 static int player2Rating = -1;
2626 /*----------------------------*/
2627
2628 ColorClass curColor = ColorNormal;
2629 int suppressKibitz = 0;
2630
2631 // [HGM] seekgraph
2632 Boolean soughtPending = FALSE;
2633 Boolean seekGraphUp;
2634 #define MAX_SEEK_ADS 200
2635 #define SQUARE 0x80
2636 char *seekAdList[MAX_SEEK_ADS];
2637 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2638 float tcList[MAX_SEEK_ADS];
2639 char colorList[MAX_SEEK_ADS];
2640 int nrOfSeekAds = 0;
2641 int minRating = 1010, maxRating = 2800;
2642 int hMargin = 10, vMargin = 20, h, w;
2643 extern int squareSize, lineGap;
2644
2645 void
2646 PlotSeekAd (int i)
2647 {
2648         int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2649         xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2650         if(r < minRating+100 && r >=0 ) r = minRating+100;
2651         if(r > maxRating) r = maxRating;
2652         if(tc < 1.f) tc = 1.f;
2653         if(tc > 95.f) tc = 95.f;
2654         x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2655         y = ((double)r - minRating)/(maxRating - minRating)
2656             * (h-vMargin-squareSize/8-1) + vMargin;
2657         if(ratingList[i] < 0) y = vMargin + squareSize/4;
2658         if(strstr(seekAdList[i], " u ")) color = 1;
2659         if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2660            !strstr(seekAdList[i], "bullet") &&
2661            !strstr(seekAdList[i], "blitz") &&
2662            !strstr(seekAdList[i], "standard") ) color = 2;
2663         if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2664         DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2665 }
2666
2667 void
2668 PlotSingleSeekAd (int i)
2669 {
2670         PlotSeekAd(i);
2671 }
2672
2673 void
2674 AddAd (char *handle, char *rating, int base, int inc,  char rated, char *type, int nr, Boolean plot)
2675 {
2676         char buf[MSG_SIZ], *ext = "";
2677         VariantClass v = StringToVariant(type);
2678         if(strstr(type, "wild")) {
2679             ext = type + 4; // append wild number
2680             if(v == VariantFischeRandom) type = "chess960"; else
2681             if(v == VariantLoadable) type = "setup"; else
2682             type = VariantName(v);
2683         }
2684         snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2685         if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2686             if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2687             ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2688             sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2689             tcList[nrOfSeekAds] = base + (2./3.)*inc;
2690             seekNrList[nrOfSeekAds] = nr;
2691             zList[nrOfSeekAds] = 0;
2692             seekAdList[nrOfSeekAds++] = StrSave(buf);
2693             if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
2694         }
2695 }
2696
2697 void
2698 EraseSeekDot (int i)
2699 {
2700     int x = xList[i], y = yList[i], d=squareSize/4, k;
2701     DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2702     if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2703     // now replot every dot that overlapped
2704     for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2705         int xx = xList[k], yy = yList[k];
2706         if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2707             DrawSeekDot(xx, yy, colorList[k]);
2708     }
2709 }
2710
2711 void
2712 RemoveSeekAd (int nr)
2713 {
2714         int i;
2715         for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2716             EraseSeekDot(i);
2717             if(seekAdList[i]) free(seekAdList[i]);
2718             seekAdList[i] = seekAdList[--nrOfSeekAds];
2719             seekNrList[i] = seekNrList[nrOfSeekAds];
2720             ratingList[i] = ratingList[nrOfSeekAds];
2721             colorList[i]  = colorList[nrOfSeekAds];
2722             tcList[i] = tcList[nrOfSeekAds];
2723             xList[i]  = xList[nrOfSeekAds];
2724             yList[i]  = yList[nrOfSeekAds];
2725             zList[i]  = zList[nrOfSeekAds];
2726             seekAdList[nrOfSeekAds] = NULL;
2727             break;
2728         }
2729 }
2730
2731 Boolean
2732 MatchSoughtLine (char *line)
2733 {
2734     char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2735     int nr, base, inc, u=0; char dummy;
2736
2737     if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2738        sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2739        (u=1) &&
2740        (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2741         sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7)  ) {
2742         // match: compact and save the line
2743         AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2744         return TRUE;
2745     }
2746     return FALSE;
2747 }
2748
2749 int
2750 DrawSeekGraph ()
2751 {
2752     int i;
2753     if(!seekGraphUp) return FALSE;
2754     h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap + 2*border;
2755     w = BOARD_WIDTH  * (squareSize + lineGap) + lineGap + 2*border;
2756
2757     DrawSeekBackground(0, 0, w, h);
2758     DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2759     DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2760     for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2761         int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2762         yy = h-1-yy;
2763         DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
2764         if(i%500 == 0) {
2765             char buf[MSG_SIZ];
2766             snprintf(buf, MSG_SIZ, "%d", i);
2767             DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2768         }
2769     }
2770     DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2771     for(i=1; i<100; i+=(i<10?1:5)) {
2772         int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2773         DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2774         if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2775             char buf[MSG_SIZ];
2776             snprintf(buf, MSG_SIZ, "%d", i);
2777             DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2778         }
2779     }
2780     for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2781     return TRUE;
2782 }
2783
2784 int
2785 SeekGraphClick (ClickType click, int x, int y, int moving)
2786 {
2787     static int lastDown = 0, displayed = 0, lastSecond;
2788     if(y < 0) return FALSE;
2789     if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2790         (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2791         if(!seekGraphUp) return FALSE;
2792         seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2793         DrawPosition(TRUE, NULL);
2794         return TRUE;
2795     }
2796     if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2797         if(click == Release || moving) return FALSE;
2798         nrOfSeekAds = 0;
2799         soughtPending = TRUE;
2800         SendToICS(ics_prefix);
2801         SendToICS("sought\n"); // should this be "sought all"?
2802     } else { // issue challenge based on clicked ad
2803         int dist = 10000; int i, closest = 0, second = 0;
2804         for(i=0; i<nrOfSeekAds; i++) {
2805             int d = (x-xList[i])*(x-xList[i]) +  (y-yList[i])*(y-yList[i]) + zList[i];
2806             if(d < dist) { dist = d; closest = i; }
2807             second += (d - zList[i] < 120); // count in-range ads
2808             if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2809         }
2810         if(dist < 120) {
2811             char buf[MSG_SIZ];
2812             second = (second > 1);
2813             if(displayed != closest || second != lastSecond) {
2814                 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2815                 lastSecond = second; displayed = closest;
2816             }
2817             if(click == Press) {
2818                 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2819                 lastDown = closest;
2820                 return TRUE;
2821             } // on press 'hit', only show info
2822             if(moving == 2) return TRUE; // ignore right up-clicks on dot
2823             snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2824             SendToICS(ics_prefix);
2825             SendToICS(buf);
2826             return TRUE; // let incoming board of started game pop down the graph
2827         } else if(click == Release) { // release 'miss' is ignored
2828             zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2829             if(moving == 2) { // right up-click
2830                 nrOfSeekAds = 0; // refresh graph
2831                 soughtPending = TRUE;
2832                 SendToICS(ics_prefix);
2833                 SendToICS("sought\n"); // should this be "sought all"?
2834             }
2835             return TRUE;
2836         } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2837         // press miss or release hit 'pop down' seek graph
2838         seekGraphUp = FALSE;
2839         DrawPosition(TRUE, NULL);
2840     }
2841     return TRUE;
2842 }
2843
2844 void
2845 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2846 {
2847 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2848 #define STARTED_NONE 0
2849 #define STARTED_MOVES 1
2850 #define STARTED_BOARD 2
2851 #define STARTED_OBSERVE 3
2852 #define STARTED_HOLDINGS 4
2853 #define STARTED_CHATTER 5
2854 #define STARTED_COMMENT 6
2855 #define STARTED_MOVES_NOHIDE 7
2856
2857     static int started = STARTED_NONE;
2858     static char parse[20000];
2859     static int parse_pos = 0;
2860     static char buf[BUF_SIZE + 1];
2861     static int firstTime = TRUE, intfSet = FALSE;
2862     static ColorClass prevColor = ColorNormal;
2863     static int savingComment = FALSE;
2864     static int cmatch = 0; // continuation sequence match
2865     char *bp;
2866     char str[MSG_SIZ];
2867     int i, oldi;
2868     int buf_len;
2869     int next_out;
2870     int tkind;
2871     int backup;    /* [DM] For zippy color lines */
2872     char *p;
2873     char talker[MSG_SIZ]; // [HGM] chat
2874     int channel, collective=0;
2875
2876     connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2877
2878     if (appData.debugMode) {
2879       if (!error) {
2880         fprintf(debugFP, "<ICS: ");
2881         show_bytes(debugFP, data, count);
2882         fprintf(debugFP, "\n");
2883       }
2884     }
2885
2886     if (appData.debugMode) { int f = forwardMostMove;
2887         fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2888                 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2889                 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2890     }
2891     if (count > 0) {
2892         /* If last read ended with a partial line that we couldn't parse,
2893            prepend it to the new read and try again. */
2894         if (leftover_len > 0) {
2895             for (i=0; i<leftover_len; i++)
2896               buf[i] = buf[leftover_start + i];
2897         }
2898
2899     /* copy new characters into the buffer */
2900     bp = buf + leftover_len;
2901     buf_len=leftover_len;
2902     for (i=0; i<count; i++)
2903     {
2904         // ignore these
2905         if (data[i] == '\r')
2906             continue;
2907
2908         // join lines split by ICS?
2909         if (!appData.noJoin)
2910         {
2911             /*
2912                 Joining just consists of finding matches against the
2913                 continuation sequence, and discarding that sequence
2914                 if found instead of copying it.  So, until a match
2915                 fails, there's nothing to do since it might be the
2916                 complete sequence, and thus, something we don't want
2917                 copied.
2918             */
2919             if (data[i] == cont_seq[cmatch])
2920             {
2921                 cmatch++;
2922                 if (cmatch == strlen(cont_seq))
2923                 {
2924                     cmatch = 0; // complete match.  just reset the counter
2925
2926                     /*
2927                         it's possible for the ICS to not include the space
2928                         at the end of the last word, making our [correct]
2929                         join operation fuse two separate words.  the server
2930                         does this when the space occurs at the width setting.
2931                     */
2932                     if (!buf_len || buf[buf_len-1] != ' ')
2933                     {
2934                         *bp++ = ' ';
2935                         buf_len++;
2936                     }
2937                 }
2938                 continue;
2939             }
2940             else if (cmatch)
2941             {
2942                 /*
2943                     match failed, so we have to copy what matched before
2944                     falling through and copying this character.  In reality,
2945                     this will only ever be just the newline character, but
2946                     it doesn't hurt to be precise.
2947                 */
2948                 strncpy(bp, cont_seq, cmatch);
2949                 bp += cmatch;
2950                 buf_len += cmatch;
2951                 cmatch = 0;
2952             }
2953         }
2954
2955         // copy this char
2956         *bp++ = data[i];
2957         buf_len++;
2958     }
2959
2960         buf[buf_len] = NULLCHAR;
2961 //      next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2962         next_out = 0;
2963         leftover_start = 0;
2964
2965         i = 0;
2966         while (i < buf_len) {
2967             /* Deal with part of the TELNET option negotiation
2968                protocol.  We refuse to do anything beyond the
2969                defaults, except that we allow the WILL ECHO option,
2970                which ICS uses to turn off password echoing when we are
2971                directly connected to it.  We reject this option
2972                if localLineEditing mode is on (always on in xboard)
2973                and we are talking to port 23, which might be a real
2974                telnet server that will try to keep WILL ECHO on permanently.
2975              */
2976             if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2977                 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2978                 unsigned char option;
2979                 oldi = i;
2980                 switch ((unsigned char) buf[++i]) {
2981                   case TN_WILL:
2982                     if (appData.debugMode)
2983                       fprintf(debugFP, "\n<WILL ");
2984                     switch (option = (unsigned char) buf[++i]) {
2985                       case TN_ECHO:
2986                         if (appData.debugMode)
2987                           fprintf(debugFP, "ECHO ");
2988                         /* Reply only if this is a change, according
2989                            to the protocol rules. */
2990                         if (remoteEchoOption) break;
2991                         if (appData.localLineEditing &&
2992                             atoi(appData.icsPort) == TN_PORT) {
2993                             TelnetRequest(TN_DONT, TN_ECHO);
2994                         } else {
2995                             EchoOff();
2996                             TelnetRequest(TN_DO, TN_ECHO);
2997                             remoteEchoOption = TRUE;
2998                         }
2999                         break;
3000                       default:
3001                         if (appData.debugMode)
3002                           fprintf(debugFP, "%d ", option);
3003                         /* Whatever this is, we don't want it. */
3004                         TelnetRequest(TN_DONT, option);
3005                         break;
3006                     }
3007                     break;
3008                   case TN_WONT:
3009                     if (appData.debugMode)
3010                       fprintf(debugFP, "\n<WONT ");
3011                     switch (option = (unsigned char) buf[++i]) {
3012                       case TN_ECHO:
3013                         if (appData.debugMode)
3014                           fprintf(debugFP, "ECHO ");
3015                         /* Reply only if this is a change, according
3016                            to the protocol rules. */
3017                         if (!remoteEchoOption) break;
3018                         EchoOn();
3019                         TelnetRequest(TN_DONT, TN_ECHO);
3020                         remoteEchoOption = FALSE;
3021                         break;
3022                       default:
3023                         if (appData.debugMode)
3024                           fprintf(debugFP, "%d ", (unsigned char) option);
3025                         /* Whatever this is, it must already be turned
3026                            off, because we never agree to turn on
3027                            anything non-default, so according to the
3028                            protocol rules, we don't reply. */
3029                         break;
3030                     }
3031                     break;
3032                   case TN_DO:
3033                     if (appData.debugMode)
3034                       fprintf(debugFP, "\n<DO ");
3035                     switch (option = (unsigned char) buf[++i]) {
3036                       default:
3037                         /* Whatever this is, we refuse to do it. */
3038                         if (appData.debugMode)
3039                           fprintf(debugFP, "%d ", option);
3040                         TelnetRequest(TN_WONT, option);
3041                         break;
3042                     }
3043                     break;
3044                   case TN_DONT:
3045                     if (appData.debugMode)
3046                       fprintf(debugFP, "\n<DONT ");
3047                     switch (option = (unsigned char) buf[++i]) {
3048                       default:
3049                         if (appData.debugMode)
3050                           fprintf(debugFP, "%d ", option);
3051                         /* Whatever this is, we are already not doing
3052                            it, because we never agree to do anything
3053                            non-default, so according to the protocol
3054                            rules, we don't reply. */
3055                         break;
3056                     }
3057                     break;
3058                   case TN_IAC:
3059                     if (appData.debugMode)
3060                       fprintf(debugFP, "\n<IAC ");
3061                     /* Doubled IAC; pass it through */
3062                     i--;
3063                     break;
3064                   default:
3065                     if (appData.debugMode)
3066                       fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
3067                     /* Drop all other telnet commands on the floor */
3068                     break;
3069                 }
3070                 if (oldi > next_out)
3071                   SendToPlayer(&buf[next_out], oldi - next_out);
3072                 if (++i > next_out)
3073                   next_out = i;
3074                 continue;
3075             }
3076
3077             /* OK, this at least will *usually* work */
3078             if (!loggedOn && looking_at(buf, &i, "ics%")) {
3079                 loggedOn = TRUE;
3080             }
3081
3082             if (loggedOn && !intfSet) {
3083                 if (ics_type == ICS_ICC) {
3084                   snprintf(str, MSG_SIZ,
3085                           "/set-quietly interface %s\n/set-quietly style 12\n",
3086                           programVersion);
3087                   if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3088                       strcat(str, "/set-2 51 1\n/set seek 1\n");
3089                 } else if (ics_type == ICS_CHESSNET) {
3090                   snprintf(str, MSG_SIZ, "/style 12\n");
3091                 } else {
3092                   safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
3093                   strcat(str, programVersion);
3094                   strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
3095                   if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3096                       strcat(str, "$iset seekremove 1\n$set seek 1\n");
3097 #ifdef WIN32
3098                   strcat(str, "$iset nohighlight 1\n");
3099 #endif
3100                   strcat(str, "$iset lock 1\n$style 12\n");
3101                 }
3102                 SendToICS(str);
3103                 NotifyFrontendLogin();
3104                 intfSet = TRUE;
3105             }
3106
3107             if (started == STARTED_COMMENT) {
3108                 /* Accumulate characters in comment */
3109                 parse[parse_pos++] = buf[i];
3110                 if (buf[i] == '\n') {
3111                     parse[parse_pos] = NULLCHAR;
3112                     if(chattingPartner>=0) {
3113                         char mess[MSG_SIZ];
3114                         snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
3115                         OutputChatMessage(chattingPartner, mess);
3116                         if(collective == 1) { // broadcasted talk also goes to private chatbox of talker
3117                             int p;
3118                             talker[strlen(talker+1)-1] = NULLCHAR; // strip closing delimiter
3119                             for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3120                                 snprintf(mess, MSG_SIZ, "%s: %s", chatPartner[chattingPartner], parse);
3121                                 OutputChatMessage(p, mess);
3122                                 break;
3123                             }
3124                         }
3125                         chattingPartner = -1;
3126                         if(collective != 3) next_out = i+1; // [HGM] suppress printing in ICS window
3127                         collective = 0;
3128                     } else
3129                     if(!suppressKibitz) // [HGM] kibitz
3130                         AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
3131                     else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
3132                         int nrDigit = 0, nrAlph = 0, j;
3133                         if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
3134                         { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
3135                         parse[parse_pos] = NULLCHAR;
3136                         // try to be smart: if it does not look like search info, it should go to
3137                         // ICS interaction window after all, not to engine-output window.
3138                         for(j=0; j<parse_pos; j++) { // count letters and digits
3139                             nrDigit += (parse[j] >= '0' && parse[j] <= '9');
3140                             nrAlph  += (parse[j] >= 'a' && parse[j] <= 'z');
3141                             nrAlph  += (parse[j] >= 'A' && parse[j] <= 'Z');
3142                         }
3143                         if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
3144                             int depth=0; float score;
3145                             if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
3146                                 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
3147                                 pvInfoList[forwardMostMove-1].depth = depth;
3148                                 pvInfoList[forwardMostMove-1].score = 100*score;
3149                             }
3150                             OutputKibitz(suppressKibitz, parse);
3151                         } else {
3152                             char tmp[MSG_SIZ];
3153                             if(gameMode == IcsObserving) // restore original ICS messages
3154                               /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3155                               snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
3156                             else
3157                             /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3158                             snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
3159                             SendToPlayer(tmp, strlen(tmp));
3160                         }
3161                         next_out = i+1; // [HGM] suppress printing in ICS window
3162                     }
3163                     started = STARTED_NONE;
3164                 } else {
3165                     /* Don't match patterns against characters in comment */
3166                     i++;
3167                     continue;
3168                 }
3169             }
3170             if (started == STARTED_CHATTER) {
3171                 if (buf[i] != '\n') {
3172                     /* Don't match patterns against characters in chatter */
3173                     i++;
3174                     continue;
3175                 }
3176                 started = STARTED_NONE;
3177                 if(suppressKibitz) next_out = i+1;
3178             }
3179
3180             /* Kludge to deal with rcmd protocol */
3181             if (firstTime && looking_at(buf, &i, "\001*")) {
3182                 DisplayFatalError(&buf[1], 0, 1);
3183                 continue;
3184             } else {
3185                 firstTime = FALSE;
3186             }
3187
3188             if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3189                 ics_type = ICS_ICC;
3190                 ics_prefix = "/";
3191                 if (appData.debugMode)
3192                   fprintf(debugFP, "ics_type %d\n", ics_type);
3193                 continue;
3194             }
3195             if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3196                 ics_type = ICS_FICS;
3197                 ics_prefix = "$";
3198                 if (appData.debugMode)
3199                   fprintf(debugFP, "ics_type %d\n", ics_type);
3200                 continue;
3201             }
3202             if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3203                 ics_type = ICS_CHESSNET;
3204                 ics_prefix = "/";
3205                 if (appData.debugMode)
3206                   fprintf(debugFP, "ics_type %d\n", ics_type);
3207                 continue;
3208             }
3209
3210             if (!loggedOn &&
3211                 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3212                  looking_at(buf, &i, "Logging you in as \"*\"") ||
3213                  looking_at(buf, &i, "will be \"*\""))) {
3214               safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3215               continue;
3216             }
3217
3218             if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3219               char buf[MSG_SIZ];
3220               snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3221               DisplayIcsInteractionTitle(buf);
3222               have_set_title = TRUE;
3223             }
3224
3225             /* skip finger notes */
3226             if (started == STARTED_NONE &&
3227                 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3228                  (buf[i] == '1' && buf[i+1] == '0')) &&
3229                 buf[i+2] == ':' && buf[i+3] == ' ') {
3230               started = STARTED_CHATTER;
3231               i += 3;
3232               continue;
3233             }
3234
3235             oldi = i;
3236             // [HGM] seekgraph: recognize sought lines and end-of-sought message
3237             if(appData.seekGraph) {
3238                 if(soughtPending && MatchSoughtLine(buf+i)) {
3239                     i = strstr(buf+i, "rated") - buf;
3240                     if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3241                     next_out = leftover_start = i;
3242                     started = STARTED_CHATTER;
3243                     suppressKibitz = TRUE;
3244                     continue;
3245                 }
3246                 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3247                         && looking_at(buf, &i, "* ads displayed")) {
3248                     soughtPending = FALSE;
3249                     seekGraphUp = TRUE;
3250                     DrawSeekGraph();
3251                     continue;
3252                 }
3253                 if(appData.autoRefresh) {
3254                     if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3255                         int s = (ics_type == ICS_ICC); // ICC format differs
3256                         if(seekGraphUp)
3257                         AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3258                               star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3259                         looking_at(buf, &i, "*% "); // eat prompt
3260                         if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3261                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3262                         next_out = i; // suppress
3263                         continue;
3264                     }
3265                     if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3266                         char *p = star_match[0];
3267                         while(*p) {
3268                             if(seekGraphUp) RemoveSeekAd(atoi(p));
3269                             while(*p && *p++ != ' '); // next
3270                         }
3271                         looking_at(buf, &i, "*% "); // eat prompt
3272                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3273                         next_out = i;
3274                         continue;
3275                     }
3276                 }
3277             }
3278
3279             /* skip formula vars */
3280             if (started == STARTED_NONE &&
3281                 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3282               started = STARTED_CHATTER;
3283               i += 3;
3284               continue;
3285             }
3286
3287             // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3288             if (appData.autoKibitz && started == STARTED_NONE &&
3289                 !appData.icsEngineAnalyze &&                     // [HGM] [DM] ICS analyze
3290                 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3291                 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3292                     looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3293                    (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3294                     StrStr(star_match[0], gameInfo.black) == star_match[0]   )) { // kibitz of self or opponent
3295                         suppressKibitz = TRUE;
3296                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3297                         next_out = i;
3298                         if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3299                                 && (gameMode == IcsPlayingWhite)) ||
3300                            (StrStr(star_match[0], gameInfo.black) == star_match[0]
3301                                 && (gameMode == IcsPlayingBlack))   ) // opponent kibitz
3302                             started = STARTED_CHATTER; // own kibitz we simply discard
3303                         else {
3304                             started = STARTED_COMMENT; // make sure it will be collected in parse[]
3305                             parse_pos = 0; parse[0] = NULLCHAR;
3306                             savingComment = TRUE;
3307                             suppressKibitz = gameMode != IcsObserving ? 2 :
3308                                 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3309                         }
3310                         continue;
3311                 } else
3312                 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3313                     looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3314                          && atoi(star_match[0])) {
3315                     // suppress the acknowledgements of our own autoKibitz
3316                     char *p;
3317                     if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3318                     if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3319                     SendToPlayer(star_match[0], strlen(star_match[0]));
3320                     if(looking_at(buf, &i, "*% ")) // eat prompt
3321                         suppressKibitz = FALSE;
3322                     next_out = i;
3323                     continue;
3324                 }
3325             } // [HGM] kibitz: end of patch
3326
3327             if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3328
3329             // [HGM] chat: intercept tells by users for which we have an open chat window
3330             channel = -1;
3331             if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3332                                            looking_at(buf, &i, "* whispers:") ||
3333                                            looking_at(buf, &i, "* kibitzes:") ||
3334                                            looking_at(buf, &i, "* shouts:") ||
3335                                            looking_at(buf, &i, "* c-shouts:") ||
3336                                            looking_at(buf, &i, "--> * ") ||
3337                                            looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3338                                            looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3339                                            looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3340                                            looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3341                 int p;
3342                 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3343                 chattingPartner = -1; collective = 0;
3344
3345                 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3346                 for(p=0; p<MAX_CHAT; p++) {
3347                     collective = 1;
3348                     if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3349                     talker[0] = '['; strcat(talker, "] ");
3350                     Colorize((channel == 1 ? ColorChannel1 : ColorChannel), FALSE);
3351                     chattingPartner = p; break;
3352                     }
3353                 } else
3354                 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3355                 for(p=0; p<MAX_CHAT; p++) {
3356                     collective = 1;
3357                     if(!strcmp("kibitzes", chatPartner[p])) {
3358                         talker[0] = '['; strcat(talker, "] ");
3359                         chattingPartner = p; break;
3360                     }
3361                 } else
3362                 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3363                 for(p=0; p<MAX_CHAT; p++) {
3364                     collective = 1;
3365                     if(!strcmp("whispers", chatPartner[p])) {
3366                         talker[0] = '['; strcat(talker, "] ");
3367                         chattingPartner = p; break;
3368                     }
3369                 } else
3370                 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3371                   if(buf[i-8] == '-' && buf[i-3] == 't')
3372                   for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3373                     collective = 1;
3374                     if(!strcmp("c-shouts", chatPartner[p])) {
3375                         talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3376                         chattingPartner = p; break;
3377                     }
3378                   }
3379                   if(chattingPartner < 0)
3380                   for(p=0; p<MAX_CHAT; p++) {
3381                     collective = 1;
3382                     if(!strcmp("shouts", chatPartner[p])) {
3383                         if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3384                         else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3385                         else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3386                         chattingPartner = p; break;
3387                     }
3388                   }
3389                 }
3390                 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3391                 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3392                     talker[0] = 0;
3393                     Colorize(ColorTell, FALSE);
3394                     if(collective) safeStrCpy(talker, "broadcasts: ", MSG_SIZ);
3395                     collective |= 2;
3396                     chattingPartner = p; break;
3397                 }
3398                 if(chattingPartner<0) i = oldi, safeStrCpy(lastTalker, talker+1, MSG_SIZ); else {
3399                     Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3400                     started = STARTED_COMMENT;
3401                     parse_pos = 0; parse[0] = NULLCHAR;
3402                     savingComment = 3 + chattingPartner; // counts as TRUE
3403                     if(collective == 3) i = oldi; else {
3404                         suppressKibitz = TRUE;
3405                         if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3406                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3407                         continue;
3408                     }
3409                 }
3410             } // [HGM] chat: end of patch
3411
3412           backup = i;
3413             if (appData.zippyTalk || appData.zippyPlay) {
3414                 /* [DM] Backup address for color zippy lines */
3415 #if ZIPPY
3416                if (loggedOn == TRUE)
3417                        if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3418                           (appData.zippyPlay && ZippyMatch(buf, &backup)))
3419                        ;
3420 #endif
3421             } // [DM] 'else { ' deleted
3422                 if (
3423                     /* Regular tells and says */
3424                     (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3425                     looking_at(buf, &i, "* (your partner) tells you: ") ||
3426                     looking_at(buf, &i, "* says: ") ||
3427                     /* Don't color "message" or "messages" output */
3428                     (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3429                     looking_at(buf, &i, "*. * at *:*: ") ||
3430                     looking_at(buf, &i, "--* (*:*): ") ||
3431                     /* Message notifications (same color as tells) */
3432                     looking_at(buf, &i, "* has left a message ") ||
3433                     looking_at(buf, &i, "* just sent you a message:\n") ||
3434                     /* Whispers and kibitzes */
3435                     (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3436                     looking_at(buf, &i, "* kibitzes: ") ||
3437                     /* Channel tells */
3438                     (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3439
3440                   if (tkind == 1 && strchr(star_match[0], ':')) {
3441                       /* Avoid "tells you:" spoofs in channels */
3442                      tkind = 3;
3443                   }
3444                   if (star_match[0][0] == NULLCHAR ||
3445                       strchr(star_match[0], ' ') ||
3446                       (tkind == 3 && strchr(star_match[1], ' '))) {
3447                     /* Reject bogus matches */
3448                     i = oldi;
3449                   } else {
3450                     if (appData.colorize) {
3451                       if (oldi > next_out) {
3452                         SendToPlayer(&buf[next_out], oldi - next_out);
3453                         next_out = oldi;
3454                       }
3455                       switch (tkind) {
3456                       case 1:
3457                         Colorize(ColorTell, FALSE);
3458                         curColor = ColorTell;
3459                         break;
3460                       case 2:
3461                         Colorize(ColorKibitz, FALSE);
3462                         curColor = ColorKibitz;
3463                         break;
3464                       case 3:
3465                         p = strrchr(star_match[1], '(');
3466                         if (p == NULL) {
3467                           p = star_match[1];
3468                         } else {
3469                           p++;
3470                         }
3471                         if (atoi(p) == 1) {
3472                           Colorize(ColorChannel1, FALSE);
3473                           curColor = ColorChannel1;
3474                         } else {
3475                           Colorize(ColorChannel, FALSE);
3476                           curColor = ColorChannel;
3477                         }
3478                         break;
3479                       case 5:
3480                         curColor = ColorNormal;
3481                         break;
3482                       }
3483                     }
3484                     if (started == STARTED_NONE && appData.autoComment &&
3485                         (gameMode == IcsObserving ||
3486                          gameMode == IcsPlayingWhite ||
3487                          gameMode == IcsPlayingBlack)) {
3488                       parse_pos = i - oldi;
3489                       memcpy(parse, &buf[oldi], parse_pos);
3490                       parse[parse_pos] = NULLCHAR;
3491                       started = STARTED_COMMENT;
3492                       savingComment = TRUE;
3493                     } else if(collective != 3) {
3494                       started = STARTED_CHATTER;
3495                       savingComment = FALSE;
3496                     }
3497                     loggedOn = TRUE;
3498                     continue;
3499                   }
3500                 }
3501
3502                 if (looking_at(buf, &i, "* s-shouts: ") ||
3503                     looking_at(buf, &i, "* c-shouts: ")) {
3504                     if (appData.colorize) {
3505                         if (oldi > next_out) {
3506                             SendToPlayer(&buf[next_out], oldi - next_out);
3507                             next_out = oldi;
3508                         }
3509                         Colorize(ColorSShout, FALSE);
3510                         curColor = ColorSShout;
3511                     }
3512                     loggedOn = TRUE;
3513                     started = STARTED_CHATTER;
3514                     continue;
3515                 }
3516
3517                 if (looking_at(buf, &i, "--->")) {
3518                     loggedOn = TRUE;
3519                     continue;
3520                 }
3521
3522                 if (looking_at(buf, &i, "* shouts: ") ||
3523                     looking_at(buf, &i, "--> ")) {
3524                     if (appData.colorize) {
3525                         if (oldi > next_out) {
3526                             SendToPlayer(&buf[next_out], oldi - next_out);
3527                             next_out = oldi;
3528                         }
3529                         Colorize(ColorShout, FALSE);
3530                         curColor = ColorShout;
3531                     }
3532                     loggedOn = TRUE;
3533                     started = STARTED_CHATTER;
3534                     continue;
3535                 }
3536
3537                 if (looking_at( buf, &i, "Challenge:")) {
3538                     if (appData.colorize) {
3539                         if (oldi > next_out) {
3540                             SendToPlayer(&buf[next_out], oldi - next_out);
3541                             next_out = oldi;
3542                         }
3543                         Colorize(ColorChallenge, FALSE);
3544                         curColor = ColorChallenge;
3545                     }
3546                     loggedOn = TRUE;
3547                     continue;
3548                 }
3549
3550                 if (looking_at(buf, &i, "* offers you") ||
3551                     looking_at(buf, &i, "* offers to be") ||
3552                     looking_at(buf, &i, "* would like to") ||
3553                     looking_at(buf, &i, "* requests to") ||
3554                     looking_at(buf, &i, "Your opponent offers") ||
3555                     looking_at(buf, &i, "Your opponent requests")) {
3556
3557                     if (appData.colorize) {
3558                         if (oldi > next_out) {
3559                             SendToPlayer(&buf[next_out], oldi - next_out);
3560                             next_out = oldi;
3561                         }
3562                         Colorize(ColorRequest, FALSE);
3563                         curColor = ColorRequest;
3564                     }
3565                     continue;
3566                 }
3567
3568                 if (looking_at(buf, &i, "* (*) seeking")) {
3569                     if (appData.colorize) {
3570                         if (oldi > next_out) {
3571                             SendToPlayer(&buf[next_out], oldi - next_out);
3572                             next_out = oldi;
3573                         }
3574                         Colorize(ColorSeek, FALSE);
3575                         curColor = ColorSeek;
3576                     }
3577                     continue;
3578             }
3579
3580           if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3581
3582             if (looking_at(buf, &i, "\\   ")) {
3583                 if (prevColor != ColorNormal) {
3584                     if (oldi > next_out) {
3585                         SendToPlayer(&buf[next_out], oldi - next_out);
3586                         next_out = oldi;
3587                     }
3588                     Colorize(prevColor, TRUE);
3589                     curColor = prevColor;
3590                 }
3591                 if (savingComment) {
3592                     parse_pos = i - oldi;
3593                     memcpy(parse, &buf[oldi], parse_pos);
3594                     parse[parse_pos] = NULLCHAR;
3595                     started = STARTED_COMMENT;
3596                     if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3597                         chattingPartner = savingComment - 3; // kludge to remember the box
3598                 } else {
3599                     started = STARTED_CHATTER;
3600                 }
3601                 continue;
3602             }
3603
3604             if (looking_at(buf, &i, "Black Strength :") ||
3605                 looking_at(buf, &i, "<<< style 10 board >>>") ||
3606                 looking_at(buf, &i, "<10>") ||
3607                 looking_at(buf, &i, "#@#")) {
3608                 /* Wrong board style */
3609                 loggedOn = TRUE;
3610                 SendToICS(ics_prefix);
3611                 SendToICS("set style 12\n");
3612                 SendToICS(ics_prefix);
3613                 SendToICS("refresh\n");
3614                 continue;
3615             }
3616
3617             if (looking_at(buf, &i, "login:")) {
3618               if (!have_sent_ICS_logon) {
3619                 if(ICSInitScript())
3620                   have_sent_ICS_logon = 1;
3621                 else // no init script was found
3622                   have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
3623               } else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
3624                   have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
3625               }
3626                 continue;
3627             }
3628
3629             if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3630                 (looking_at(buf, &i, "\n<12> ") ||
3631                  looking_at(buf, &i, "<12> "))) {
3632                 loggedOn = TRUE;
3633                 if (oldi > next_out) {
3634                     SendToPlayer(&buf[next_out], oldi - next_out);
3635                 }
3636                 next_out = i;
3637                 started = STARTED_BOARD;
3638                 parse_pos = 0;
3639                 continue;
3640             }
3641
3642             if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3643                 looking_at(buf, &i, "<b1> ")) {
3644                 if (oldi > next_out) {
3645                     SendToPlayer(&buf[next_out], oldi - next_out);
3646                 }
3647                 next_out = i;
3648                 started = STARTED_HOLDINGS;
3649                 parse_pos = 0;
3650                 continue;
3651             }
3652
3653             if (looking_at(buf, &i, "* *vs. * *--- *")) {
3654                 loggedOn = TRUE;
3655                 /* Header for a move list -- first line */
3656
3657                 switch (ics_getting_history) {
3658                   case H_FALSE:
3659                     switch (gameMode) {
3660                       case IcsIdle:
3661                       case BeginningOfGame:
3662                         /* User typed "moves" or "oldmoves" while we
3663                            were idle.  Pretend we asked for these
3664                            moves and soak them up so user can step
3665                            through them and/or save them.
3666                            */
3667                         Reset(FALSE, TRUE);
3668                         gameMode = IcsObserving;
3669                         ModeHighlight();
3670                         ics_gamenum = -1;
3671                         ics_getting_history = H_GOT_UNREQ_HEADER;
3672                         break;
3673                       case EditGame: /*?*/
3674                       case EditPosition: /*?*/
3675                         /* Should above feature work in these modes too? */
3676                         /* For now it doesn't */
3677                         ics_getting_history = H_GOT_UNWANTED_HEADER;
3678                         break;
3679                       default:
3680                         ics_getting_history = H_GOT_UNWANTED_HEADER;
3681                         break;
3682                     }
3683                     break;
3684                   case H_REQUESTED:
3685                     /* Is this the right one? */
3686                     if (gameInfo.white && gameInfo.black &&
3687                         strcmp(gameInfo.white, star_match[0]) == 0 &&
3688                         strcmp(gameInfo.black, star_match[2]) == 0) {
3689                         /* All is well */
3690                         ics_getting_history = H_GOT_REQ_HEADER;
3691                     }
3692                     break;
3693                   case H_GOT_REQ_HEADER:
3694                   case H_GOT_UNREQ_HEADER:
3695                   case H_GOT_UNWANTED_HEADER:
3696                   case H_GETTING_MOVES:
3697                     /* Should not happen */
3698                     DisplayError(_("Error gathering move list: two headers"), 0);
3699                     ics_getting_history = H_FALSE;
3700                     break;
3701                 }
3702
3703                 /* Save player ratings into gameInfo if needed */
3704                 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3705                      ics_getting_history == H_GOT_UNREQ_HEADER) &&
3706                     (gameInfo.whiteRating == -1 ||
3707                      gameInfo.blackRating == -1)) {
3708
3709                     gameInfo.whiteRating = string_to_rating(star_match[1]);
3710                     gameInfo.blackRating = string_to_rating(star_match[3]);
3711                     if (appData.debugMode)
3712                       fprintf(debugFP, "Ratings from header: W %d, B %d\n",
3713                               gameInfo.whiteRating, gameInfo.blackRating);
3714                 }
3715                 continue;
3716             }
3717
3718             if (looking_at(buf, &i,
3719               "* * match, initial time: * minute*, increment: * second")) {
3720                 /* Header for a move list -- second line */
3721                 /* Initial board will follow if this is a wild game */
3722                 if (gameInfo.event != NULL) free(gameInfo.event);
3723                 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3724                 gameInfo.event = StrSave(str);
3725                 /* [HGM] we switched variant. Translate boards if needed. */
3726                 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3727                 continue;
3728             }
3729
3730             if (looking_at(buf, &i, "Move  ")) {
3731                 /* Beginning of a move list */
3732                 switch (ics_getting_history) {
3733                   case H_FALSE:
3734                     /* Normally should not happen */
3735                     /* Maybe user hit reset while we were parsing */
3736                     break;
3737                   case H_REQUESTED:
3738                     /* Happens if we are ignoring a move list that is not
3739                      * the one we just requested.  Common if the user
3740                      * tries to observe two games without turning off
3741                      * getMoveList */
3742                     break;
3743                   case H_GETTING_MOVES:
3744                     /* Should not happen */
3745                     DisplayError(_("Error gathering move list: nested"), 0);
3746                     ics_getting_history = H_FALSE;
3747                     break;
3748                   case H_GOT_REQ_HEADER:
3749                     ics_getting_history = H_GETTING_MOVES;
3750                     started = STARTED_MOVES;
3751                     parse_pos = 0;
3752                     if (oldi > next_out) {
3753                         SendToPlayer(&buf[next_out], oldi - next_out);
3754                     }
3755                     break;
3756                   case H_GOT_UNREQ_HEADER:
3757                     ics_getting_history = H_GETTING_MOVES;
3758                     started = STARTED_MOVES_NOHIDE;
3759                     parse_pos = 0;
3760                     break;
3761                   case H_GOT_UNWANTED_HEADER:
3762                     ics_getting_history = H_FALSE;
3763                     break;
3764                 }
3765                 continue;
3766             }
3767
3768             if (looking_at(buf, &i, "% ") ||
3769                 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3770                  && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3771                 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3772                     soughtPending = FALSE;
3773                     seekGraphUp = TRUE;
3774                     DrawSeekGraph();
3775                 }
3776                 if(suppressKibitz) next_out = i;
3777                 savingComment = FALSE;
3778                 suppressKibitz = 0;
3779                 switch (started) {
3780                   case STARTED_MOVES:
3781                   case STARTED_MOVES_NOHIDE:
3782                     memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3783                     parse[parse_pos + i - oldi] = NULLCHAR;
3784                     ParseGameHistory(parse);
3785 #if ZIPPY
3786                     if (appData.zippyPlay && first.initDone) {
3787                         FeedMovesToProgram(&first, forwardMostMove);
3788                         if (gameMode == IcsPlayingWhite) {
3789                             if (WhiteOnMove(forwardMostMove)) {
3790                                 if (first.sendTime) {
3791                                   if (first.useColors) {
3792                                     SendToProgram("black\n", &first);
3793                                   }
3794                                   SendTimeRemaining(&first, TRUE);
3795                                 }
3796                                 if (first.useColors) {
3797                                   SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3798                                 }
3799                                 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3800                                 first.maybeThinking = TRUE;
3801                             } else {
3802                                 if (first.usePlayother) {
3803                                   if (first.sendTime) {
3804                                     SendTimeRemaining(&first, TRUE);
3805                                   }
3806                                   SendToProgram("playother\n", &first);
3807                                   firstMove = FALSE;
3808                                 } else {
3809                                   firstMove = TRUE;
3810                                 }
3811                             }
3812                         } else if (gameMode == IcsPlayingBlack) {
3813                             if (!WhiteOnMove(forwardMostMove)) {
3814                                 if (first.sendTime) {
3815                                   if (first.useColors) {
3816                                     SendToProgram("white\n", &first);
3817                                   }
3818                                   SendTimeRemaining(&first, FALSE);
3819                                 }
3820                                 if (first.useColors) {
3821                                   SendToProgram("black\n", &first);
3822                                 }
3823                                 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3824                                 first.maybeThinking = TRUE;
3825                             } else {
3826                                 if (first.usePlayother) {
3827                                   if (first.sendTime) {
3828                                     SendTimeRemaining(&first, FALSE);
3829                                   }
3830                                   SendToProgram("playother\n", &first);
3831                                   firstMove = FALSE;
3832                                 } else {
3833                                   firstMove = TRUE;
3834                                 }
3835                             }
3836                         }
3837                     }
3838 #endif
3839                     if (gameMode == IcsObserving && ics_gamenum == -1) {
3840                         /* Moves came from oldmoves or moves command
3841                            while we weren't doing anything else.
3842                            */
3843                         currentMove = forwardMostMove;
3844                         ClearHighlights();/*!!could figure this out*/
3845                         flipView = appData.flipView;
3846                         DrawPosition(TRUE, boards[currentMove]);
3847                         DisplayBothClocks();
3848                         snprintf(str, MSG_SIZ, "%s %s %s",
3849                                 gameInfo.white, _("vs."),  gameInfo.black);
3850                         DisplayTitle(str);
3851                         gameMode = IcsIdle;
3852                     } else {
3853                         /* Moves were history of an active game */
3854                         if (gameInfo.resultDetails != NULL) {
3855                             free(gameInfo.resultDetails);
3856                             gameInfo.resultDetails = NULL;
3857                         }
3858                     }
3859                     HistorySet(parseList, backwardMostMove,
3860                                forwardMostMove, currentMove-1);
3861                     DisplayMove(currentMove - 1);
3862                     if (started == STARTED_MOVES) next_out = i;
3863                     started = STARTED_NONE;
3864                     ics_getting_history = H_FALSE;
3865                     break;
3866
3867                   case STARTED_OBSERVE:
3868                     started = STARTED_NONE;
3869                     SendToICS(ics_prefix);
3870                     SendToICS("refresh\n");
3871                     break;
3872
3873                   default:
3874                     break;
3875                 }
3876                 if(bookHit) { // [HGM] book: simulate book reply
3877                     static char bookMove[MSG_SIZ]; // a bit generous?
3878
3879                     programStats.nodes = programStats.depth = programStats.time =
3880                     programStats.score = programStats.got_only_move = 0;
3881                     sprintf(programStats.movelist, "%s (xbook)", bookHit);
3882
3883                     safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3884                     strcat(bookMove, bookHit);
3885                     HandleMachineMove(bookMove, &first);
3886                 }
3887                 continue;
3888             }
3889
3890             if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3891                  started == STARTED_HOLDINGS ||
3892                  started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3893                 /* Accumulate characters in move list or board */
3894                 parse[parse_pos++] = buf[i];
3895             }
3896
3897             /* Start of game messages.  Mostly we detect start of game
3898                when the first board image arrives.  On some versions
3899                of the ICS, though, we need to do a "refresh" after starting
3900                to observe in order to get the current board right away. */
3901             if (looking_at(buf, &i, "Adding game * to observation list")) {
3902                 started = STARTED_OBSERVE;
3903                 continue;
3904             }
3905
3906             /* Handle auto-observe */
3907             if (appData.autoObserve &&
3908                 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3909                 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3910                 char *player;
3911                 /* Choose the player that was highlighted, if any. */
3912                 if (star_match[0][0] == '\033' ||
3913                     star_match[1][0] != '\033') {
3914                     player = star_match[0];
3915                 } else {
3916                     player = star_match[2];
3917                 }
3918                 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3919                         ics_prefix, StripHighlightAndTitle(player));
3920                 SendToICS(str);
3921
3922                 /* Save ratings from notify string */
3923                 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3924                 player1Rating = string_to_rating(star_match[1]);
3925                 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3926                 player2Rating = string_to_rating(star_match[3]);
3927
3928                 if (appData.debugMode)
3929                   fprintf(debugFP,
3930                           "Ratings from 'Game notification:' %s %d, %s %d\n",
3931                           player1Name, player1Rating,
3932                           player2Name, player2Rating);
3933
3934                 continue;
3935             }
3936
3937             /* Deal with automatic examine mode after a game,
3938                and with IcsObserving -> IcsExamining transition */
3939             if (looking_at(buf, &i, "Entering examine mode for game *") ||
3940                 looking_at(buf, &i, "has made you an examiner of game *")) {
3941
3942                 int gamenum = atoi(star_match[0]);
3943                 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3944                     gamenum == ics_gamenum) {
3945                     /* We were already playing or observing this game;
3946                        no need to refetch history */
3947                     gameMode = IcsExamining;
3948                     if (pausing) {
3949                         pauseExamForwardMostMove = forwardMostMove;
3950                     } else if (currentMove < forwardMostMove) {
3951                         ForwardInner(forwardMostMove);
3952                     }
3953                 } else {
3954                     /* I don't think this case really can happen */
3955                     SendToICS(ics_prefix);
3956                     SendToICS("refresh\n");
3957                 }
3958                 continue;
3959             }
3960
3961             /* Error messages */
3962 //          if (ics_user_moved) {
3963             if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3964                 if (looking_at(buf, &i, "Illegal move") ||
3965                     looking_at(buf, &i, "Not a legal move") ||
3966                     looking_at(buf, &i, "Your king is in check") ||
3967                     looking_at(buf, &i, "It isn't your turn") ||
3968                     looking_at(buf, &i, "It is not your move")) {
3969                     /* Illegal move */
3970                     if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3971                         currentMove = forwardMostMove-1;
3972                         DisplayMove(currentMove - 1); /* before DMError */
3973                         DrawPosition(FALSE, boards[currentMove]);
3974                         SwitchClocks(forwardMostMove-1); // [HGM] race
3975                         DisplayBothClocks();
3976                     }
3977                     DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3978                     ics_user_moved = 0;
3979                     continue;
3980                 }
3981             }
3982
3983             if (looking_at(buf, &i, "still have time") ||
3984                 looking_at(buf, &i, "not out of time") ||
3985                 looking_at(buf, &i, "either player is out of time") ||
3986                 looking_at(buf, &i, "has timeseal; checking")) {
3987                 /* We must have called his flag a little too soon */
3988                 whiteFlag = blackFlag = FALSE;
3989                 continue;
3990             }
3991
3992             if (looking_at(buf, &i, "added * seconds to") ||
3993                 looking_at(buf, &i, "seconds were added to")) {
3994                 /* Update the clocks */
3995                 SendToICS(ics_prefix);
3996                 SendToICS("refresh\n");
3997                 continue;
3998             }
3999
4000             if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
4001                 ics_clock_paused = TRUE;
4002                 StopClocks();
4003                 continue;
4004             }
4005
4006             if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
4007                 ics_clock_paused = FALSE;
4008                 StartClocks();
4009                 continue;
4010             }
4011
4012             /* Grab player ratings from the Creating: message.
4013                Note we have to check for the special case when
4014                the ICS inserts things like [white] or [black]. */
4015             if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
4016                 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
4017                 /* star_matches:
4018                    0    player 1 name (not necessarily white)
4019                    1    player 1 rating
4020                    2    empty, white, or black (IGNORED)
4021                    3    player 2 name (not necessarily black)
4022                    4    player 2 rating
4023
4024                    The names/ratings are sorted out when the game
4025                    actually starts (below).
4026                 */
4027                 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
4028                 player1Rating = string_to_rating(star_match[1]);
4029                 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
4030                 player2Rating = string_to_rating(star_match[4]);
4031
4032                 if (appData.debugMode)
4033                   fprintf(debugFP,
4034                           "Ratings from 'Creating:' %s %d, %s %d\n",
4035                           player1Name, player1Rating,
4036                           player2Name, player2Rating);
4037
4038                 continue;
4039             }
4040
4041             /* Improved generic start/end-of-game messages */
4042             if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
4043                 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
4044                 /* If tkind == 0: */
4045                 /* star_match[0] is the game number */
4046                 /*           [1] is the white player's name */
4047                 /*           [2] is the black player's name */
4048                 /* For end-of-game: */
4049                 /*           [3] is the reason for the game end */
4050                 /*           [4] is a PGN end game-token, preceded by " " */
4051                 /* For start-of-game: */
4052                 /*           [3] begins with "Creating" or "Continuing" */
4053                 /*           [4] is " *" or empty (don't care). */
4054                 int gamenum = atoi(star_match[0]);
4055                 char *whitename, *blackname, *why, *endtoken;
4056                 ChessMove endtype = EndOfFile;
4057
4058                 if (tkind == 0) {
4059                   whitename = star_match[1];
4060                   blackname = star_match[2];
4061                   why = star_match[3];
4062                   endtoken = star_match[4];
4063                 } else {
4064                   whitename = star_match[1];
4065                   blackname = star_match[3];
4066                   why = star_match[5];
4067                   endtoken = star_match[6];
4068                 }
4069
4070                 /* Game start messages */
4071                 if (strncmp(why, "Creating ", 9) == 0 ||
4072                     strncmp(why, "Continuing ", 11) == 0) {
4073                     gs_gamenum = gamenum;
4074                     safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
4075                     if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
4076                     VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
4077 #if ZIPPY
4078                     if (appData.zippyPlay) {
4079                         ZippyGameStart(whitename, blackname);
4080                     }
4081 #endif /*ZIPPY*/
4082                     partnerBoardValid = FALSE; // [HGM] bughouse
4083                     continue;
4084                 }
4085
4086                 /* Game end messages */
4087                 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
4088                     ics_gamenum != gamenum) {
4089                     continue;
4090                 }
4091                 while (endtoken[0] == ' ') endtoken++;
4092                 switch (endtoken[0]) {
4093                   case '*':
4094                   default:
4095                     endtype = GameUnfinished;
4096                     break;
4097                   case '0':
4098                     endtype = BlackWins;
4099                     break;
4100                   case '1':
4101                     if (endtoken[1] == '/')
4102                       endtype = GameIsDrawn;
4103                     else
4104                       endtype = WhiteWins;
4105                     break;
4106                 }
4107                 GameEnds(endtype, why, GE_ICS);
4108 #if ZIPPY
4109                 if (appData.zippyPlay && first.initDone) {
4110                     ZippyGameEnd(endtype, why);
4111                     if (first.pr == NoProc) {
4112                       /* Start the next process early so that we'll
4113                          be ready for the next challenge */
4114                       StartChessProgram(&first);
4115                     }
4116                     /* Send "new" early, in case this command takes
4117                        a long time to finish, so that we'll be ready
4118                        for the next challenge. */
4119                     gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
4120                     Reset(TRUE, TRUE);
4121                 }
4122 #endif /*ZIPPY*/
4123                 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
4124                 continue;
4125             }
4126
4127             if (looking_at(buf, &i, "Removing game * from observation") ||
4128                 looking_at(buf, &i, "no longer observing game *") ||
4129                 looking_at(buf, &i, "Game * (*) has no examiners")) {
4130                 if (gameMode == IcsObserving &&
4131                     atoi(star_match[0]) == ics_gamenum)
4132                   {
4133                       /* icsEngineAnalyze */
4134                       if (appData.icsEngineAnalyze) {
4135                             ExitAnalyzeMode();
4136                             ModeHighlight();
4137                       }
4138                       StopClocks();
4139                       gameMode = IcsIdle;
4140                       ics_gamenum = -1;
4141                       ics_user_moved = FALSE;
4142                   }
4143                 continue;
4144             }
4145
4146             if (looking_at(buf, &i, "no longer examining game *")) {
4147                 if (gameMode == IcsExamining &&
4148                     atoi(star_match[0]) == ics_gamenum)
4149                   {
4150                       gameMode = IcsIdle;
4151                       ics_gamenum = -1;
4152                       ics_user_moved = FALSE;
4153                   }
4154                 continue;
4155             }
4156
4157             /* Advance leftover_start past any newlines we find,
4158                so only partial lines can get reparsed */
4159             if (looking_at(buf, &i, "\n")) {
4160                 prevColor = curColor;
4161                 if (curColor != ColorNormal) {
4162                     if (oldi > next_out) {
4163                         SendToPlayer(&buf[next_out], oldi - next_out);
4164                         next_out = oldi;
4165                     }
4166                     Colorize(ColorNormal, FALSE);
4167                     curColor = ColorNormal;
4168                 }
4169                 if (started == STARTED_BOARD) {
4170                     started = STARTED_NONE;
4171                     parse[parse_pos] = NULLCHAR;
4172                     ParseBoard12(parse);
4173                     ics_user_moved = 0;
4174
4175                     /* Send premove here */
4176                     if (appData.premove) {
4177                       char str[MSG_SIZ];
4178                       if (currentMove == 0 &&
4179                           gameMode == IcsPlayingWhite &&
4180                           appData.premoveWhite) {
4181                         snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
4182                         if (appData.debugMode)
4183                           fprintf(debugFP, "Sending premove:\n");
4184                         SendToICS(str);
4185                       } else if (currentMove == 1 &&
4186                                  gameMode == IcsPlayingBlack &&
4187                                  appData.premoveBlack) {
4188                         snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4189                         if (appData.debugMode)
4190                           fprintf(debugFP, "Sending premove:\n");
4191                         SendToICS(str);
4192                       } else if (gotPremove) {
4193                         int oldFMM = forwardMostMove;
4194                         gotPremove = 0;
4195                         ClearPremoveHighlights();
4196                         if (appData.debugMode)
4197                           fprintf(debugFP, "Sending premove:\n");
4198                           UserMoveEvent(premoveFromX, premoveFromY,
4199                                         premoveToX, premoveToY,
4200                                         premovePromoChar);
4201                         if(forwardMostMove == oldFMM) { // premove was rejected, highlight last opponent move
4202                           if(moveList[oldFMM-1][1] != '@')
4203                             SetHighlights(moveList[oldFMM-1][0]-AAA, moveList[oldFMM-1][1]-ONE,
4204                                           moveList[oldFMM-1][2]-AAA, moveList[oldFMM-1][3]-ONE);
4205                           else // (drop)
4206                             SetHighlights(-1, -1, moveList[oldFMM-1][2]-AAA, moveList[oldFMM-1][3]-ONE);
4207                         }
4208                       }
4209                     }
4210
4211                     /* Usually suppress following prompt */
4212                     if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4213                         while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4214                         if (looking_at(buf, &i, "*% ")) {
4215                             savingComment = FALSE;
4216                             suppressKibitz = 0;
4217                         }
4218                     }
4219                     next_out = i;
4220                 } else if (started == STARTED_HOLDINGS) {
4221                     int gamenum;
4222                     char new_piece[MSG_SIZ];
4223                     started = STARTED_NONE;
4224                     parse[parse_pos] = NULLCHAR;
4225                     if (appData.debugMode)
4226                       fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4227                                                         parse, currentMove);
4228                     if (sscanf(parse, " game %d", &gamenum) == 1) {
4229                       if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4230                         new_piece[0] = NULLCHAR;
4231                         sscanf(parse, "game %d white [%s black [%s <- %s",
4232                                &gamenum, white_holding, black_holding,
4233                                new_piece);
4234                         white_holding[strlen(white_holding)-1] = NULLCHAR;
4235                         black_holding[strlen(black_holding)-1] = NULLCHAR;
4236                         if (gameInfo.variant == VariantNormal) {
4237                           /* [HGM] We seem to switch variant during a game!
4238                            * Presumably no holdings were displayed, so we have
4239                            * to move the position two files to the right to
4240                            * create room for them!
4241                            */
4242                           VariantClass newVariant;
4243                           switch(gameInfo.boardWidth) { // base guess on board width
4244                                 case 9:  newVariant = VariantShogi; break;
4245                                 case 10: newVariant = VariantGreat; break;
4246                                 default: newVariant = VariantCrazyhouse;
4247                                      if(strchr(white_holding, 'E') || strchr(black_holding, 'E') || 
4248                                         strchr(white_holding, 'H') || strchr(black_holding, 'H')   )
4249                                          newVariant = VariantSChess;
4250                           }
4251                           VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4252                           /* Get a move list just to see the header, which
4253                              will tell us whether this is really bug or zh */
4254                           if (ics_getting_history == H_FALSE) {
4255                             ics_getting_history = H_REQUESTED;
4256                             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4257                             SendToICS(str);
4258                           }
4259                         }
4260                         /* [HGM] copy holdings to board holdings area */
4261                         CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4262                         CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4263                         boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4264 #if ZIPPY
4265                         if (appData.zippyPlay && first.initDone) {
4266                             ZippyHoldings(white_holding, black_holding,
4267                                           new_piece);
4268                         }
4269 #endif /*ZIPPY*/
4270                         if (tinyLayout || smallLayout) {
4271                             char wh[16], bh[16];
4272                             PackHolding(wh, white_holding);
4273                             PackHolding(bh, black_holding);
4274                             snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4275                                     gameInfo.white, gameInfo.black);
4276                         } else {
4277                           snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4278                                     gameInfo.white, white_holding, _("vs."),
4279                                     gameInfo.black, black_holding);
4280                         }
4281                         if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4282                         DrawPosition(FALSE, boards[currentMove]);
4283                         DisplayTitle(str);
4284                       } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4285                         sscanf(parse, "game %d white [%s black [%s <- %s",
4286                                &gamenum, white_holding, black_holding,
4287                                new_piece);
4288                         white_holding[strlen(white_holding)-1] = NULLCHAR;
4289                         black_holding[strlen(black_holding)-1] = NULLCHAR;
4290                         /* [HGM] copy holdings to partner-board holdings area */
4291                         CopyHoldings(partnerBoard, white_holding, WhitePawn);
4292                         CopyHoldings(partnerBoard, black_holding, BlackPawn);
4293                         if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4294                         if(partnerUp) DrawPosition(FALSE, partnerBoard);
4295                         if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4296                       }
4297                     }
4298                     /* Suppress following prompt */
4299                     if (looking_at(buf, &i, "*% ")) {
4300                         if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4301                         savingComment = FALSE;
4302                         suppressKibitz = 0;
4303                     }
4304                     next_out = i;
4305                 }
4306                 continue;
4307             }
4308
4309             i++;                /* skip unparsed character and loop back */
4310         }
4311
4312         if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4313 //          started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4314 //          SendToPlayer(&buf[next_out], i - next_out);
4315             started != STARTED_HOLDINGS && leftover_start > next_out) {
4316             SendToPlayer(&buf[next_out], leftover_start - next_out);
4317             next_out = i;
4318         }
4319
4320         leftover_len = buf_len - leftover_start;
4321         /* if buffer ends with something we couldn't parse,
4322            reparse it after appending the next read */
4323
4324     } else if (count == 0) {
4325         RemoveInputSource(isr);
4326         DisplayFatalError(_("Connection closed by ICS"), 0, 6666);
4327     } else {
4328         DisplayFatalError(_("Error reading from ICS"), error, 1);
4329     }
4330 }
4331
4332
4333 /* Board style 12 looks like this:
4334
4335    <12> r-b---k- pp----pp ---bP--- ---p---- q------- ------P- P--Q--BP -----R-K W -1 0 0 0 0 0 0 paf MaxII 0 2 12 21 25 234 174 24 Q/d7-a4 (0:06) Qxa4 0 0
4336
4337  * The "<12> " is stripped before it gets to this routine.  The two
4338  * trailing 0's (flip state and clock ticking) are later addition, and
4339  * some chess servers may not have them, or may have only the first.
4340  * Additional trailing fields may be added in the future.
4341  */
4342
4343 #define PATTERN "%c%d%d%d%d%d%d%d%s%s%d%d%d%d%d%d%d%d%s%s%s%d%d"
4344
4345 #define RELATION_OBSERVING_PLAYED    0
4346 #define RELATION_OBSERVING_STATIC   -2   /* examined, oldmoves, or smoves */
4347 #define RELATION_PLAYING_MYMOVE      1
4348 #define RELATION_PLAYING_NOTMYMOVE  -1
4349 #define RELATION_EXAMINING           2
4350 #define RELATION_ISOLATED_BOARD     -3
4351 #define RELATION_STARTING_POSITION  -4   /* FICS only */
4352
4353 void
4354 ParseBoard12 (char *string)
4355 {
4356 #if ZIPPY
4357     int i, takeback;
4358     char *bookHit = NULL; // [HGM] book
4359 #endif
4360     GameMode newGameMode;
4361     int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
4362     int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
4363     int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4364     char to_play, board_chars[200];
4365     char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4366     char black[32], white[32];
4367     Board board;
4368     int prevMove = currentMove;
4369     int ticking = 2;
4370     ChessMove moveType;
4371     int fromX, fromY, toX, toY;
4372     char promoChar;
4373     int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4374     Boolean weird = FALSE, reqFlag = FALSE;
4375
4376     fromX = fromY = toX = toY = -1;
4377
4378     newGame = FALSE;
4379
4380     if (appData.debugMode)
4381       fprintf(debugFP, "Parsing board: %s\n", string);
4382
4383     move_str[0] = NULLCHAR;
4384     elapsed_time[0] = NULLCHAR;
4385     {   /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4386         int  i = 0, j;
4387         while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4388             if(string[i] == ' ') { ranks++; files = 0; }
4389             else files++;
4390             if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4391             i++;
4392         }
4393         for(j = 0; j <i; j++) board_chars[j] = string[j];
4394         board_chars[i] = '\0';
4395         string += i + 1;
4396     }
4397     n = sscanf(string, PATTERN, &to_play, &double_push,
4398                &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4399                &gamenum, white, black, &relation, &basetime, &increment,
4400                &white_stren, &black_stren, &white_time, &black_time,
4401                &moveNum, str, elapsed_time, move_str, &ics_flip,
4402                &ticking);
4403
4404     if (n < 21) {
4405         snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4406         DisplayError(str, 0);
4407         return;
4408     }
4409
4410     /* Convert the move number to internal form */
4411     moveNum = (moveNum - 1) * 2;
4412     if (to_play == 'B') moveNum++;
4413     if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4414       DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4415                         0, 1);
4416       return;
4417     }
4418
4419     switch (relation) {
4420       case RELATION_OBSERVING_PLAYED:
4421       case RELATION_OBSERVING_STATIC:
4422         if (gamenum == -1) {
4423             /* Old ICC buglet */
4424             relation = RELATION_OBSERVING_STATIC;
4425         }
4426         newGameMode = IcsObserving;
4427         break;
4428       case RELATION_PLAYING_MYMOVE:
4429       case RELATION_PLAYING_NOTMYMOVE:
4430         newGameMode =
4431           ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4432             IcsPlayingWhite : IcsPlayingBlack;
4433         soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4434         break;
4435       case RELATION_EXAMINING:
4436         newGameMode = IcsExamining;
4437         break;
4438       case RELATION_ISOLATED_BOARD:
4439       default:
4440         /* Just display this board.  If user was doing something else,
4441            we will forget about it until the next board comes. */
4442         newGameMode = IcsIdle;
4443         break;
4444       case RELATION_STARTING_POSITION:
4445         newGameMode = gameMode;
4446         break;
4447     }
4448
4449     if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4450         gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4451          && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4452       // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4453       int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4454       static int lastBgGame = -1;
4455       char *toSqr;
4456       for (k = 0; k < ranks; k++) {
4457         for (j = 0; j < files; j++)
4458           board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4459         if(gameInfo.holdingsWidth > 1) {
4460              board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4461              board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4462         }
4463       }
4464       CopyBoard(partnerBoard, board);
4465       if(toSqr = strchr(str, '/')) { // extract highlights from long move
4466         partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4467         partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4468       } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4469       if(toSqr = strchr(str, '-')) {
4470         partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4471         partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4472       } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4473       if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4474       if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4475       if(partnerUp) DrawPosition(FALSE, partnerBoard);
4476       if(twoBoards) {
4477           DisplayWhiteClock(white_time*fac, to_play == 'W');
4478           DisplayBlackClock(black_time*fac, to_play != 'W');
4479           activePartner = to_play;
4480           if(gamenum != lastBgGame) {
4481               char buf[MSG_SIZ];
4482               snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4483               DisplayTitle(buf);
4484           }
4485           lastBgGame = gamenum;
4486           activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4487                       partnerUp = 0; flipView = !flipView; } // [HGM] dual
4488       snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4489                  (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4490       if(!twoBoards) DisplayMessage(partnerStatus, "");
4491         partnerBoardValid = TRUE;
4492       return;
4493     }
4494
4495     if(appData.dualBoard && appData.bgObserve) {
4496         if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4497             SendToICS(ics_prefix), SendToICS("pobserve\n");
4498         else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4499             char buf[MSG_SIZ];
4500             snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4501             SendToICS(buf);
4502         }
4503     }
4504
4505     /* Modify behavior for initial board display on move listing
4506        of wild games.
4507        */
4508     switch (ics_getting_history) {
4509       case H_FALSE:
4510       case H_REQUESTED:
4511         break;
4512       case H_GOT_REQ_HEADER:
4513       case H_GOT_UNREQ_HEADER:
4514         /* This is the initial position of the current game */
4515         gamenum = ics_gamenum;
4516         moveNum = 0;            /* old ICS bug workaround */
4517         if (to_play == 'B') {
4518           startedFromSetupPosition = TRUE;
4519           blackPlaysFirst = TRUE;
4520           moveNum = 1;
4521           if (forwardMostMove == 0) forwardMostMove = 1;
4522           if (backwardMostMove == 0) backwardMostMove = 1;
4523           if (currentMove == 0) currentMove = 1;
4524         }
4525         newGameMode = gameMode;
4526         relation = RELATION_STARTING_POSITION; /* ICC needs this */
4527         break;
4528       case H_GOT_UNWANTED_HEADER:
4529         /* This is an initial board that we don't want */
4530         return;
4531       case H_GETTING_MOVES:
4532         /* Should not happen */
4533         DisplayError(_("Error gathering move list: extra board"), 0);
4534         ics_getting_history = H_FALSE;
4535         return;
4536     }
4537
4538    if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4539                                         move_str[1] == '@' && !gameInfo.holdingsWidth ||
4540                                         weird && (int)gameInfo.variant < (int)VariantShogi) {
4541      /* [HGM] We seem to have switched variant unexpectedly
4542       * Try to guess new variant from board size
4543       */
4544           VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4545           if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4546           if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4547           if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4548           if(ranks == 9 && files == 9)  newVariant = VariantShogi; else
4549           if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4550           if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4551           VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4552           /* Get a move list just to see the header, which
4553              will tell us whether this is really bug or zh */
4554           if (ics_getting_history == H_FALSE) {
4555             ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4556             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4557             SendToICS(str);
4558           }
4559     }
4560
4561     /* Take action if this is the first board of a new game, or of a
4562        different game than is currently being displayed.  */
4563     if (gamenum != ics_gamenum || newGameMode != gameMode ||
4564         relation == RELATION_ISOLATED_BOARD) {
4565
4566         /* Forget the old game and get the history (if any) of the new one */
4567         if (gameMode != BeginningOfGame) {
4568           Reset(TRUE, TRUE);
4569         }
4570         newGame = TRUE;
4571         if (appData.autoRaiseBoard) BoardToTop();
4572         prevMove = -3;
4573         if (gamenum == -1) {
4574             newGameMode = IcsIdle;
4575         } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4576                    appData.getMoveList && !reqFlag) {
4577             /* Need to get game history */
4578             ics_getting_history = H_REQUESTED;
4579             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4580             SendToICS(str);
4581         }
4582
4583         /* Initially flip the board to have black on the bottom if playing
4584            black or if the ICS flip flag is set, but let the user change
4585            it with the Flip View button. */
4586         flipView = appData.autoFlipView ?
4587           (newGameMode == IcsPlayingBlack) || ics_flip :
4588           appData.flipView;
4589
4590         /* Done with values from previous mode; copy in new ones */
4591         gameMode = newGameMode;
4592         ModeHighlight();
4593         ics_gamenum = gamenum;
4594         if (gamenum == gs_gamenum) {
4595             int klen = strlen(gs_kind);
4596             if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4597             snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4598             gameInfo.event = StrSave(str);
4599         } else {
4600             gameInfo.event = StrSave("ICS game");
4601         }
4602         gameInfo.site = StrSave(appData.icsHost);
4603         gameInfo.date = PGNDate();
4604         gameInfo.round = StrSave("-");
4605         gameInfo.white = StrSave(white);
4606         gameInfo.black = StrSave(black);
4607         timeControl = basetime * 60 * 1000;
4608         timeControl_2 = 0;
4609         timeIncrement = increment * 1000;
4610         movesPerSession = 0;
4611         gameInfo.timeControl = TimeControlTagValue();
4612         VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4613   if (appData.debugMode) {
4614     fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4615     fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4616     setbuf(debugFP, NULL);
4617   }
4618
4619         gameInfo.outOfBook = NULL;
4620
4621         /* Do we have the ratings? */
4622         if (strcmp(player1Name, white) == 0 &&
4623             strcmp(player2Name, black) == 0) {
4624             if (appData.debugMode)
4625               fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4626                       player1Rating, player2Rating);
4627             gameInfo.whiteRating = player1Rating;
4628             gameInfo.blackRating = player2Rating;
4629         } else if (strcmp(player2Name, white) == 0 &&
4630                    strcmp(player1Name, black) == 0) {
4631             if (appData.debugMode)
4632               fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4633                       player2Rating, player1Rating);
4634             gameInfo.whiteRating = player2Rating;
4635             gameInfo.blackRating = player1Rating;
4636         }
4637         player1Name[0] = player2Name[0] = NULLCHAR;
4638
4639         /* Silence shouts if requested */
4640         if (appData.quietPlay &&
4641             (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4642             SendToICS(ics_prefix);
4643             SendToICS("set shout 0\n");
4644         }
4645     }
4646
4647     /* Deal with midgame name changes */
4648     if (!newGame) {
4649         if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4650             if (gameInfo.white) free(gameInfo.white);
4651             gameInfo.white = StrSave(white);
4652         }
4653         if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4654             if (gameInfo.black) free(gameInfo.black);
4655             gameInfo.black = StrSave(black);
4656         }
4657     }
4658
4659     /* Throw away game result if anything actually changes in examine mode */
4660     if (gameMode == IcsExamining && !newGame) {
4661         gameInfo.result = GameUnfinished;
4662         if (gameInfo.resultDetails != NULL) {
4663             free(gameInfo.resultDetails);
4664             gameInfo.resultDetails = NULL;
4665         }
4666     }
4667
4668     /* In pausing && IcsExamining mode, we ignore boards coming
4669        in if they are in a different variation than we are. */
4670     if (pauseExamInvalid) return;
4671     if (pausing && gameMode == IcsExamining) {
4672         if (moveNum <= pauseExamForwardMostMove) {
4673             pauseExamInvalid = TRUE;
4674             forwardMostMove = pauseExamForwardMostMove;
4675             return;
4676         }
4677     }
4678
4679   if (appData.debugMode) {
4680     fprintf(debugFP, "load %dx%d board\n", files, ranks);
4681   }
4682     /* Parse the board */
4683     for (k = 0; k < ranks; k++) {
4684       for (j = 0; j < files; j++)
4685         board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4686       if(gameInfo.holdingsWidth > 1) {
4687            board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4688            board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4689       }
4690     }
4691     if(moveNum==0 && gameInfo.variant == VariantSChess) {
4692       board[5][BOARD_RGHT+1] = WhiteAngel;
4693       board[6][BOARD_RGHT+1] = WhiteMarshall;
4694       board[1][0] = BlackMarshall;
4695       board[2][0] = BlackAngel;
4696       board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4697     }
4698     CopyBoard(boards[moveNum], board);
4699     boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4700     if (moveNum == 0) {
4701         startedFromSetupPosition =
4702           !CompareBoards(board, initialPosition);
4703         if(startedFromSetupPosition)
4704             initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4705     }
4706
4707     /* [HGM] Set castling rights. Take the outermost Rooks,
4708        to make it also work for FRC opening positions. Note that board12
4709        is really defective for later FRC positions, as it has no way to
4710        indicate which Rook can castle if they are on the same side of King.
4711        For the initial position we grant rights to the outermost Rooks,
4712        and remember thos rights, and we then copy them on positions
4713        later in an FRC game. This means WB might not recognize castlings with
4714        Rooks that have moved back to their original position as illegal,
4715        but in ICS mode that is not its job anyway.
4716     */
4717     if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4718     { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4719
4720         for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4721             if(board[0][i] == WhiteRook) j = i;
4722         initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4723         for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4724             if(board[0][i] == WhiteRook) j = i;
4725         initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4726         for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4727             if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4728         initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4729         for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4730             if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4731         initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4732
4733         boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4734         if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4735         for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4736             if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4737         for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4738             if(board[BOARD_HEIGHT-1][k] == bKing)
4739                 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4740         if(gameInfo.variant == VariantTwoKings) {
4741             // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4742             if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4743             if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4744         }
4745     } else { int r;
4746         r = boards[moveNum][CASTLING][0] = initialRights[0];
4747         if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4748         r = boards[moveNum][CASTLING][1] = initialRights[1];
4749         if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4750         r = boards[moveNum][CASTLING][3] = initialRights[3];
4751         if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4752         r = boards[moveNum][CASTLING][4] = initialRights[4];
4753         if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4754         /* wildcastle kludge: always assume King has rights */
4755         r = boards[moveNum][CASTLING][2] = initialRights[2];
4756         r = boards[moveNum][CASTLING][5] = initialRights[5];
4757     }
4758     /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4759     boards[moveNum][EP_STATUS] = EP_NONE;
4760     if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4761     if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4762     if(double_push !=  -1) {
4763         int dir = WhiteOnMove(moveNum) ? 1 : -1, last = BOARD_HEIGHT-1;
4764         boards[moveNum][EP_FILE] = // also set new e.p. variables
4765         boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4766         boards[moveNum][EP_RANK] = (last + 3*dir)/2;
4767         boards[moveNum][LAST_TO] = 128*(last + dir) + boards[moveNum][EP_FILE];
4768     } else boards[moveNum][EP_FILE] = boards[moveNum][EP_RANK] = 100;
4769
4770
4771     if (ics_getting_history == H_GOT_REQ_HEADER ||
4772         ics_getting_history == H_GOT_UNREQ_HEADER) {
4773         /* This was an initial position from a move list, not
4774            the current position */
4775         return;
4776     }
4777
4778     /* Update currentMove and known move number limits */
4779     newMove = newGame || moveNum > forwardMostMove;
4780
4781     if (newGame) {
4782         forwardMostMove = backwardMostMove = currentMove = moveNum;
4783         if (gameMode == IcsExamining && moveNum == 0) {
4784           /* Workaround for ICS limitation: we are not told the wild
4785              type when starting to examine a game.  But if we ask for
4786              the move list, the move list header will tell us */
4787             ics_getting_history = H_REQUESTED;
4788             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4789             SendToICS(str);
4790         }
4791     } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4792                || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4793 #if ZIPPY
4794         /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4795         /* [HGM] applied this also to an engine that is silently watching        */
4796         if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4797             (gameMode == IcsObserving || gameMode == IcsExamining) &&
4798             gameInfo.variant == currentlyInitializedVariant) {
4799           takeback = forwardMostMove - moveNum;
4800           for (i = 0; i < takeback; i++) {
4801             if (appData.debugMode) fprintf(debugFP, "take back move\n");
4802             SendToProgram("undo\n", &first);
4803           }
4804         }
4805 #endif
4806
4807         forwardMostMove = moveNum;
4808         if (!pausing || currentMove > forwardMostMove)
4809           currentMove = forwardMostMove;
4810     } else {
4811         /* New part of history that is not contiguous with old part */
4812         if (pausing && gameMode == IcsExamining) {
4813             pauseExamInvalid = TRUE;
4814             forwardMostMove = pauseExamForwardMostMove;
4815             return;
4816         }
4817         if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4818 #if ZIPPY
4819             if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4820                 // [HGM] when we will receive the move list we now request, it will be
4821                 // fed to the engine from the first move on. So if the engine is not
4822                 // in the initial position now, bring it there.
4823                 InitChessProgram(&first, 0);
4824             }
4825 #endif
4826             ics_getting_history = H_REQUESTED;
4827             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4828             SendToICS(str);
4829         }
4830         forwardMostMove = backwardMostMove = currentMove = moveNum;
4831     }
4832
4833     /* Update the clocks */
4834     if (strchr(elapsed_time, '.')) {
4835       /* Time is in ms */
4836       timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4837       timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4838     } else {
4839       /* Time is in seconds */
4840       timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4841       timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4842     }
4843
4844
4845 #if ZIPPY
4846     if (appData.zippyPlay && newGame &&
4847         gameMode != IcsObserving && gameMode != IcsIdle &&
4848         gameMode != IcsExamining)
4849       ZippyFirstBoard(moveNum, basetime, increment);
4850 #endif
4851
4852     /* Put the move on the move list, first converting
4853        to canonical algebraic form. */
4854     if (moveNum > 0) {
4855   if (appData.debugMode) {
4856     int f = forwardMostMove;
4857     fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4858             boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4859             boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4860     fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4861     fprintf(debugFP, "moveNum = %d\n", moveNum);
4862     fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4863     setbuf(debugFP, NULL);
4864   }
4865         if (moveNum <= backwardMostMove) {
4866             /* We don't know what the board looked like before
4867                this move.  Punt. */
4868           safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4869             strcat(parseList[moveNum - 1], " ");
4870             strcat(parseList[moveNum - 1], elapsed_time);
4871             moveList[moveNum - 1][0] = NULLCHAR;
4872         } else if (strcmp(move_str, "none") == 0) {
4873             // [HGM] long SAN: swapped order; test for 'none' before parsing move
4874             /* Again, we don't know what the board looked like;
4875                this is really the start of the game. */
4876             parseList[moveNum - 1][0] = NULLCHAR;
4877             moveList[moveNum - 1][0] = NULLCHAR;
4878             backwardMostMove = moveNum;
4879             startedFromSetupPosition = TRUE;
4880             fromX = fromY = toX = toY = -1;
4881         } else {
4882           // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4883           //                 So we parse the long-algebraic move string in stead of the SAN move
4884           int valid; char buf[MSG_SIZ], *prom;
4885
4886           if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4887                 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4888           // str looks something like "Q/a1-a2"; kill the slash
4889           if(str[1] == '/')
4890             snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4891           else  safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4892           if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4893                 strcat(buf, prom); // long move lacks promo specification!
4894           if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4895                 if(appData.debugMode)
4896                         fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4897                 safeStrCpy(move_str, buf, MSG_SIZ);
4898           }
4899           valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4900                                 &fromX, &fromY, &toX, &toY, &promoChar)
4901                || ParseOneMove(buf, moveNum - 1, &moveType,
4902                                 &fromX, &fromY, &toX, &toY, &promoChar);
4903           // end of long SAN patch
4904           if (valid) {
4905             (void) CoordsToAlgebraic(boards[moveNum - 1],
4906                                      PosFlags(moveNum - 1),
4907                                      fromY, fromX, toY, toX, promoChar,
4908                                      parseList[moveNum-1]);
4909             switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4910               case MT_NONE:
4911               case MT_STALEMATE:
4912               default:
4913                 break;
4914               case MT_CHECK:
4915                 if(!IS_SHOGI(gameInfo.variant))
4916                     strcat(parseList[moveNum - 1], "+");
4917                 break;
4918               case MT_CHECKMATE:
4919               case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4920                 strcat(parseList[moveNum - 1], "#");
4921                 break;
4922             }
4923             strcat(parseList[moveNum - 1], " ");
4924             strcat(parseList[moveNum - 1], elapsed_time);
4925             /* currentMoveString is set as a side-effect of ParseOneMove */
4926             if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4927             safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4928             strcat(moveList[moveNum - 1], "\n");
4929
4930             if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4931                && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4932               for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4933                 ChessSquare old, new = boards[moveNum][k][j];
4934                   if(new == EmptySquare || fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4935                   old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4936                   if(old == new) continue;
4937                   if(old == PROMOTED(new)) boards[moveNum][k][j] = old;// prevent promoted pieces to revert to primordial ones
4938                   else if(new == WhiteWazir || new == BlackWazir) {
4939                       if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4940                            boards[moveNum][k][j] = PROMOTED(old); // choose correct type of Gold in promotion
4941                       else boards[moveNum][k][j] = old; // preserve type of Gold
4942                   } else if(old == WhitePawn || old == BlackPawn) // Pawn promotions (but not e.p.capture!)
4943                       boards[moveNum][k][j] = PROMOTED(new); // use non-primordial representation of chosen piece
4944               }
4945           } else {
4946             /* Move from ICS was illegal!?  Punt. */
4947             if (appData.debugMode) {
4948               fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4949               fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4950             }
4951             safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4952             strcat(parseList[moveNum - 1], " ");
4953             strcat(parseList[moveNum - 1], elapsed_time);
4954             moveList[moveNum - 1][0] = NULLCHAR;
4955             fromX = fromY = toX = toY = -1;
4956           }
4957         }
4958   if (appData.debugMode) {
4959     fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4960     setbuf(debugFP, NULL);
4961   }
4962
4963 #if ZIPPY
4964         /* Send move to chess program (BEFORE animating it). */
4965         if (appData.zippyPlay && !newGame && newMove &&
4966            (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4967
4968             if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4969                 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4970                 if (moveList[moveNum - 1][0] == NULLCHAR) {
4971                   snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4972                             move_str);
4973                     DisplayError(str, 0);
4974                 } else {
4975                     if (first.sendTime) {
4976                         SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4977                     }
4978                     bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4979                     if (firstMove && !bookHit) {
4980                         firstMove = FALSE;
4981                         if (first.useColors) {
4982                           SendToProgram(gameMode == IcsPlayingWhite ?
4983                                         "white\ngo\n" :
4984                                         "black\ngo\n", &first);
4985                         } else {
4986                           SendToProgram("go\n", &first);
4987                         }
4988                         first.maybeThinking = TRUE;
4989                     }
4990                 }
4991             } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4992               if (moveList[moveNum - 1][0] == NULLCHAR) {
4993                 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4994                 DisplayError(str, 0);
4995               } else {
4996                 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4997                 SendMoveToProgram(moveNum - 1, &first);
4998               }
4999             }
5000         }
5001 #endif
5002     }
5003
5004     if (moveNum > 0 && !gotPremove && !appData.noGUI) {
5005         /* If move comes from a remote source, animate it.  If it
5006            isn't remote, it will have already been animated. */
5007         if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
5008             AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
5009         }
5010         if (!pausing && appData.highlightLastMove) {
5011             SetHighlights(fromX, fromY, toX, toY);
5012         }
5013     }
5014
5015     /* Start the clocks */
5016     whiteFlag = blackFlag = FALSE;
5017     appData.clockMode = !(basetime == 0 && increment == 0);
5018     if (ticking == 0) {
5019       ics_clock_paused = TRUE;
5020       StopClocks();
5021     } else if (ticking == 1) {
5022       ics_clock_paused = FALSE;
5023     }
5024     if (gameMode == IcsIdle ||
5025         relation == RELATION_OBSERVING_STATIC ||
5026         relation == RELATION_EXAMINING ||
5027         ics_clock_paused)
5028       DisplayBothClocks();
5029     else
5030       StartClocks();
5031
5032     /* Display opponents and material strengths */
5033     if (gameInfo.variant != VariantBughouse &&
5034         gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
5035         if (tinyLayout || smallLayout) {
5036             if(gameInfo.variant == VariantNormal)
5037               snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
5038                     gameInfo.white, white_stren, gameInfo.black, black_stren,
5039                     basetime, increment);
5040             else
5041               snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
5042                     gameInfo.white, white_stren, gameInfo.black, black_stren,
5043                     basetime, increment, (int) gameInfo.variant);
5044         } else {
5045             if(gameInfo.variant == VariantNormal)
5046               snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
5047                     gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5048                     basetime, increment);
5049             else
5050               snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
5051                     gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5052                     basetime, increment, VariantName(gameInfo.variant));
5053         }
5054         DisplayTitle(str);
5055   if (appData.debugMode) {
5056     fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
5057   }
5058     }
5059
5060
5061     /* Display the board */
5062     if (!pausing && !appData.noGUI) {
5063
5064       if (appData.premove)
5065           if (!gotPremove ||
5066              ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
5067              ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
5068               ClearPremoveHighlights();
5069
5070       j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
5071         if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
5072       DrawPosition(j, boards[currentMove]);
5073
5074       DisplayMove(moveNum - 1);
5075       if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
5076             !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
5077               (gameMode == IcsPlayingBlack) &&  (WhiteOnMove(moveNum))   ) ) {
5078         if(newMove) RingBell(); else PlayIcsUnfinishedSound();
5079       }
5080     }
5081
5082     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5083 #if ZIPPY
5084     if(bookHit) { // [HGM] book: simulate book reply
5085         static char bookMove[MSG_SIZ]; // a bit generous?
5086
5087         programStats.nodes = programStats.depth = programStats.time =
5088         programStats.score = programStats.got_only_move = 0;
5089         sprintf(programStats.movelist, "%s (xbook)", bookHit);
5090
5091         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
5092         strcat(bookMove, bookHit);
5093         HandleMachineMove(bookMove, &first);
5094     }
5095 #endif
5096 }
5097
5098 void
5099 GetMoveListEvent ()
5100 {
5101     char buf[MSG_SIZ];
5102     if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
5103         ics_getting_history = H_REQUESTED;
5104         snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
5105         SendToICS(buf);
5106     }
5107 }
5108
5109 void
5110 SendToBoth (char *msg)
5111 {   // to make it easy to keep two engines in step in dual analysis
5112     SendToProgram(msg, &first);
5113     if(second.analyzing) SendToProgram(msg, &second);
5114 }
5115
5116 void
5117 AnalysisPeriodicEvent (int force)
5118 {
5119     if (((programStats.ok_to_send == 0 || programStats.line_is_book)
5120          && !force) || !appData.periodicUpdates)
5121       return;
5122
5123     /* Send . command to Crafty to collect stats */
5124     SendToBoth(".\n");
5125
5126     /* Don't send another until we get a response (this makes
5127        us stop sending to old Crafty's which don't understand
5128        the "." command (sending illegal cmds resets node count & time,
5129        which looks bad)) */
5130     programStats.ok_to_send = 0;
5131 }
5132
5133 void
5134 ics_update_width (int new_width)
5135 {
5136         ics_printf("set width %d\n", new_width);
5137 }
5138
5139 void
5140 SendMoveToProgram (int moveNum, ChessProgramState *cps)
5141 {
5142     char buf[MSG_SIZ];
5143
5144     if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
5145         if(gameInfo.variant == VariantLion || gameInfo.variant == VariantChuChess || gameInfo.variant == VariantChu) {
5146             sprintf(buf, "%s@@@@\n", cps->useUsermove ? "usermove " : "");
5147             SendToProgram(buf, cps);
5148             return;
5149         }
5150         // null move in variant where engine does not understand it (for analysis purposes)
5151         SendBoard(cps, moveNum + 1); // send position after move in stead.
5152         return;
5153     }
5154     if (cps->useUsermove) {
5155       SendToProgram("usermove ", cps);
5156     }
5157     if (cps->useSAN) {
5158       char *space;
5159       if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
5160         int len = space - parseList[moveNum];
5161         memcpy(buf, parseList[moveNum], len);
5162         buf[len++] = '\n';
5163         buf[len] = NULLCHAR;
5164       } else {
5165         snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
5166       }
5167       SendToProgram(buf, cps);
5168     } else {
5169       if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
5170         AlphaRank(moveList[moveNum], 4);
5171         SendToProgram(moveList[moveNum], cps);
5172         AlphaRank(moveList[moveNum], 4); // and back
5173       } else
5174       /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
5175        * the engine. It would be nice to have a better way to identify castle
5176        * moves here. */
5177       if(appData.fischerCastling && cps->useOOCastle) {
5178         int fromX = moveList[moveNum][0] - AAA;
5179         int fromY = moveList[moveNum][1] - ONE;
5180         int toX = moveList[moveNum][2] - AAA;
5181         int toY = moveList[moveNum][3] - ONE;
5182         if((boards[moveNum][fromY][fromX] == WhiteKing
5183             && boards[moveNum][toY][toX] == WhiteRook)
5184            || (boards[moveNum][fromY][fromX] == BlackKing
5185                && boards[moveNum][toY][toX] == BlackRook)) {
5186           if(toX > fromX) SendToProgram("O-O\n", cps);
5187           else SendToProgram("O-O-O\n", cps);
5188         }
5189         else SendToProgram(moveList[moveNum], cps);
5190       } else
5191       if(moveList[moveNum][4] == ';') { // [HGM] lion: move is double-step over intermediate square
5192         char *m = moveList[moveNum];
5193         static char c[2];
5194         *c = m[7]; if(*c == '\n') *c = NULLCHAR; // promoChar
5195         if((boards[moveNum][m[6]-ONE][m[5]-AAA] < BlackPawn) == (boards[moveNum][m[1]-ONE][m[0]-AAA] < BlackPawn)) // move is kludge to indicate castling
5196           snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d\n", m[0], m[1] - '0', // convert to two moves
5197                                                m[2], m[3] - '0',
5198                                                m[5], m[6] - '0',
5199                                                m[2] + (m[0] > m[5] ? 1 : -1), m[3] - '0');
5200         else if(*c && m[8] != '\n') { // kill square followed by 2 characters: 2nd kill square rather than promo suffix
5201           *c = m[9]; if(*c == '\n') *c = NULLCHAR;
5202           snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d,%c%d%c%d%s\n", m[0], m[1] - '0', // convert to three moves
5203                                                m[7], m[8] - '0',
5204                                                m[7], m[8] - '0',
5205                                                m[5], m[6] - '0',
5206                                                m[5], m[6] - '0',
5207                                                m[2], m[3] - '0', c);
5208         } else
5209           snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d%s\n", m[0], m[1] - '0', // convert to two moves
5210                                                m[5], m[6] - '0',
5211                                                m[5], m[6] - '0',
5212                                                m[2], m[3] - '0', c);
5213           SendToProgram(buf, cps);
5214       } else
5215       if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
5216         if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
5217           if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
5218           snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
5219                                               moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5220         } else
5221           snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
5222                                                moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5223         SendToProgram(buf, cps);
5224       }
5225       else SendToProgram(moveList[moveNum], cps);
5226       /* End of additions by Tord */
5227     }
5228
5229     /* [HGM] setting up the opening has brought engine in force mode! */
5230     /*       Send 'go' if we are in a mode where machine should play. */
5231     if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
5232         (gameMode == TwoMachinesPlay   ||
5233 #if ZIPPY
5234          gameMode == IcsPlayingBlack     || gameMode == IcsPlayingWhite ||
5235 #endif
5236          gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5237         SendToProgram("go\n", cps);
5238   if (appData.debugMode) {
5239     fprintf(debugFP, "(extra)\n");
5240   }
5241     }
5242     setboardSpoiledMachineBlack = 0;
5243 }
5244
5245 void
5246 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5247 {
5248     char user_move[MSG_SIZ];
5249     char suffix[4];
5250
5251     if(gameInfo.variant == VariantSChess && promoChar) {
5252         snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5253         if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5254     } else suffix[0] = NULLCHAR;
5255
5256     switch (moveType) {
5257       default:
5258         snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5259                 (int)moveType, fromX, fromY, toX, toY);
5260         DisplayError(user_move + strlen("say "), 0);
5261         break;
5262       case WhiteKingSideCastle:
5263       case BlackKingSideCastle:
5264       case WhiteQueenSideCastleWild:
5265       case BlackQueenSideCastleWild:
5266       /* PUSH Fabien */
5267       case WhiteHSideCastleFR:
5268       case BlackHSideCastleFR:
5269       /* POP Fabien */
5270         snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5271         break;
5272       case WhiteQueenSideCastle:
5273       case BlackQueenSideCastle:
5274       case WhiteKingSideCastleWild:
5275       case BlackKingSideCastleWild:
5276       /* PUSH Fabien */
5277       case WhiteASideCastleFR:
5278       case BlackASideCastleFR:
5279       /* POP Fabien */
5280         snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5281         break;
5282       case WhiteNonPromotion:
5283       case BlackNonPromotion:
5284         sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5285         break;
5286       case WhitePromotion:
5287       case BlackPromotion:
5288         if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
5289            gameInfo.variant == VariantMakruk)
5290           snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5291                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5292                 PieceToChar(WhiteFerz));
5293         else if(gameInfo.variant == VariantGreat)
5294           snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5295                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5296                 PieceToChar(WhiteMan));
5297         else
5298           snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5299                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5300                 promoChar);
5301         break;
5302       case WhiteDrop:
5303       case BlackDrop:
5304       drop:
5305         snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5306                  ToUpper(PieceToChar((ChessSquare) fromX)),
5307                  AAA + toX, ONE + toY);
5308         break;
5309       case IllegalMove:  /* could be a variant we don't quite understand */
5310         if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5311       case NormalMove:
5312       case WhiteCapturesEnPassant:
5313       case BlackCapturesEnPassant:
5314         snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5315                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5316         break;
5317     }
5318     SendToICS(user_move);
5319     if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5320         ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5321 }
5322
5323 void
5324 UploadGameEvent ()
5325 {   // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5326     int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5327     static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5328     if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5329       DisplayError(_("You cannot do this while you are playing or observing"), 0);
5330       return;
5331     }
5332     if(gameMode != IcsExamining) { // is this ever not the case?
5333         char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5334
5335         if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5336           snprintf(command,MSG_SIZ, "match %s", ics_handle);
5337         } else { // on FICS we must first go to general examine mode
5338           safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5339         }
5340         if(gameInfo.variant != VariantNormal) {
5341             // try figure out wild number, as xboard names are not always valid on ICS
5342             for(i=1; i<=36; i++) {
5343               snprintf(buf, MSG_SIZ, "wild/%d", i);
5344                 if(StringToVariant(buf) == gameInfo.variant) break;
5345             }
5346             if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5347             else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5348             else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5349         } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5350         SendToICS(ics_prefix);
5351         SendToICS(buf);
5352         if(startedFromSetupPosition || backwardMostMove != 0) {
5353           fen = PositionToFEN(backwardMostMove, NULL, 1);
5354           if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5355             snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5356             SendToICS(buf);
5357           } else { // FICS: everything has to set by separate bsetup commands
5358             p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5359             snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5360             SendToICS(buf);
5361             if(!WhiteOnMove(backwardMostMove)) {
5362                 SendToICS("bsetup tomove black\n");
5363             }
5364             i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5365             snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5366             SendToICS(buf);
5367             i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5368             snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5369             SendToICS(buf);
5370             i = boards[backwardMostMove][EP_STATUS];
5371             if(i >= 0) { // set e.p.
5372               snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5373                 SendToICS(buf);
5374             }
5375             bsetup++;
5376           }
5377         }
5378       if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5379             SendToICS("bsetup done\n"); // switch to normal examining.
5380     }
5381     for(i = backwardMostMove; i<last; i++) {
5382         char buf[20];
5383         snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5384         if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5385             int len = strlen(moveList[i]);
5386             snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5387             if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5388         }
5389         SendToICS(buf);
5390     }
5391     SendToICS(ics_prefix);
5392     SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5393 }
5394
5395 int killX = -1, killY = -1, kill2X = -1, kill2Y = -1; // [HGM] lion: used for passing e.p. capture square to MakeMove
5396 int legNr = 1;
5397
5398 void
5399 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[9])
5400 {
5401     if (rf == DROP_RANK) {
5402       if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5403       sprintf(move, "%c@%c%c\n",
5404                 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5405     } else {
5406         if (promoChar == 'x' || promoChar == NULLCHAR) {
5407           sprintf(move, "%c%c%c%c\n",
5408                     AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5409           if(killX >= 0 && killY >= 0) {
5410             sprintf(move+4, ";%c%c\n", AAA + killX, ONE + killY);
5411             if(kill2X >= 0 && kill2Y >= 0) sprintf(move+7, "%c%c\n", AAA + kill2X, ONE + kill2Y);
5412           }
5413         } else {
5414             sprintf(move, "%c%c%c%c%c\n",
5415                     AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5416           if(killX >= 0 && killY >= 0) {
5417             sprintf(move+4, ";%c%c%c\n", AAA + killX, ONE + killY, promoChar);
5418             if(kill2X >= 0 && kill2Y >= 0) sprintf(move+7, "%c%c%c\n", AAA + kill2X, ONE + kill2Y, promoChar);
5419           }
5420         }
5421     }
5422 }
5423
5424 void
5425 ProcessICSInitScript (FILE *f)
5426 {
5427     char buf[MSG_SIZ];
5428
5429     while (fgets(buf, MSG_SIZ, f)) {
5430         SendToICSDelayed(buf,(long)appData.msLoginDelay);
5431     }
5432
5433     fclose(f);
5434 }
5435
5436
5437 static int lastX, lastY, lastLeftX, lastLeftY, selectFlag;
5438 int dragging;
5439 static ClickType lastClickType;
5440
5441 int
5442 PieceInString (char *s, ChessSquare piece)
5443 {
5444   char *p, ID = ToUpper(PieceToChar(piece)), suffix = PieceSuffix(piece);
5445   while((p = strchr(s, ID))) {
5446     if(!suffix || p[1] == suffix) return TRUE;
5447     s = p;
5448   }
5449   return FALSE;
5450 }
5451
5452 int
5453 Partner (ChessSquare *p)
5454 { // change piece into promotion partner if one shogi-promotes to the other
5455   ChessSquare partner = promoPartner[*p];
5456   if(PieceToChar(*p) != '+' && PieceToChar(partner) != '+') return 0;
5457   if(PieceToChar(*p) == '+') partner = boards[currentMove][fromY][fromX];
5458   *p = partner;
5459   return 1;
5460 }
5461
5462 void
5463 Sweep (int step)
5464 {
5465     ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5466     static int toggleFlag;
5467     if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5468     if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5469     if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5470     if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5471     if(fromY != BOARD_HEIGHT-2 && fromY != 1 && gameInfo.variant != VariantChuChess) pawn = EmptySquare;
5472     if(!step) toggleFlag = Partner(&last); // piece has shogi-promotion
5473     do {
5474         if(step && !(toggleFlag && Partner(&promoSweep))) promoSweep -= step;
5475         if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5476         else if((int)promoSweep == -1) promoSweep = WhiteKing;
5477         else if(promoSweep == BlackPawn && step < 0 && !toggleFlag) promoSweep = WhitePawn;
5478         else if(promoSweep == WhiteKing && step > 0 && !toggleFlag) promoSweep = BlackKing;
5479         if(!step) step = -1;
5480     } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' ||
5481             !toggleFlag && PieceToChar(promoSweep) == '+' || // skip promoted versions of other
5482             promoRestrict[0] ? !PieceInString(promoRestrict, promoSweep) : // if choice set available, use it 
5483             promoSweep == pawn ||
5484             appData.testLegality && (promoSweep == king || gameInfo.variant != VariantChuChess &&
5485             (promoSweep == WhiteLion || promoSweep == BlackLion)));
5486     if(toX >= 0) {
5487         int victim = boards[currentMove][toY][toX];
5488         boards[currentMove][toY][toX] = promoSweep;
5489         DrawPosition(FALSE, boards[currentMove]);
5490         boards[currentMove][toY][toX] = victim;
5491     } else
5492     ChangeDragPiece(promoSweep);
5493 }
5494
5495 int
5496 PromoScroll (int x, int y)
5497 {
5498   int step = 0;
5499
5500   if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5501   if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5502   if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5503   if(!step) return FALSE;
5504   lastX = x; lastY = y;
5505   if((promoSweep < BlackPawn) == flipView) step = -step;
5506   if(step > 0) selectFlag = 1;
5507   if(!selectFlag) Sweep(step);
5508   return FALSE;
5509 }
5510
5511 void
5512 NextPiece (int step)
5513 {
5514     ChessSquare piece = boards[currentMove][toY][toX];
5515     do {
5516         pieceSweep -= step;
5517         if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5518         if((int)pieceSweep == -1) pieceSweep = BlackKing;
5519         if(!step) step = -1;
5520     } while(PieceToChar(pieceSweep) == '.');
5521     boards[currentMove][toY][toX] = pieceSweep;
5522     DrawPosition(FALSE, boards[currentMove]);
5523     boards[currentMove][toY][toX] = piece;
5524 }
5525 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5526 void
5527 AlphaRank (char *move, int n)
5528 {
5529 //    char *p = move, c; int x, y;
5530
5531     if (appData.debugMode) {
5532         fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5533     }
5534
5535     if(move[1]=='*' &&
5536        move[2]>='0' && move[2]<='9' &&
5537        move[3]>='a' && move[3]<='x'    ) {
5538         move[1] = '@';
5539         move[2] = BOARD_RGHT  -1 - (move[2]-'1') + AAA;
5540         move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5541     } else
5542     if(move[0]>='0' && move[0]<='9' &&
5543        move[1]>='a' && move[1]<='x' &&
5544        move[2]>='0' && move[2]<='9' &&
5545        move[3]>='a' && move[3]<='x'    ) {
5546         /* input move, Shogi -> normal */
5547         move[0] = BOARD_RGHT  -1 - (move[0]-'1') + AAA;
5548         move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5549         move[2] = BOARD_RGHT  -1 - (move[2]-'1') + AAA;
5550         move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5551     } else
5552     if(move[1]=='@' &&
5553        move[3]>='0' && move[3]<='9' &&
5554        move[2]>='a' && move[2]<='x'    ) {
5555         move[1] = '*';
5556         move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5557         move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5558     } else
5559     if(
5560        move[0]>='a' && move[0]<='x' &&
5561        move[3]>='0' && move[3]<='9' &&
5562        move[2]>='a' && move[2]<='x'    ) {
5563          /* output move, normal -> Shogi */
5564         move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5565         move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5566         move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5567         move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5568         if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5569     }
5570     if (appData.debugMode) {
5571         fprintf(debugFP, "   out = '%s'\n", move);
5572     }
5573 }
5574
5575 char yy_textstr[8000];
5576
5577 /* Parser for moves from gnuchess, ICS, or user typein box */
5578 Boolean
5579 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5580 {
5581     *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5582
5583     switch (*moveType) {
5584       case WhitePromotion:
5585       case BlackPromotion:
5586       case WhiteNonPromotion:
5587       case BlackNonPromotion:
5588       case NormalMove:
5589       case FirstLeg:
5590       case WhiteCapturesEnPassant:
5591       case BlackCapturesEnPassant:
5592       case WhiteKingSideCastle:
5593       case WhiteQueenSideCastle:
5594       case BlackKingSideCastle:
5595       case BlackQueenSideCastle:
5596       case WhiteKingSideCastleWild:
5597       case WhiteQueenSideCastleWild:
5598       case BlackKingSideCastleWild:
5599       case BlackQueenSideCastleWild:
5600       /* Code added by Tord: */
5601       case WhiteHSideCastleFR:
5602       case WhiteASideCastleFR:
5603       case BlackHSideCastleFR:
5604       case BlackASideCastleFR:
5605       /* End of code added by Tord */
5606       case IllegalMove:         /* bug or odd chess variant */
5607         if(currentMoveString[1] == '@') { // illegal drop
5608           *fromX = WhiteOnMove(moveNum) ?
5609             (int) CharToPiece(ToUpper(currentMoveString[0])) :
5610             (int) CharToPiece(ToLower(currentMoveString[0]));
5611           goto drop;
5612         }
5613         *fromX = currentMoveString[0] - AAA;
5614         *fromY = currentMoveString[1] - ONE;
5615         *toX = currentMoveString[2] - AAA;
5616         *toY = currentMoveString[3] - ONE;
5617         *promoChar = currentMoveString[4];
5618         if(*promoChar == ';') *promoChar = currentMoveString[7 + 2*(currentMoveString[8] != 0)];
5619         if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5620             *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5621     if (appData.debugMode) {
5622         fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5623     }
5624             *fromX = *fromY = *toX = *toY = 0;
5625             return FALSE;
5626         }
5627         if (appData.testLegality) {
5628           return (*moveType != IllegalMove);
5629         } else {
5630           return !(*fromX == *toX && *fromY == *toY && killX < 0) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5631                          // [HGM] lion: if this is a double move we are less critical
5632                         WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5633         }
5634
5635       case WhiteDrop:
5636       case BlackDrop:
5637         *fromX = *moveType == WhiteDrop ?
5638           (int) CharToPiece(ToUpper(currentMoveString[0])) :
5639           (int) CharToPiece(ToLower(currentMoveString[0]));
5640       drop:
5641         *fromY = DROP_RANK;
5642         *toX = currentMoveString[2] - AAA;
5643         *toY = currentMoveString[3] - ONE;
5644         *promoChar = NULLCHAR;
5645         return TRUE;
5646
5647       case AmbiguousMove:
5648       case ImpossibleMove:
5649       case EndOfFile:
5650       case ElapsedTime:
5651       case Comment:
5652       case PGNTag:
5653       case NAG:
5654       case WhiteWins:
5655       case BlackWins:
5656       case GameIsDrawn:
5657       default:
5658     if (appData.debugMode) {
5659         fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5660     }
5661         /* bug? */
5662         *fromX = *fromY = *toX = *toY = 0;
5663         *promoChar = NULLCHAR;
5664         return FALSE;
5665     }
5666 }
5667
5668 Boolean pushed = FALSE;
5669 char *lastParseAttempt;
5670
5671 void
5672 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5673 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5674   int fromX, fromY, toX, toY; char promoChar;
5675   ChessMove moveType;
5676   Boolean valid;
5677   int nr = 0;
5678
5679   lastParseAttempt = pv; if(!*pv) return;    // turns out we crash when we parse an empty PV
5680   if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
5681     PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5682     pushed = TRUE;
5683   }
5684   endPV = forwardMostMove;
5685   do {
5686     while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5687     if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5688     lastParseAttempt = pv;
5689     valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5690     if(!valid && nr == 0 &&
5691        ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5692         nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5693         // Hande case where played move is different from leading PV move
5694         CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5695         CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5696         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5697         if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5698           endPV += 2; // if position different, keep this
5699           moveList[endPV-1][0] = fromX + AAA;
5700           moveList[endPV-1][1] = fromY + ONE;
5701           moveList[endPV-1][2] = toX + AAA;
5702           moveList[endPV-1][3] = toY + ONE;
5703           parseList[endPV-1][0] = NULLCHAR;
5704           safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5705         }
5706       }
5707     pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5708     if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5709     if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5710     if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5711         valid++; // allow comments in PV
5712         continue;
5713     }
5714     nr++;
5715     if(endPV+1 > framePtr) break; // no space, truncate
5716     if(!valid) break;
5717     endPV++;
5718     CopyBoard(boards[endPV], boards[endPV-1]);
5719     ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5720     CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5721     strncat(moveList[endPV-1], "\n", MOVE_LEN);
5722     CoordsToAlgebraic(boards[endPV - 1],
5723                              PosFlags(endPV - 1),
5724                              fromY, fromX, toY, toX, promoChar,
5725                              parseList[endPV - 1]);
5726   } while(valid);
5727   if(atEnd == 2) return; // used hidden, for PV conversion
5728   currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5729   if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5730   SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5731                        moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5732   DrawPosition(TRUE, boards[currentMove]);
5733 }
5734
5735 int
5736 MultiPV (ChessProgramState *cps, int kind)
5737 {       // check if engine supports MultiPV, and if so, return the number of the option that sets it
5738         int i;
5739         for(i=0; i<cps->nrOptions; i++) {
5740             char *s = cps->option[i].name;
5741             if((kind & 1) && !StrCaseCmp(s, "MultiPV") && cps->option[i].type == Spin) return i;
5742             if((kind & 2) && StrCaseStr(s, "multi") && StrCaseStr(s, "PV")
5743                           && StrCaseStr(s, "margin") && cps->option[i].type == Spin) return -i-2;
5744         }
5745         return -1;
5746 }
5747
5748 Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
5749 static int multi, pv_margin;
5750 static ChessProgramState *activeCps;
5751
5752 Boolean
5753 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5754 {
5755         int startPV, lineStart, origIndex = index;
5756         char *p, buf2[MSG_SIZ];
5757         ChessProgramState *cps = (pane ? &second : &first);
5758
5759         if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5760         lastX = x; lastY = y;
5761         while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5762         lineStart = startPV = index;
5763         while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5764         if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5765         index = startPV;
5766         do{ while(buf[index] && buf[index] != '\n') index++;
5767         } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5768         buf[index] = 0;
5769         if(lineStart == 0 && gameMode == AnalyzeMode) {
5770             int n = 0;
5771             if(origIndex > 17 && origIndex < 24) n--; else if(origIndex > index - 6) n++;
5772             if(n == 0) { // click not on "fewer" or "more"
5773                 if((multi = -2 - MultiPV(cps, 2)) >= 0) {
5774                     pv_margin = cps->option[multi].value;
5775                     activeCps = cps; // non-null signals margin adjustment
5776                 }
5777             } else if((multi = MultiPV(cps, 1)) >= 0) {
5778                 n += cps->option[multi].value; if(n < 1) n = 1;
5779                 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5780                 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5781                 cps->option[multi].value = n;
5782                 *start = *end = 0;
5783                 return FALSE;
5784             }
5785         } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5786                 ExcludeClick(origIndex - lineStart);
5787                 return FALSE;
5788         } else if(!strncmp(buf+lineStart, "dep\t", 4)) {                // column headers clicked
5789                 Collapse(origIndex - lineStart);
5790                 return FALSE;
5791         }
5792         ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5793         *start = startPV; *end = index-1;
5794         extendGame = (gameMode == AnalyzeMode && appData.autoExtend && origIndex - startPV < 5);
5795         return TRUE;
5796 }
5797
5798 char *
5799 PvToSAN (char *pv)
5800 {
5801         static char buf[10*MSG_SIZ];
5802         int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5803         *buf = NULLCHAR;
5804         if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
5805         ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5806         for(i = forwardMostMove; i<endPV; i++){
5807             if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5808             else    snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5809             k += strlen(buf+k);
5810         }
5811         snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5812         if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
5813         if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5814         endPV = savedEnd;
5815         return buf;
5816 }
5817
5818 Boolean
5819 LoadPV (int x, int y)
5820 { // called on right mouse click to load PV
5821   int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5822   lastX = x; lastY = y;
5823   ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5824   extendGame = FALSE;
5825   return TRUE;
5826 }
5827
5828 void
5829 UnLoadPV ()
5830 {
5831   int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5832   if(activeCps) {
5833     if(pv_margin != activeCps->option[multi].value) {
5834       char buf[MSG_SIZ];
5835       snprintf(buf, MSG_SIZ, "option %s=%d\n", "Multi-PV Margin", pv_margin);
5836       SendToProgram(buf, activeCps);
5837       activeCps->option[multi].value = pv_margin;
5838     }
5839     activeCps = NULL;
5840     return;
5841   }
5842   if(endPV < 0) return;
5843   if(appData.autoCopyPV) CopyFENToClipboard();
5844   endPV = -1;
5845   if(extendGame && currentMove > forwardMostMove) {
5846         Boolean saveAnimate = appData.animate;
5847         if(pushed) {
5848             if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5849                 if(storedGames == 1) GreyRevert(FALSE);      // we already pushed the tail, so just make it official
5850             } else storedGames--; // abandon shelved tail of original game
5851         }
5852         pushed = FALSE;
5853         forwardMostMove = currentMove;
5854         currentMove = oldFMM;
5855         appData.animate = FALSE;
5856         ToNrEvent(forwardMostMove);
5857         appData.animate = saveAnimate;
5858   }
5859   currentMove = forwardMostMove;
5860   if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5861   ClearPremoveHighlights();
5862   DrawPosition(TRUE, boards[currentMove]);
5863 }
5864
5865 void
5866 MovePV (int x, int y, int h)
5867 { // step through PV based on mouse coordinates (called on mouse move)
5868   int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5869
5870   if(activeCps) { // adjusting engine's multi-pv margin
5871     if(x > lastX) pv_margin++; else
5872     if(x < lastX) pv_margin -= (pv_margin > 0);
5873     if(x != lastX) {
5874       char buf[MSG_SIZ];
5875       snprintf(buf, MSG_SIZ, "margin = %d", pv_margin);
5876       DisplayMessage(buf, "");
5877     }
5878     lastX = x;
5879     return;
5880   }
5881   // we must somehow check if right button is still down (might be released off board!)
5882   if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5883   if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5884   if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5885   if(!step) return;
5886   lastX = x; lastY = y;
5887
5888   if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5889   if(endPV < 0) return;
5890   if(y < margin) step = 1; else
5891   if(y > h - margin) step = -1;
5892   if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5893   currentMove += step;
5894   if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5895   SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5896                        moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5897   DrawPosition(FALSE, boards[currentMove]);
5898 }
5899
5900
5901 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5902 // All positions will have equal probability, but the current method will not provide a unique
5903 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5904 #define DARK 1
5905 #define LITE 2
5906 #define ANY 3
5907
5908 int squaresLeft[4];
5909 int piecesLeft[(int)BlackPawn];
5910 int seed, nrOfShuffles;
5911
5912 void
5913 GetPositionNumber ()
5914 {       // sets global variable seed
5915         int i;
5916
5917         seed = appData.defaultFrcPosition;
5918         if(seed < 0) { // randomize based on time for negative FRC position numbers
5919                 for(i=0; i<50; i++) seed += random();
5920                 seed = random() ^ random() >> 8 ^ random() << 8;
5921                 if(seed<0) seed = -seed;
5922         }
5923 }
5924
5925 int
5926 put (Board board, int pieceType, int rank, int n, int shade)
5927 // put the piece on the (n-1)-th empty squares of the given shade
5928 {
5929         int i;
5930
5931         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5932                 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5933                         board[rank][i] = (ChessSquare) pieceType;
5934                         squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5935                         squaresLeft[ANY]--;
5936                         piecesLeft[pieceType]--;
5937                         return i;
5938                 }
5939         }
5940         return -1;
5941 }
5942
5943
5944 void
5945 AddOnePiece (Board board, int pieceType, int rank, int shade)
5946 // calculate where the next piece goes, (any empty square), and put it there
5947 {
5948         int i;
5949
5950         i = seed % squaresLeft[shade];
5951         nrOfShuffles *= squaresLeft[shade];
5952         seed /= squaresLeft[shade];
5953         put(board, pieceType, rank, i, shade);
5954 }
5955
5956 void
5957 AddTwoPieces (Board board, int pieceType, int rank)
5958 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5959 {
5960         int i, n=squaresLeft[ANY], j=n-1, k;
5961
5962         k = n*(n-1)/2; // nr of possibilities, not counting permutations
5963         i = seed % k;  // pick one
5964         nrOfShuffles *= k;
5965         seed /= k;
5966         while(i >= j) i -= j--;
5967         j = n - 1 - j; i += j;
5968         put(board, pieceType, rank, j, ANY);
5969         put(board, pieceType, rank, i, ANY);
5970 }
5971
5972 void
5973 SetUpShuffle (Board board, int number)
5974 {
5975         int i, p, first=1;
5976
5977         GetPositionNumber(); nrOfShuffles = 1;
5978
5979         squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5980         squaresLeft[ANY]  = BOARD_RGHT - BOARD_LEFT;
5981         squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5982
5983         for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5984
5985         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5986             p = (int) board[0][i];
5987             if(p < (int) BlackPawn) piecesLeft[p] ++;
5988             board[0][i] = EmptySquare;
5989         }
5990
5991         if(PosFlags(0) & F_ALL_CASTLE_OK) {
5992             // shuffles restricted to allow normal castling put KRR first
5993             if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5994                 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5995             else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5996                 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5997             if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5998                 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5999             if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
6000                 put(board, WhiteRook, 0, 0, ANY);
6001             // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
6002         }
6003
6004         if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
6005             // only for even boards make effort to put pairs of colorbound pieces on opposite colors
6006             for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
6007                 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
6008                 while(piecesLeft[p] >= 2) {
6009                     AddOnePiece(board, p, 0, LITE);
6010                     AddOnePiece(board, p, 0, DARK);
6011                 }
6012                 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
6013             }
6014
6015         for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
6016             // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
6017             // but we leave King and Rooks for last, to possibly obey FRC restriction
6018             if(p == (int)WhiteRook) continue;
6019             while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
6020             if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY);     // add the odd piece
6021         }
6022
6023         // now everything is placed, except perhaps King (Unicorn) and Rooks
6024
6025         if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
6026             // Last King gets castling rights
6027             while(piecesLeft[(int)WhiteUnicorn]) {
6028                 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
6029                 initialRights[2]  = initialRights[5]  = board[CASTLING][2] = board[CASTLING][5] = i;
6030             }
6031
6032             while(piecesLeft[(int)WhiteKing]) {
6033                 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
6034                 initialRights[2]  = initialRights[5]  = board[CASTLING][2] = board[CASTLING][5] = i;
6035             }
6036
6037
6038         } else {
6039             while(piecesLeft[(int)WhiteKing])    AddOnePiece(board, WhiteKing, 0, ANY);
6040             while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
6041         }
6042
6043         // Only Rooks can be left; simply place them all
6044         while(piecesLeft[(int)WhiteRook]) {
6045                 i = put(board, WhiteRook, 0, 0, ANY);
6046                 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
6047                         if(first) {
6048                                 first=0;
6049                                 initialRights[1]  = initialRights[4]  = board[CASTLING][1] = board[CASTLING][4] = i;
6050                         }
6051                         initialRights[0]  = initialRights[3]  = board[CASTLING][0] = board[CASTLING][3] = i;
6052                 }
6053         }
6054         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
6055             board[BOARD_HEIGHT-1][i] =  (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
6056         }
6057
6058         if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
6059 }
6060
6061 int
6062 ptclen (const char *s, char *escapes)
6063 {
6064     int n = 0;
6065     if(!*escapes) return strlen(s);
6066     while(*s) n += (*s != '/' && *s != '-' && *s != '^' && *s != '*' && !strchr(escapes, *s)) - 2*(*s == '='), s++;
6067     return n;
6068 }
6069
6070 int
6071 SetCharTableEsc (unsigned char *table, const char * map, char * escapes)
6072 /* [HGM] moved here from winboard.c because of its general usefulness */
6073 /*       Basically a safe strcpy that uses the last character as King */
6074 {
6075     int result = FALSE; int NrPieces;
6076     unsigned char partner[EmptySquare];
6077
6078     if( map != NULL && (NrPieces=ptclen(map, escapes)) <= (int) EmptySquare
6079                     && NrPieces >= 12 && !(NrPieces&1)) {
6080         int i, ii, offs, j = 0; /* [HGM] Accept even length from 12 to 88 */
6081
6082         for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
6083         for( i=offs=0; i<NrPieces/2-1; i++ ) {
6084             char *p, c=0;
6085             if(map[j] == '/') offs = WhitePBishop - i, j++;
6086             if(*escapes && (map[j] == '*' || map[j] == '-' || map[j] == '^')) c = map[j++];
6087             table[i+offs] = map[j++];
6088             if(p = strchr(escapes, map[j])) j++, table[i+offs] += 64*(p - escapes + 1);
6089             if(c) partner[i+offs] = table[i+offs], table[i+offs] = c;
6090             if(*escapes && map[j] == '=') pieceNickName[i+offs] = map[++j], j++;
6091         }
6092         table[(int) WhiteKing]  = map[j++];
6093         for( ii=offs=0; ii<NrPieces/2-1; ii++ ) {
6094             char *p, c=0;
6095             if(map[j] == '/') offs = WhitePBishop - ii, j++;
6096             i = WHITE_TO_BLACK ii;
6097             if(*escapes && (map[j] == '*' || map[j] == '-' || map[j] == '^')) c = map[j++];
6098             table[i+offs] = map[j++];
6099             if(p = strchr(escapes, map[j])) j++, table[i+offs] += 64*(p - escapes + 1);
6100             if(c) partner[i+offs] = table[i+offs], table[i+offs] = c;
6101             if(*escapes && map[j] == '=') pieceNickName[i+offs] = map[++j], j++;
6102         }
6103         table[(int) BlackKing]  = map[j++];
6104
6105
6106         if(*escapes) { // set up promotion pairing
6107             for( i=0; i<(int) EmptySquare; i++ ) promoPartner[i] = (i%BlackPawn < 11 ? i + 11 : i%BlackPawn < 22 ? i - 11 : i); // default
6108             // pieceToChar entirely filled, so we can look up specified partners
6109             for(i=0; i<EmptySquare; i++) { // adjust promotion pairing
6110                 int c = table[i];
6111                 if(c == '^' || c == '-') { // has specified partner
6112                     int p;
6113                     for(p=0; p<EmptySquare; p++) if(table[p] == partner[i]) break;
6114                     if(c == '^') table[i] = '+';
6115                     if(p < EmptySquare) {
6116                         if(promoPartner[promoPartner[p]] == p) promoPartner[promoPartner[p]] = promoPartner[p]; // divorce old partners
6117                         if(promoPartner[promoPartner[i]] == i) promoPartner[promoPartner[i]] = promoPartner[i];
6118                         promoPartner[p] = i, promoPartner[i] = p; // and marry this couple
6119                     }
6120                 } else if(c == '*') {
6121                     table[i] = partner[i];
6122                     promoPartner[i] = (i < BlackPawn ? WhiteTokin : BlackTokin); // promotes to Tokin
6123                 }
6124             }
6125         }
6126
6127         result = TRUE;
6128     }
6129
6130     return result;
6131 }
6132
6133 int
6134 SetCharTable (unsigned char *table, const char * map)
6135 {
6136     return SetCharTableEsc(table, map, "");
6137 }
6138
6139 void
6140 Prelude (Board board)
6141 {       // [HGM] superchess: random selection of exo-pieces
6142         int i, j, k; ChessSquare p;
6143         static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
6144
6145         GetPositionNumber(); // use FRC position number
6146
6147         if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
6148             SetCharTable(pieceToChar, appData.pieceToCharTable);
6149             for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
6150                 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
6151         }
6152
6153         j = seed%4;                 seed /= 4;
6154         p = board[0][BOARD_LEFT+j];   board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
6155         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
6156         board[handSize-1-k][0] = WHITE_TO_BLACK p;  board[handSize-1-k][1]++;
6157         j = seed%3 + (seed%3 >= j); seed /= 3;
6158         p = board[0][BOARD_LEFT+j];   board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
6159         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
6160         board[handSize-1-k][0] = WHITE_TO_BLACK p;  board[handSize-1-k][1]++;
6161         j = seed%3;                 seed /= 3;
6162         p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
6163         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
6164         board[handSize-1-k][0] = WHITE_TO_BLACK p;  board[handSize-1-k][1]++;
6165         j = seed%2 + (seed%2 >= j); seed /= 2;
6166         p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
6167         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
6168         board[handSize-1-k][0] = WHITE_TO_BLACK p;  board[handSize-1-k][1]++;
6169         j = seed%4; seed /= 4; put(board, exoPieces[3],    0, j, ANY);
6170         j = seed%3; seed /= 3; put(board, exoPieces[2],   0, j, ANY);
6171         j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
6172         put(board, exoPieces[0],    0, 0, ANY);
6173         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
6174 }
6175
6176 void
6177 InitPosition (int redraw)
6178 {
6179     ChessSquare (* pieces)[BOARD_FILES];
6180     int i, j, pawnRow=1, pieceRows=1, overrule,
6181     oldx = gameInfo.boardWidth,
6182     oldy = gameInfo.boardHeight,
6183     oldh = gameInfo.holdingsWidth;
6184     static int oldv;
6185
6186     if(appData.icsActive) shuffleOpenings = appData.fischerCastling = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
6187
6188     /* [AS] Initialize pv info list [HGM] and game status */
6189     {
6190         for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
6191             pvInfoList[i].depth = 0;
6192             boards[i][EP_STATUS] = EP_NONE;
6193             for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
6194         }
6195
6196         initialRulePlies = 0; /* 50-move counter start */
6197
6198         castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
6199         castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
6200     }
6201
6202
6203     /* [HGM] logic here is completely changed. In stead of full positions */
6204     /* the initialized data only consist of the two backranks. The switch */
6205     /* selects which one we will use, which is than copied to the Board   */
6206     /* initialPosition, which for the rest is initialized by Pawns and    */
6207     /* empty squares. This initial position is then copied to boards[0],  */
6208     /* possibly after shuffling, so that it remains available.            */
6209
6210     gameInfo.holdingsWidth = 0; /* default board sizes */
6211     gameInfo.boardWidth    = 8;
6212     gameInfo.boardHeight   = 8;
6213     gameInfo.holdingsSize  = 0;
6214     nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
6215     for(i=0; i<BOARD_FILES-6; i++)
6216       initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
6217     initialPosition[EP_STATUS] = EP_NONE;
6218     initialPosition[TOUCHED_W] = initialPosition[TOUCHED_B] = 0;
6219     SetCharTableEsc(pieceToChar, "PNBRQ...........Kpnbrq...........k", SUFFIXES);
6220     if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
6221          SetCharTable(pieceNickName, appData.pieceNickNames);
6222     else SetCharTable(pieceNickName, "............");
6223     pieces = FIDEArray;
6224
6225     switch (gameInfo.variant) {
6226     case VariantFischeRandom:
6227       shuffleOpenings = TRUE;
6228       appData.fischerCastling = TRUE;
6229     default:
6230       break;
6231     case VariantShatranj:
6232       pieces = ShatranjArray;
6233       nrCastlingRights = 0;
6234       SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
6235       break;
6236     case VariantMakruk:
6237       pieces = makrukArray;
6238       nrCastlingRights = 0;
6239       SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
6240       break;
6241     case VariantASEAN:
6242       pieces = aseanArray;
6243       nrCastlingRights = 0;
6244       SetCharTable(pieceToChar, "PN.R.Q....BKpn.r.q....bk");
6245       break;
6246     case VariantTwoKings:
6247       pieces = twoKingsArray;
6248       break;
6249     case VariantGrand:
6250       pieces = GrandArray;
6251       nrCastlingRights = 0;
6252       SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6253       gameInfo.boardWidth = 10;
6254       gameInfo.boardHeight = 10;
6255       gameInfo.holdingsSize = 7;
6256       break;
6257     case VariantCapaRandom:
6258       shuffleOpenings = TRUE;
6259       appData.fischerCastling = TRUE;
6260     case VariantCapablanca:
6261       pieces = CapablancaArray;
6262       gameInfo.boardWidth = 10;
6263       SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6264       break;
6265     case VariantGothic:
6266       pieces = GothicArray;
6267       gameInfo.boardWidth = 10;
6268       SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6269       break;
6270     case VariantSChess:
6271       SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
6272       gameInfo.holdingsSize = 7;
6273       for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
6274       break;
6275     case VariantJanus:
6276       pieces = JanusArray;
6277       gameInfo.boardWidth = 10;
6278       SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
6279       nrCastlingRights = 6;
6280         initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6281         initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6282         initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
6283         initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6284         initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6285         initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
6286       break;
6287     case VariantFalcon:
6288       pieces = FalconArray;
6289       gameInfo.boardWidth = 10;
6290       SetCharTable(pieceToChar, "PNBRQ............FKpnbrq............fk");
6291       break;
6292     case VariantXiangqi:
6293       pieces = XiangqiArray;
6294       gameInfo.boardWidth  = 9;
6295       gameInfo.boardHeight = 10;
6296       nrCastlingRights = 0;
6297       SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
6298       break;
6299     case VariantShogi:
6300       pieces = ShogiArray;
6301       gameInfo.boardWidth  = 9;
6302       gameInfo.boardHeight = 9;
6303       gameInfo.holdingsSize = 7;
6304       nrCastlingRights = 0;
6305       SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
6306       break;
6307     case VariantChu:
6308       pieces = ChuArray; pieceRows = 3;
6309       gameInfo.boardWidth  = 12;
6310       gameInfo.boardHeight = 12;
6311       nrCastlingRights = 0;
6312 //      SetCharTableEsc(pieceToChar, "P.BRQSEXOGCATHD.VMLIFN.........^T..^L......^A^H/^F^G^M.^E^X^O^I.^P.^B^R..^D^S^C^VK"
6313   //                                 "p.brqsexogcathd.vmlifn.........^t..^l......^a^h/^f^g^m.^e^x^o^i.^p.^b^r..^d^s^c^vk", SUFFIXES);
6314       SetCharTableEsc(pieceToChar, "P.BRQSEXOG...HD..^DLI^HNV........^T..^L.C...A^AFT/^F^G^M.^E^X^O^I.^P.^B^R..M^S^C^VK"
6315                                    "p.brqsexog...hd..^dli^hnv........^t..^l.c...a^aft/^f^g^m.^e^x^o^i.^p.^b^r..m^s^c^vk", SUFFIXES);
6316       break;
6317     case VariantCourier:
6318       pieces = CourierArray;
6319       gameInfo.boardWidth  = 12;
6320       nrCastlingRights = 0;
6321       SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
6322       break;
6323     case VariantKnightmate:
6324       pieces = KnightmateArray;
6325       SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
6326       break;
6327     case VariantSpartan:
6328       pieces = SpartanArray;
6329       SetCharTable(pieceToChar, "PNBRQ.....................K......lw......g...h......ck");
6330       break;
6331     case VariantLion:
6332       pieces = lionArray;
6333       SetCharTable(pieceToChar, "PNBRQ................LKpnbrq................lk");
6334       break;
6335     case VariantChuChess:
6336       pieces = ChuChessArray;
6337       gameInfo.boardWidth = 10;
6338       gameInfo.boardHeight = 10;
6339       SetCharTable(pieceToChar, "PNBRQ.....M.+++......LKpnbrq.....m.+++......lk");
6340       break;
6341     case VariantFairy:
6342       pieces = fairyArray;
6343       SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
6344       break;
6345     case VariantGreat:
6346       pieces = GreatArray;
6347       gameInfo.boardWidth = 10;
6348       SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
6349       gameInfo.holdingsSize = 8;
6350       break;
6351     case VariantSuper:
6352       pieces = FIDEArray;
6353       SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
6354       gameInfo.holdingsSize = 8;
6355       startedFromSetupPosition = TRUE;
6356       break;
6357     case VariantCrazyhouse:
6358     case VariantBughouse:
6359       pieces = FIDEArray;
6360       SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
6361       gameInfo.holdingsSize = 5;
6362       break;
6363     case VariantWildCastle:
6364       pieces = FIDEArray;
6365       /* !!?shuffle with kings guaranteed to be on d or e file */
6366       shuffleOpenings = 1;
6367       break;
6368     case VariantNoCastle:
6369       /* !!?unconstrained back-rank shuffle */
6370       shuffleOpenings = 1;
6371     case VariantSuicide:
6372       pieces = FIDEArray;
6373       nrCastlingRights = 0;
6374       break;
6375     }
6376
6377     overrule = 0;
6378     if(appData.NrFiles >= 0) {
6379         if(gameInfo.boardWidth != appData.NrFiles) overrule++;
6380         gameInfo.boardWidth = appData.NrFiles;
6381     }
6382     if(appData.NrRanks >= 0) {
6383         gameInfo.boardHeight = appData.NrRanks;
6384     }
6385     if(appData.holdingsSize >= 0) {
6386         i = appData.holdingsSize;
6387 //        if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
6388         gameInfo.holdingsSize = i;
6389     }
6390     if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
6391     if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
6392         DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
6393
6394     if(!handSize) handSize = BOARD_HEIGHT;
6395     pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
6396     if(pawnRow < 1) pawnRow = 1;
6397     if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN ||
6398        gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) pawnRow = 2;
6399     if(gameInfo.variant == VariantChu) pawnRow = 3;
6400
6401     /* User pieceToChar list overrules defaults */
6402     if(appData.pieceToCharTable != NULL)
6403         SetCharTableEsc(pieceToChar, appData.pieceToCharTable, SUFFIXES);
6404
6405     for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
6406
6407         if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
6408             s = (ChessSquare) 0; /* account holding counts in guard band */
6409         for( i=0; i<BOARD_HEIGHT; i++ )
6410             initialPosition[i][j] = s;
6411
6412         if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6413         initialPosition[gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess][j] = pieces[0][j-gameInfo.holdingsWidth];
6414         initialPosition[pawnRow][j] = WhitePawn;
6415         initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6416         if(gameInfo.variant == VariantXiangqi) {
6417             if(j&1) {
6418                 initialPosition[pawnRow][j] =
6419                 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6420                 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6421                    initialPosition[2][j] = WhiteCannon;
6422                    initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6423                 }
6424             }
6425         }
6426         if(gameInfo.variant == VariantChu) {
6427              if(j == (BOARD_WIDTH-2)/3 || j == BOARD_WIDTH - (BOARD_WIDTH+1)/3)
6428                initialPosition[pawnRow+1][j] = WhiteCobra,
6429                initialPosition[BOARD_HEIGHT-pawnRow-2][j] = BlackCobra;
6430              for(i=1; i<pieceRows; i++) {
6431                initialPosition[i][j] = pieces[2*i][j-gameInfo.holdingsWidth];
6432                initialPosition[BOARD_HEIGHT-1-i][j] =  pieces[2*i+1][j-gameInfo.holdingsWidth];
6433              }
6434         }
6435         if(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6436             if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6437                initialPosition[0][j] = WhiteRook;
6438                initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6439             }
6440         }
6441         initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess)][j] =  pieces[1][j-gameInfo.holdingsWidth];
6442     }
6443     if(gameInfo.variant == VariantChuChess) initialPosition[0][BOARD_WIDTH/2] = WhiteKing, initialPosition[BOARD_HEIGHT-1][BOARD_WIDTH/2-1] = BlackKing;
6444     if( (gameInfo.variant == VariantShogi) && !overrule ) {
6445
6446             j=BOARD_LEFT+1;
6447             initialPosition[1][j] = WhiteBishop;
6448             initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6449             j=BOARD_RGHT-2;
6450             initialPosition[1][j] = WhiteRook;
6451             initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6452     }
6453
6454     if( nrCastlingRights == -1) {
6455         /* [HGM] Build normal castling rights (must be done after board sizing!) */
6456         /*       This sets default castling rights from none to normal corners   */
6457         /* Variants with other castling rights must set them themselves above    */
6458         nrCastlingRights = 6;
6459
6460         initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6461         initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6462         initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6463         initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6464         initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6465         initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6466      }
6467
6468      if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6469      if(gameInfo.variant == VariantGreat) { // promotion commoners
6470         initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6471         initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6472         initialPosition[handSize-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6473         initialPosition[handSize-1-PieceToNumber(WhiteMan)][1] = 9;
6474      }
6475      if( gameInfo.variant == VariantSChess ) {
6476       initialPosition[1][0] = BlackMarshall;
6477       initialPosition[2][0] = BlackAngel;
6478       initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6479       initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6480       initialPosition[1][1] = initialPosition[2][1] =
6481       initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6482      }
6483      initialPosition[CHECK_COUNT] = (gameInfo.variant == Variant3Check ? 0x303 : 0);
6484   if (appData.debugMode) {
6485     fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6486   }
6487     if(shuffleOpenings) {
6488         SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6489         startedFromSetupPosition = TRUE;
6490     }
6491     if(startedFromPositionFile) {
6492       /* [HGM] loadPos: use PositionFile for every new game */
6493       CopyBoard(initialPosition, filePosition);
6494       for(i=0; i<nrCastlingRights; i++)
6495           initialRights[i] = filePosition[CASTLING][i];
6496       startedFromSetupPosition = TRUE;
6497     }
6498     if(*appData.men) LoadPieceDesc(appData.men);
6499
6500     CopyBoard(boards[0], initialPosition);
6501
6502     if(oldx != gameInfo.boardWidth ||
6503        oldy != gameInfo.boardHeight ||
6504        oldv != gameInfo.variant ||
6505        oldh != gameInfo.holdingsWidth
6506                                          )
6507             InitDrawingSizes(-2 ,0);
6508
6509     oldv = gameInfo.variant;
6510     if (redraw)
6511       DrawPosition(TRUE, boards[currentMove]);
6512 }
6513
6514 void
6515 SendBoard (ChessProgramState *cps, int moveNum)
6516 {
6517     char message[MSG_SIZ];
6518
6519     if (cps->useSetboard) {
6520       char* fen = PositionToFEN(moveNum, cps->fenOverride, 1);
6521       snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6522       SendToProgram(message, cps);
6523       free(fen);
6524
6525     } else {
6526       ChessSquare *bp;
6527       int i, j, left=0, right=BOARD_WIDTH;
6528       /* Kludge to set black to move, avoiding the troublesome and now
6529        * deprecated "black" command.
6530        */
6531       if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6532         SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn && !pieceDesc[WhitePawn] ? "a2a3\n" : "black\nforce\n", cps);
6533
6534       if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6535
6536       SendToProgram("edit\n", cps);
6537       SendToProgram("#\n", cps);
6538       for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6539         bp = &boards[moveNum][i][left];
6540         for (j = left; j < right; j++, bp++) {
6541           if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6542           if ((int) *bp < (int) BlackPawn) {
6543             if(j == BOARD_RGHT+1)
6544                  snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6545             else snprintf(message, MSG_SIZ, "%c%c%d\n", PieceToChar(*bp), AAA + j, ONE + i - '0');
6546             if(message[0] == '+' || message[0] == '~') {
6547               snprintf(message, MSG_SIZ,"%c%c%d+\n",
6548                         PieceToChar((ChessSquare)(DEMOTED(*bp))),
6549                         AAA + j, ONE + i - '0');
6550             }
6551             if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6552                 message[1] = BOARD_RGHT   - 1 - j + '1';
6553                 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6554             }
6555             SendToProgram(message, cps);
6556           }
6557         }
6558       }
6559
6560       SendToProgram("c\n", cps);
6561       for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6562         bp = &boards[moveNum][i][left];
6563         for (j = left; j < right; j++, bp++) {
6564           if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6565           if (((int) *bp != (int) EmptySquare)
6566               && ((int) *bp >= (int) BlackPawn)) {
6567             if(j == BOARD_LEFT-2)
6568                  snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6569             else snprintf(message,MSG_SIZ, "%c%c%d\n", ToUpper(PieceToChar(*bp)),
6570                     AAA + j, ONE + i - '0');
6571             if(message[0] == '+' || message[0] == '~') {
6572               snprintf(message, MSG_SIZ,"%c%c%d+\n",
6573                         PieceToChar((ChessSquare)(DEMOTED(*bp))),
6574                         AAA + j, ONE + i - '0');
6575             }
6576             if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6577                 message[1] = BOARD_RGHT   - 1 - j + '1';
6578                 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6579             }
6580             SendToProgram(message, cps);
6581           }
6582         }
6583       }
6584
6585       SendToProgram(".\n", cps);
6586     }
6587     setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6588 }
6589
6590 char exclusionHeader[MSG_SIZ];
6591 int exCnt, excludePtr;
6592 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6593 static Exclusion excluTab[200];
6594 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6595
6596 static void
6597 WriteMap (int s)
6598 {
6599     int j;
6600     for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6601     exclusionHeader[19] = s ? '-' : '+'; // update tail state
6602 }
6603
6604 static void
6605 ClearMap ()
6606 {
6607     safeStrCpy(exclusionHeader, "exclude: none best +tail                                          \n", MSG_SIZ);
6608     excludePtr = 24; exCnt = 0;
6609     WriteMap(0);
6610 }
6611
6612 static void
6613 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6614 {   // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6615     char buf[2*MOVE_LEN], *p;
6616     Exclusion *e = excluTab;
6617     int i;
6618     for(i=0; i<exCnt; i++)
6619         if(e[i].ff == fromX && e[i].fr == fromY &&
6620            e[i].tf == toX   && e[i].tr == toY && e[i].pc == promoChar) break;
6621     if(i == exCnt) { // was not in exclude list; add it
6622         CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6623         if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6624             if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6625             return; // abort
6626         }
6627         e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6628         excludePtr++; e[i].mark = excludePtr++;
6629         for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6630         exCnt++;
6631     }
6632     exclusionHeader[e[i].mark] = state;
6633 }
6634
6635 static int
6636 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6637 {   // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6638     char buf[MSG_SIZ];
6639     int j, k;
6640     ChessMove moveType;
6641     if((signed char)promoChar == -1) { // kludge to indicate best move
6642         if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6643             return 1; // if unparsable, abort
6644     }
6645     // update exclusion map (resolving toggle by consulting existing state)
6646     k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6647     j = k%8; k >>= 3;
6648     if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6649     if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6650          excludeMap[k] |=   1<<j;
6651     else excludeMap[k] &= ~(1<<j);
6652     // update header
6653     UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6654     // inform engine
6655     snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6656     CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6657     SendToBoth(buf);
6658     return (state == '+');
6659 }
6660
6661 static void
6662 ExcludeClick (int index)
6663 {
6664     int i, j;
6665     Exclusion *e = excluTab;
6666     if(index < 25) { // none, best or tail clicked
6667         if(index < 13) { // none: include all
6668             WriteMap(0); // clear map
6669             for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6670             SendToBoth("include all\n"); // and inform engine
6671         } else if(index > 18) { // tail
6672             if(exclusionHeader[19] == '-') { // tail was excluded
6673                 SendToBoth("include all\n");
6674                 WriteMap(0); // clear map completely
6675                 // now re-exclude selected moves
6676                 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6677                     ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6678             } else { // tail was included or in mixed state
6679                 SendToBoth("exclude all\n");
6680                 WriteMap(0xFF); // fill map completely
6681                 // now re-include selected moves
6682                 j = 0; // count them
6683                 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6684                     ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6685                 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6686             }
6687         } else { // best
6688             ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6689         }
6690     } else {
6691         for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6692             char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6693             ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6694             break;
6695         }
6696     }
6697 }
6698
6699 ChessSquare
6700 DefaultPromoChoice (int white)
6701 {
6702     ChessSquare result;
6703     if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6704        gameInfo.variant == VariantMakruk)
6705         result = WhiteFerz; // no choice
6706     else if(gameInfo.variant == VariantASEAN)
6707         result = WhiteRook; // no choice
6708     else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6709         result= WhiteKing; // in Suicide Q is the last thing we want
6710     else if(gameInfo.variant == VariantSpartan)
6711         result = white ? WhiteQueen : WhiteAngel;
6712     else result = WhiteQueen;
6713     if(!white) result = WHITE_TO_BLACK result;
6714     return result;
6715 }
6716
6717 static int autoQueen; // [HGM] oneclick
6718
6719 int
6720 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6721 {
6722     /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6723     /* [HGM] add Shogi promotions */
6724     int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6725     ChessSquare piece, partner;
6726     ChessMove moveType;
6727     Boolean premove;
6728
6729     if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6730     if(toX   < BOARD_LEFT || toX   >= BOARD_RGHT) return FALSE; // move into holdings
6731
6732     if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6733       !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6734         return FALSE;
6735
6736     if(legal[toY][toX] == 4) return FALSE;
6737
6738     piece = boards[currentMove][fromY][fromX];
6739     if(gameInfo.variant == VariantChu) {
6740         promotionZoneSize = (BOARD_HEIGHT - deadRanks)/3;
6741         if(legal[toY][toX] == 6) return FALSE; // no promotion if highlights deny it
6742         highestPromotingPiece = (PieceToChar(piece) == '+' || PieceToChar(CHUPROMOTED(piece)) != '+') ? WhitePawn : WhiteKing;
6743     } else if(gameInfo.variant == VariantShogi) {
6744         promotionZoneSize = (BOARD_HEIGHT- deadRanks)/3 +(BOARD_HEIGHT == 8);
6745         highestPromotingPiece = (int)WhiteAlfil;
6746         if(PieceToChar(piece) != '+' || PieceToChar(CHUPROMOTED(piece)) == '+') highestPromotingPiece = piece;
6747     } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6748         promotionZoneSize = 3;
6749     }
6750
6751     // Treat Lance as Pawn when it is not representing Amazon or Lance
6752     if(gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu) {
6753         if(piece == WhiteLance) piece = WhitePawn; else
6754         if(piece == BlackLance) piece = BlackPawn;
6755     }
6756
6757     // next weed out all moves that do not touch the promotion zone at all
6758     if((int)piece >= BlackPawn) {
6759         if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6760              return FALSE;
6761         if(fromY < promotionZoneSize && gameInfo.variant == VariantChuChess) return FALSE;
6762         highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6763     } else {
6764         if(  toY < BOARD_HEIGHT - deadRanks - promotionZoneSize &&
6765            fromY < BOARD_HEIGHT - deadRanks - promotionZoneSize) return FALSE;
6766         if(fromY >= BOARD_HEIGHT - deadRanks - promotionZoneSize && gameInfo.variant == VariantChuChess)
6767              return FALSE;
6768     }
6769
6770     if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6771
6772     // weed out mandatory Shogi promotions
6773     if(gameInfo.variant == VariantShogi) {
6774         if(piece >= BlackPawn) {
6775             if(toY == 0 && piece == BlackPawn ||
6776                toY == 0 && piece == BlackQueen ||
6777                toY <= 1 && piece == BlackKnight) {
6778                 *promoChoice = '+';
6779                 return FALSE;
6780             }
6781         } else {
6782             if(toY == BOARD_HEIGHT-deadRanks-1 && piece == WhitePawn ||
6783                toY == BOARD_HEIGHT-deadRanks-1 && piece == WhiteQueen ||
6784                toY >= BOARD_HEIGHT-deadRanks-2 && piece == WhiteKnight) {
6785                 *promoChoice = '+';
6786                 return FALSE;
6787             }
6788         }
6789     }
6790
6791     // weed out obviously illegal Pawn moves
6792     if(appData.testLegality  && (piece == WhitePawn || piece == BlackPawn) ) {
6793         if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6794         if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6795         if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6796         if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6797         // note we are not allowed to test for valid (non-)capture, due to premove
6798     }
6799
6800     // we either have a choice what to promote to, or (in Shogi) whether to promote
6801     if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6802        gameInfo.variant == VariantMakruk) {
6803         ChessSquare p=BlackFerz;  // no choice
6804         while(p < EmptySquare) {  //but make sure we use piece that exists
6805             *promoChoice = PieceToChar(p++);
6806             if(*promoChoice != '.') break;
6807         }
6808         if(!*engineVariant) return FALSE; // if used as parent variant there might be promotion choice
6809     }
6810     // no sense asking what we must promote to if it is going to explode...
6811     if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6812         *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6813         return FALSE;
6814     }
6815     // give caller the default choice even if we will not make it
6816     *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6817     partner = piece; // pieces can promote if the pieceToCharTable says so
6818     if(IS_SHOGI(gameInfo.variant)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? '=' : '+'); // obsolete?
6819     else if(Partner(&partner))     *promoChoice = (defaultPromoChoice == piece && sweepSelect ? NULLCHAR : '+');
6820     if(        sweepSelect && gameInfo.variant != VariantGreat
6821                            && gameInfo.variant != VariantGrand
6822                            && gameInfo.variant != VariantSuper) return FALSE;
6823     if(autoQueen) return FALSE; // predetermined
6824
6825     // suppress promotion popup on illegal moves that are not premoves
6826     premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6827               gameMode == IcsPlayingBlack &&  WhiteOnMove(currentMove);
6828     if(appData.testLegality && !premove) {
6829         moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6830                         fromY, fromX, toY, toX, IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantChuChess ? '+' : NULLCHAR);
6831         if(moveType == IllegalMove) *promoChoice = NULLCHAR; // could be the fact we promoted was illegal
6832         if(moveType != WhitePromotion && moveType  != BlackPromotion)
6833             return FALSE;
6834     }
6835
6836     return TRUE;
6837 }
6838
6839 int
6840 InPalace (int row, int column)
6841 {   /* [HGM] for Xiangqi */
6842     if( (row < 3 || row > BOARD_HEIGHT-4) &&
6843          column < (BOARD_WIDTH + 4)/2 &&
6844          column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6845     return FALSE;
6846 }
6847
6848 int
6849 PieceForSquare (int x, int y)
6850 {
6851   if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT) return -1;
6852   if(x == BOARD_RGHT+1 && handOffsets & 1) y += handSize - BOARD_HEIGHT;
6853   if(x == BOARD_LEFT-2 && !(handOffsets & 2)) y += handSize - BOARD_HEIGHT;
6854      return boards[currentMove][y][x];
6855 }
6856
6857 ChessSquare
6858 More (Board board, int col, int start, int end)
6859 {
6860     int k;
6861     for(k=start; k<end; k++) if(board[k][col]) return (col == 1 ? WhiteMonarch : BlackMonarch); // arrow image
6862     return EmptySquare;
6863 }
6864
6865 void
6866 DrawPosition (int repaint, Board board)
6867 {
6868     Board compactedBoard;
6869     if(handSize > BOARD_HEIGHT && board) {
6870         int k;
6871         CopyBoard(compactedBoard, board);
6872         if(handOffsets & 1) {
6873             for(k=0; k<BOARD_HEIGHT; k++) {
6874                 compactedBoard[k][BOARD_WIDTH-1] = board[k+handSize-BOARD_HEIGHT][BOARD_WIDTH-1];
6875                 compactedBoard[k][BOARD_WIDTH-2] = board[k+handSize-BOARD_HEIGHT][BOARD_WIDTH-2];
6876             }
6877             compactedBoard[0][BOARD_WIDTH-1] = More(board, BOARD_WIDTH-2, 0, handSize-BOARD_HEIGHT+1);
6878         } else compactedBoard[BOARD_HEIGHT-1][BOARD_WIDTH-1] = More(board, BOARD_WIDTH-2, BOARD_HEIGHT-1, handSize);
6879         if(!(handOffsets & 2)) {
6880             for(k=0; k<BOARD_HEIGHT; k++) {
6881                 compactedBoard[k][0] = board[k+handSize-BOARD_HEIGHT][0];
6882                 compactedBoard[k][1] = board[k+handSize-BOARD_HEIGHT][1];
6883             }
6884             compactedBoard[0][0] = More(board, 1, 0, handSize-BOARD_HEIGHT+1);
6885         } else compactedBoard[BOARD_HEIGHT-1][0] = More(board, 1, BOARD_HEIGHT-1, handSize);
6886         DrawPositionX(TRUE, compactedBoard);
6887     } else DrawPositionX(repaint, board);
6888 }
6889
6890 int
6891 OKToStartUserMove (int x, int y)
6892 {
6893     ChessSquare from_piece;
6894     int white_piece;
6895
6896     if (matchMode) return FALSE;
6897     if (gameMode == EditPosition) return TRUE;
6898
6899     if (x >= 0 && y >= 0)
6900       from_piece = boards[currentMove][y][x];
6901     else
6902       from_piece = EmptySquare;
6903
6904     if (from_piece == EmptySquare) return FALSE;
6905
6906     white_piece = (int)from_piece >= (int)WhitePawn &&
6907       (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6908
6909     switch (gameMode) {
6910       case AnalyzeFile:
6911       case TwoMachinesPlay:
6912       case EndOfGame:
6913         return FALSE;
6914
6915       case IcsObserving:
6916       case IcsIdle:
6917         return FALSE;
6918
6919       case MachinePlaysWhite:
6920       case IcsPlayingBlack:
6921         if (appData.zippyPlay) return FALSE;
6922         if (white_piece) {
6923             DisplayMoveError(_("You are playing Black"));
6924             return FALSE;
6925         }
6926         break;
6927
6928       case MachinePlaysBlack:
6929       case IcsPlayingWhite:
6930         if (appData.zippyPlay) return FALSE;
6931         if (!white_piece) {
6932             DisplayMoveError(_("You are playing White"));
6933             return FALSE;
6934         }
6935         break;
6936
6937       case PlayFromGameFile:
6938             if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6939       case EditGame:
6940       case AnalyzeMode:
6941         if (!white_piece && WhiteOnMove(currentMove)) {
6942             DisplayMoveError(_("It is White's turn"));
6943             return FALSE;
6944         }
6945         if (white_piece && !WhiteOnMove(currentMove)) {
6946             DisplayMoveError(_("It is Black's turn"));
6947             return FALSE;
6948         }
6949         if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6950             /* Editing correspondence game history */
6951             /* Could disallow this or prompt for confirmation */
6952             cmailOldMove = -1;
6953         }
6954         break;
6955
6956       case BeginningOfGame:
6957         if (appData.icsActive) return FALSE;
6958         if (!appData.noChessProgram) {
6959             if (!white_piece) {
6960                 DisplayMoveError(_("You are playing White"));
6961                 return FALSE;
6962             }
6963         }
6964         break;
6965
6966       case Training:
6967         if (!white_piece && WhiteOnMove(currentMove)) {
6968             DisplayMoveError(_("It is White's turn"));
6969             return FALSE;
6970         }
6971         if (white_piece && !WhiteOnMove(currentMove)) {
6972             DisplayMoveError(_("It is Black's turn"));
6973             return FALSE;
6974         }
6975         break;
6976
6977       default:
6978       case IcsExamining:
6979         break;
6980     }
6981     if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6982         && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6983         && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6984         && gameMode != AnalyzeFile && gameMode != Training) {
6985         DisplayMoveError(_("Displayed position is not current"));
6986         return FALSE;
6987     }
6988     return TRUE;
6989 }
6990
6991 Boolean
6992 OnlyMove (int *x, int *y, Boolean captures)
6993 {
6994     DisambiguateClosure cl;
6995     if (appData.zippyPlay || !appData.testLegality) return FALSE;
6996     switch(gameMode) {
6997       case MachinePlaysBlack:
6998       case IcsPlayingWhite:
6999       case BeginningOfGame:
7000         if(!WhiteOnMove(currentMove)) return FALSE;
7001         break;
7002       case MachinePlaysWhite:
7003       case IcsPlayingBlack:
7004         if(WhiteOnMove(currentMove)) return FALSE;
7005         break;
7006       case EditGame:
7007         break;
7008       default:
7009         return FALSE;
7010     }
7011     cl.pieceIn = EmptySquare;
7012     cl.rfIn = *y;
7013     cl.ffIn = *x;
7014     cl.rtIn = -1;
7015     cl.ftIn = -1;
7016     cl.promoCharIn = NULLCHAR;
7017     Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
7018     if( cl.kind == NormalMove ||
7019         cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
7020         cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
7021         cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
7022       fromX = cl.ff;
7023       fromY = cl.rf;
7024       *x = cl.ft;
7025       *y = cl.rt;
7026       return TRUE;
7027     }
7028     if(cl.kind != ImpossibleMove) return FALSE;
7029     cl.pieceIn = EmptySquare;
7030     cl.rfIn = -1;
7031     cl.ffIn = -1;
7032     cl.rtIn = *y;
7033     cl.ftIn = *x;
7034     cl.promoCharIn = NULLCHAR;
7035     Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
7036     if( cl.kind == NormalMove ||
7037         cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
7038         cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
7039         cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
7040       fromX = cl.ff;
7041       fromY = cl.rf;
7042       *x = cl.ft;
7043       *y = cl.rt;
7044       autoQueen = TRUE; // act as if autoQueen on when we click to-square
7045       return TRUE;
7046     }
7047     return FALSE;
7048 }
7049
7050 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
7051 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
7052 int lastLoadGameUseList = FALSE;
7053 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
7054 ChessMove lastLoadGameStart = EndOfFile;
7055 int doubleClick;
7056 Boolean addToBookFlag;
7057 static Board rightsBoard, nullBoard;
7058
7059 void
7060 UserMoveEvent (int fromX, int fromY, int toX, int toY, int promoChar)
7061 {
7062     ChessMove moveType;
7063     ChessSquare pup;
7064     int ff=fromX, rf=fromY, ft=toX, rt=toY;
7065
7066     /* Check if the user is playing in turn.  This is complicated because we
7067        let the user "pick up" a piece before it is his turn.  So the piece he
7068        tried to pick up may have been captured by the time he puts it down!
7069        Therefore we use the color the user is supposed to be playing in this
7070        test, not the color of the piece that is currently on the starting
7071        square---except in EditGame mode, where the user is playing both
7072        sides; fortunately there the capture race can't happen.  (It can
7073        now happen in IcsExamining mode, but that's just too bad.  The user
7074        will get a somewhat confusing message in that case.)
7075        */
7076
7077     switch (gameMode) {
7078       case AnalyzeFile:
7079       case TwoMachinesPlay:
7080       case EndOfGame:
7081       case IcsObserving:
7082       case IcsIdle:
7083         /* We switched into a game mode where moves are not accepted,
7084            perhaps while the mouse button was down. */
7085         return;
7086
7087       case MachinePlaysWhite:
7088         /* User is moving for Black */
7089         if (WhiteOnMove(currentMove)) {
7090             DisplayMoveError(_("It is White's turn"));
7091             return;
7092         }
7093         break;
7094
7095       case MachinePlaysBlack:
7096         /* User is moving for White */
7097         if (!WhiteOnMove(currentMove)) {
7098             DisplayMoveError(_("It is Black's turn"));
7099             return;
7100         }
7101         break;
7102
7103       case PlayFromGameFile:
7104             if(!shiftKey ||!appData.variations) return; // [HGM] only variations
7105       case EditGame:
7106       case IcsExamining:
7107       case BeginningOfGame:
7108       case AnalyzeMode:
7109       case Training:
7110         if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
7111         if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
7112             (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
7113             /* User is moving for Black */
7114             if (WhiteOnMove(currentMove)) {
7115                 DisplayMoveError(_("It is White's turn"));
7116                 return;
7117             }
7118         } else {
7119             /* User is moving for White */
7120             if (!WhiteOnMove(currentMove)) {
7121                 DisplayMoveError(_("It is Black's turn"));
7122                 return;
7123             }
7124         }
7125         break;
7126
7127       case IcsPlayingBlack:
7128         /* User is moving for Black */
7129         if (WhiteOnMove(currentMove)) {
7130             if (!appData.premove) {
7131                 DisplayMoveError(_("It is White's turn"));
7132             } else if (toX >= 0 && toY >= 0) {
7133                 premoveToX = toX;
7134                 premoveToY = toY;
7135                 premoveFromX = fromX;
7136                 premoveFromY = fromY;
7137                 premovePromoChar = promoChar;
7138                 gotPremove = 1;
7139                 if (appData.debugMode)
7140                     fprintf(debugFP, "Got premove: fromX %d,"
7141                             "fromY %d, toX %d, toY %d\n",
7142                             fromX, fromY, toX, toY);
7143             }
7144             DrawPosition(TRUE, boards[currentMove]); // [HGM] repair animation damage done by premove (in particular emptying from-square)
7145             return;
7146         }
7147         break;
7148
7149       case IcsPlayingWhite:
7150         /* User is moving for White */
7151         if (!WhiteOnMove(currentMove)) {
7152             if (!appData.premove) {
7153                 DisplayMoveError(_("It is Black's turn"));
7154             } else if (toX >= 0 && toY >= 0) {
7155                 premoveToX = toX;
7156                 premoveToY = toY;
7157                 premoveFromX = fromX;
7158                 premoveFromY = fromY;
7159                 premovePromoChar = promoChar;
7160                 gotPremove = 1;
7161                 if (appData.debugMode)
7162                     fprintf(debugFP, "Got premove: fromX %d,"
7163                             "fromY %d, toX %d, toY %d\n",
7164                             fromX, fromY, toX, toY);
7165             }
7166             DrawPosition(TRUE, boards[currentMove]);
7167             return;
7168         }
7169         break;
7170
7171       default:
7172         break;
7173
7174       case EditPosition:
7175         /* EditPosition, empty square, or different color piece;
7176            click-click move is possible */
7177         if (toX == -2 || toY == -2) {
7178             boards[0][fromY][fromX] = (boards[0][fromY][fromX] == EmptySquare ? DarkSquare : EmptySquare);
7179             DrawPosition(FALSE, boards[currentMove]);
7180             return;
7181         } else if (toX >= 0 && toY >= 0) {
7182             if(!appData.pieceMenu && toX == fromX && toY == fromY && boards[0][rf][ff] != EmptySquare) {
7183                 ChessSquare p = boards[0][rf][ff];
7184                 if(PieceToChar(p) == '+') gatingPiece = CHUDEMOTED(p); else
7185                 if(PieceToChar(CHUPROMOTED(p)) =='+') gatingPiece = CHUPROMOTED(p); else
7186                 if(p == WhiteKing || p == BlackKing || p == WhiteRook || p == BlackRook || p == WhitePawn || p == BlackPawn) {
7187                     int n = rightsBoard[toY][toX] ^= 1; // toggle virginity of K or R
7188                     DisplayMessage("", n ? _("rights granted") : _("rights revoked"));
7189                     gatingPiece = p;
7190                 }
7191             } else  rightsBoard[toY][toX] = 0;  // revoke rights on moving
7192             boards[0][toY][toX] = boards[0][fromY][fromX];
7193             if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
7194                 if(boards[0][fromY][0] != EmptySquare) {
7195                     if(boards[0][fromY][1]) boards[0][fromY][1]--;
7196                     if(boards[0][fromY][1] == 0)  boards[0][fromY][0] = EmptySquare;
7197                 }
7198             } else
7199             if(fromX == BOARD_RGHT+1) {
7200                 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
7201                     if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
7202                     if(boards[0][fromY][BOARD_WIDTH-2] == 0)  boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
7203                 }
7204             } else
7205             boards[0][fromY][fromX] = gatingPiece;
7206             ClearHighlights();
7207             DrawPosition(FALSE, boards[currentMove]);
7208             return;
7209         }
7210         return;
7211     }
7212
7213     if((toX < 0 || toY < 0) && (fromY != DROP_RANK || fromX != EmptySquare)) return;
7214     pup = boards[currentMove][toY][toX];
7215
7216     /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
7217     if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
7218          if( pup != EmptySquare ) return;
7219          moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
7220            if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
7221                 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
7222            // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
7223            if(fromX == 0) fromY = handSize-1 - fromY; // black holdings upside-down
7224            fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
7225            while(PieceToChar(fromX) == '.' || PieceToChar(fromX) == '+' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
7226          fromY = DROP_RANK;
7227     }
7228
7229     /* [HGM] always test for legality, to get promotion info */
7230     moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
7231                                          fromY, fromX, toY, toX, promoChar);
7232
7233     if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame || PosFlags(0) & F_NULL_MOVE)) moveType = NormalMove;
7234
7235     if(moveType == IllegalMove && legal[toY][toX] > 1) moveType = NormalMove; // someone explicitly told us this move is legal
7236
7237     /* [HGM] but possibly ignore an IllegalMove result */
7238     if (appData.testLegality) {
7239         if (moveType == IllegalMove || moveType == ImpossibleMove) {
7240             DisplayMoveError(_("Illegal move"));
7241             return;
7242         }
7243     }
7244
7245     if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
7246         if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
7247              ClearPremoveHighlights(); // was included
7248         else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated  by premove highlights
7249         DrawPosition(FALSE, NULL);
7250         return;
7251     }
7252
7253     if(addToBookFlag) { // adding moves to book
7254         char buf[MSG_SIZ], move[MSG_SIZ];
7255         CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, move);
7256         if(killX >= 0) snprintf(move, MSG_SIZ, "%c%dx%c%d-%c%d%c", fromX + AAA, fromY + ONE - '0',
7257                                                                    killX + AAA, killY + ONE - '0', toX + AAA, toY + ONE - '0', promoChar);
7258         snprintf(buf, MSG_SIZ, "  0.0%%     1  %s\n", move);
7259         AddBookMove(buf);
7260         addToBookFlag = FALSE;
7261         ClearHighlights();
7262         return;
7263     }
7264
7265     FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
7266 }
7267
7268 /* Common tail of UserMoveEvent and DropMenuEvent */
7269 int
7270 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
7271 {
7272     char *bookHit = 0;
7273
7274     if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
7275         // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
7276         int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
7277         if(WhiteOnMove(currentMove)) {
7278             if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
7279         } else {
7280             if(!boards[currentMove][handSize-1-k][1]) return 0;
7281         }
7282     }
7283
7284     /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
7285        move type in caller when we know the move is a legal promotion */
7286     if(moveType == NormalMove && promoChar)
7287         moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
7288
7289     /* [HGM] <popupFix> The following if has been moved here from
7290        UserMoveEvent(). Because it seemed to belong here (why not allow
7291        piece drops in training games?), and because it can only be
7292        performed after it is known to what we promote. */
7293     if (gameMode == Training) {
7294       /* compare the move played on the board to the next move in the
7295        * game. If they match, display the move and the opponent's response.
7296        * If they don't match, display an error message.
7297        */
7298       int saveAnimate;
7299       Board testBoard;
7300       CopyBoard(testBoard, boards[currentMove]);
7301       ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
7302
7303       if (CompareBoards(testBoard, boards[currentMove+1])) {
7304         ForwardInner(currentMove+1);
7305
7306         /* Autoplay the opponent's response.
7307          * if appData.animate was TRUE when Training mode was entered,
7308          * the response will be animated.
7309          */
7310         saveAnimate = appData.animate;
7311         appData.animate = animateTraining;
7312         ForwardInner(currentMove+1);
7313         appData.animate = saveAnimate;
7314
7315         /* check for the end of the game */
7316         if (currentMove >= forwardMostMove) {
7317           gameMode = PlayFromGameFile;
7318           ModeHighlight();
7319           SetTrainingModeOff();
7320           DisplayInformation(_("End of game"));
7321         }
7322       } else {
7323         DisplayError(_("Incorrect move"), 0);
7324       }
7325       return 1;
7326     }
7327
7328   /* Ok, now we know that the move is good, so we can kill
7329      the previous line in Analysis Mode */
7330   if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
7331                                 && currentMove < forwardMostMove) {
7332     if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
7333     else forwardMostMove = currentMove;
7334   }
7335
7336   ClearMap();
7337
7338   /* If we need the chess program but it's dead, restart it */
7339   ResurrectChessProgram();
7340
7341   /* A user move restarts a paused game*/
7342   if (pausing)
7343     PauseEvent();
7344
7345   thinkOutput[0] = NULLCHAR;
7346
7347   MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
7348
7349   if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
7350     ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7351     return 1;
7352   }
7353
7354   if (gameMode == BeginningOfGame) {
7355     if (appData.noChessProgram) {
7356       gameMode = EditGame;
7357       SetGameInfo();
7358     } else {
7359       char buf[MSG_SIZ];
7360       gameMode = MachinePlaysBlack;
7361       StartClocks();
7362       SetGameInfo();
7363       snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
7364       DisplayTitle(buf);
7365       if (first.sendName) {
7366         snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
7367         SendToProgram(buf, &first);
7368       }
7369       StartClocks();
7370     }
7371     ModeHighlight();
7372   }
7373
7374   /* Relay move to ICS or chess engine */
7375   if (appData.icsActive) {
7376     if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
7377         gameMode == IcsExamining) {
7378       if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7379         SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7380         SendToICS("draw ");
7381         SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7382       }
7383       // also send plain move, in case ICS does not understand atomic claims
7384       SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7385       ics_user_moved = 1;
7386     }
7387   } else {
7388     if (first.sendTime && (gameMode == BeginningOfGame ||
7389                            gameMode == MachinePlaysWhite ||
7390                            gameMode == MachinePlaysBlack)) {
7391       SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
7392     }
7393     if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
7394          // [HGM] book: if program might be playing, let it use book
7395         bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
7396         first.maybeThinking = TRUE;
7397     } else if(fromY == DROP_RANK && fromX == EmptySquare) {
7398         if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
7399         SendBoard(&first, currentMove+1);
7400         if(second.analyzing) {
7401             if(!second.useSetboard) SendToProgram("undo\n", &second);
7402             SendBoard(&second, currentMove+1);
7403         }
7404     } else {
7405         SendMoveToProgram(forwardMostMove-1, &first);
7406         if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
7407     }
7408     if (currentMove == cmailOldMove + 1) {
7409       cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
7410     }
7411   }
7412
7413   ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7414
7415   switch (gameMode) {
7416   case EditGame:
7417     if(appData.testLegality)
7418     switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
7419     case MT_NONE:
7420     case MT_CHECK:
7421       break;
7422     case MT_CHECKMATE:
7423     case MT_STAINMATE:
7424       if (WhiteOnMove(currentMove)) {
7425         GameEnds(BlackWins, "Black mates", GE_PLAYER);
7426       } else {
7427         GameEnds(WhiteWins, "White mates", GE_PLAYER);
7428       }
7429       break;
7430     case MT_STALEMATE:
7431       GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
7432       break;
7433     }
7434     break;
7435
7436   case MachinePlaysBlack:
7437   case MachinePlaysWhite:
7438     /* disable certain menu options while machine is thinking */
7439     SetMachineThinkingEnables();
7440     break;
7441
7442   default:
7443     break;
7444   }
7445
7446   userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
7447   promoDefaultAltered = FALSE; // [HGM] fall back on default choice
7448
7449   if(bookHit) { // [HGM] book: simulate book reply
7450         static char bookMove[MSG_SIZ]; // a bit generous?
7451
7452         programStats.nodes = programStats.depth = programStats.time =
7453         programStats.score = programStats.got_only_move = 0;
7454         sprintf(programStats.movelist, "%s (xbook)", bookHit);
7455
7456         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7457         strcat(bookMove, bookHit);
7458         HandleMachineMove(bookMove, &first);
7459   }
7460   return 1;
7461 }
7462
7463 void
7464 MarkByFEN(char *fen)
7465 {
7466         int r, f;
7467         if(!appData.markers || !appData.highlightDragging) return;
7468         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) legal[r][f] = marker[r][f] = 0;
7469         r=BOARD_HEIGHT-1-deadRanks; f=BOARD_LEFT;
7470         while(*fen) {
7471             int s = 0;
7472             if(*fen == 'M') legal[r][f] = 2; else // request promotion choice
7473             if(*fen == 'B') legal[r][f] = 4; else // request auto-promotion to victim
7474             if(*fen >= 'A' && *fen <= 'Z') legal[r][f] = 6; else
7475             if(*fen >= 'a' && *fen <= 'z') *fen += 'A' - 'a';
7476             if(*fen == '/' && f > BOARD_LEFT) f = BOARD_LEFT, r--; else
7477             if(*fen == 'T') marker[r][f++] = 0; else
7478             if(*fen == 'Y') marker[r][f++] = 1; else
7479             if(*fen == 'G') marker[r][f++] = 3; else
7480             if(*fen == 'B') marker[r][f++] = 4; else
7481             if(*fen == 'C') marker[r][f++] = 5; else
7482             if(*fen == 'M') marker[r][f++] = 6; else
7483             if(*fen == 'W') marker[r][f++] = 7; else
7484             if(*fen == 'D') marker[r][f++] = 8; else
7485             if(*fen == 'R') marker[r][f++] = 2; else {
7486                 while(*fen <= '9' && *fen >= '0') s = 10*s + *fen++ - '0';
7487               f += s; fen -= s>0;
7488             }
7489             while(f >= BOARD_RGHT) f -= BOARD_RGHT - BOARD_LEFT, r--;
7490             if(r < 0) break;
7491             fen++;
7492         }
7493         DrawPosition(TRUE, NULL);
7494 }
7495
7496 static char baseMarker[BOARD_RANKS][BOARD_FILES], baseLegal[BOARD_RANKS][BOARD_FILES];
7497
7498 void
7499 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
7500 {
7501     typedef char Markers[BOARD_RANKS][BOARD_FILES];
7502     Markers *m = (Markers *) closure;
7503     if(rf == fromY && ff == fromX && (killX < 0 ? !(rt == rf && ft == ff) && legNr & 1 :
7504                                       kill2X < 0 ? rt == killY && ft == killX || legNr & 2 : rt == killY && ft == killX || legNr & 4))
7505         (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
7506                          || kind == WhiteCapturesEnPassant
7507                          || kind == BlackCapturesEnPassant) + 3*(kind == FirstLeg && (killX < 0 & legNr || legNr & 2 && kill2X < 0)), legal[rt][ft] = 3;
7508     else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3, legal[rt][ft] = 3;
7509 }
7510
7511 static int hoverSavedValid;
7512
7513 void
7514 MarkTargetSquares (int clear)
7515 {
7516   int x, y, sum=0;
7517   if(clear) { // no reason to ever suppress clearing
7518     for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) sum += marker[y][x], marker[y][x] = 0;
7519     hoverSavedValid = 0;
7520     if(!sum || clear < 0) return; // nothing was cleared,no redraw needed
7521   } else {
7522     int capt = 0;
7523     if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
7524        !appData.testLegality && !pieceDefs || gameMode == EditPosition) return;
7525     GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
7526     if(PosFlags(0) & F_MANDATORY_CAPTURE) {
7527       for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
7528       if(capt)
7529       for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = legal[y][x] = 0;
7530     }
7531   }
7532   DrawPosition(FALSE, NULL);
7533 }
7534
7535 int
7536 Explode (Board board, int fromX, int fromY, int toX, int toY)
7537 {
7538     if(gameInfo.variant == VariantAtomic &&
7539        (board[toY][toX] != EmptySquare ||                     // capture?
7540         toX != fromX && (board[fromY][fromX] == WhitePawn ||  // e.p. ?
7541                          board[fromY][fromX] == BlackPawn   )
7542       )) {
7543         AnimateAtomicCapture(board, fromX, fromY, toX, toY);
7544         return TRUE;
7545     }
7546     return FALSE;
7547 }
7548
7549 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7550
7551 int
7552 CanPromote (ChessSquare piece, int y)
7553 {
7554         int zone = (gameInfo.variant == VariantChuChess ? 3 : 1);
7555         if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7556         // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7557         if(IS_SHOGI(gameInfo.variant)          || gameInfo.variant == VariantXiangqi ||
7558            gameInfo.variant == VariantSuper    || gameInfo.variant == VariantGreat   ||
7559           (gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7560            gameInfo.variant == VariantMakruk) && !*engineVariant) return FALSE;
7561         return (piece == BlackPawn && y <= zone ||
7562                 piece == WhitePawn && y >= BOARD_HEIGHT-1-deadRanks-zone ||
7563                 piece == BlackLance && y <= zone ||
7564                 piece == WhiteLance && y >= BOARD_HEIGHT-1-deadRanks-zone );
7565 }
7566
7567 void
7568 HoverEvent (int xPix, int yPix, int x, int y)
7569 {
7570         static int oldX = -1, oldY = -1, oldFromX = -1, oldFromY = -1;
7571         int r, f;
7572         if(!first.highlight) return;
7573         if(fromX != oldFromX || fromY != oldFromY)  oldX = oldY = -1; // kludge to fake entry on from-click
7574         if(x == oldX && y == oldY) return; // only do something if we enter new square
7575         oldFromX = fromX; oldFromY = fromY;
7576         if(oldX == -1 && oldY == -1 && x == fromX && y == fromY) { // record markings after from-change
7577           for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7578             baseMarker[r][f] = marker[r][f], baseLegal[r][f] = legal[r][f];
7579           hoverSavedValid = 1;
7580         } else if(oldX != x || oldY != y) {
7581           // [HGM] lift: entered new to-square; redraw arrow, and inform engine
7582           if(hoverSavedValid) // don't restore markers that are supposed to be cleared
7583           for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7584             marker[r][f] = baseMarker[r][f], legal[r][f] = baseLegal[r][f];
7585           if((marker[y][x] == 2 || marker[y][x] == 6) && legal[y][x]) {
7586             char buf[MSG_SIZ];
7587             snprintf(buf, MSG_SIZ, "hover %c%d\n", x + AAA, y + ONE - '0');
7588             SendToProgram(buf, &first);
7589           }
7590           oldX = x; oldY = y;
7591 //        SetHighlights(fromX, fromY, x, y);
7592         }
7593 }
7594
7595 void ReportClick(char *action, int x, int y)
7596 {
7597         char buf[MSG_SIZ]; // Inform engine of what user does
7598         int r, f;
7599         if(action[0] == 'l') // mark any target square of a lifted piece as legal to-square, clear markers
7600           for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7601             legal[r][f] = !pieceDefs || !appData.markers, marker[r][f] = 0;
7602         if(!first.highlight || gameMode == EditPosition) return;
7603         snprintf(buf, MSG_SIZ, "%s %c%d%s\n", action, x+AAA, y+ONE-'0', controlKey && action[0]=='p' ? "," : "");
7604         SendToProgram(buf, &first);
7605 }
7606
7607 Boolean right; // instructs front-end to use button-1 events as if they were button 3
7608 Boolean deferChoice;
7609 int createX = -1, createY = -1; // square where we last created a piece in EditPosition mode
7610
7611 void
7612 LeftClick (ClickType clickType, int xPix, int yPix)
7613 {
7614     int x, y;
7615     static Boolean saveAnimate;
7616     static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0, flashing = 0, saveFlash;
7617     char promoChoice = NULLCHAR;
7618     ChessSquare piece;
7619     static TimeMark lastClickTime, prevClickTime;
7620
7621     if(flashing) return;
7622
7623   if(!deferChoice) { // when called for a retry, skip everything to the point where we left off
7624     x = EventToSquare(xPix, BOARD_WIDTH);
7625     y = EventToSquare(yPix, BOARD_HEIGHT);
7626     if (!flipView && y >= 0) {
7627         y = BOARD_HEIGHT - 1 - y;
7628     }
7629     if (flipView && x >= 0) {
7630         x = BOARD_WIDTH - 1 - x;
7631     }
7632
7633     // map clicks in offsetted holdings back to true coords (or switch the offset)
7634     if(x == BOARD_RGHT+1) {
7635         if(handOffsets & 1) {
7636             if(y == 0) { handOffsets &= ~1; DrawPosition(TRUE, boards[currentMove]); return; }
7637             y += handSize - BOARD_HEIGHT;
7638         } else if(y == BOARD_HEIGHT-1) { handOffsets |= 1; DrawPosition(TRUE, boards[currentMove]); return; }
7639     }
7640     if(x == BOARD_LEFT-2) {
7641         if(!(handOffsets & 2)) {
7642             if(y == 0) { handOffsets |= 2; DrawPosition(TRUE, boards[currentMove]); return; }
7643             y += handSize - BOARD_HEIGHT;
7644         } else if(y == BOARD_HEIGHT-1) { handOffsets &= ~2; DrawPosition(TRUE, boards[currentMove]); return; }
7645     }
7646
7647     if(appData.monoMouse && gameMode == EditPosition && fromX < 0 && clickType == Press && 
7648         (boards[currentMove][y][x] == EmptySquare || x == createX && y == createY) ) {
7649         static int dummy;
7650         RightClick(clickType, xPix, yPix, &dummy, &dummy);
7651         right = TRUE;
7652         return;
7653     }
7654
7655     createX = createY = -1;
7656
7657     if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7658
7659     prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7660
7661     if (clickType == Press) ErrorPopDown();
7662     lastClickType = clickType, lastLeftX = xPix, lastLeftY = yPix; // [HGM] alien: remember state
7663
7664     if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7665         defaultPromoChoice = promoSweep;
7666         promoSweep = EmptySquare;   // terminate sweep
7667         promoDefaultAltered = TRUE;
7668         if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7669     }
7670
7671     if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7672         if(clickType == Release) return; // ignore upclick of click-click destination
7673         promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7674         if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7675         if(gameInfo.holdingsWidth &&
7676                 (WhiteOnMove(currentMove)
7677                         ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7678                         : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7679             // click in right holdings, for determining promotion piece
7680             ChessSquare p = boards[currentMove][y][x];
7681             if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7682             if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7683             if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7684                 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7685                 fromX = fromY = -1;
7686                 return;
7687             }
7688         }
7689         DrawPosition(FALSE, boards[currentMove]);
7690         return;
7691     }
7692
7693     /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7694     if(clickType == Press
7695             && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7696               || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7697               || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7698         return;
7699
7700     if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7701         // could be static click on premove from-square: abort premove
7702         gotPremove = 0;
7703         ClearPremoveHighlights();
7704     }
7705
7706     if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7707         fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7708
7709     if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7710         int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7711                     gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7712         defaultPromoChoice = DefaultPromoChoice(side);
7713     }
7714
7715     autoQueen = appData.alwaysPromoteToQueen;
7716
7717     if (fromX == -1) {
7718       int originalY = y;
7719       gatingPiece = EmptySquare;
7720       if (clickType != Press) {
7721         if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7722             DragPieceEnd(xPix, yPix); dragging = 0;
7723             DrawPosition(FALSE, NULL);
7724         }
7725         return;
7726       }
7727       doubleClick = FALSE;
7728       if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
7729         doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
7730       }
7731       fromX = x; fromY = y; toX = toY = killX = killY = kill2X = kill2Y = -1; *promoRestrict = NULLCHAR;
7732       if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7733          // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7734          appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7735             /* First square */
7736             if (OKToStartUserMove(fromX, fromY)) {
7737                 second = 0;
7738                 ReportClick("lift", x, y);
7739                 MarkTargetSquares(0);
7740                 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7741                 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7742                 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7743                     promoSweep = defaultPromoChoice;
7744                     selectFlag = 0; lastX = xPix; lastY = yPix; *promoRestrict = 0;
7745                     Sweep(0); // Pawn that is going to promote: preview promotion piece
7746                     DisplayMessage("", _("Pull pawn backwards to under-promote"));
7747                 }
7748                 if (appData.highlightDragging) {
7749                     SetHighlights(fromX, fromY, -1, -1);
7750                 } else {
7751                     ClearHighlights();
7752                 }
7753             } else fromX = fromY = -1;
7754             return;
7755         }
7756     }
7757
7758     /* fromX != -1 */
7759     if (clickType == Press && gameMode != EditPosition) {
7760         ChessSquare fromP;
7761         ChessSquare toP;
7762         int frc;
7763
7764         // ignore off-board to clicks
7765         if(y < 0 || x < 0) return;
7766
7767         /* Check if clicking again on the same color piece */
7768         fromP = boards[currentMove][fromY][fromX];
7769         toP = boards[currentMove][y][x];
7770         frc = appData.fischerCastling || gameInfo.variant == VariantSChess;
7771         if( (killX < 0 || x != fromX || y != fromY) && // [HGM] lion: do not interpret igui as deselect!
7772             marker[y][x] == 0 && // if engine told we can move to here, do it even if own piece
7773            ((WhitePawn <= fromP && fromP <= WhiteKing &&
7774              WhitePawn <= toP && toP <= WhiteKing &&
7775              !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7776              !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7777             (BlackPawn <= fromP && fromP <= BlackKing &&
7778              BlackPawn <= toP && toP <= BlackKing &&
7779              !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7780              !(fromP == BlackKing && toP == BlackRook && frc)))) {
7781             /* Clicked again on same color piece -- changed his mind */
7782             second = (x == fromX && y == fromY);
7783             killX = killY = kill2X = kill2Y = -1; *promoRestrict = NULLCHAR;
7784             if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7785                 second = FALSE; // first double-click rather than scond click
7786                 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7787             }
7788             promoDefaultAltered = FALSE;
7789            if(!second) MarkTargetSquares(1);
7790            if(!(second && appData.oneClick && OnlyMove(&x, &y, TRUE))) {
7791             if (appData.highlightDragging) {
7792                 SetHighlights(x, y, -1, -1);
7793             } else {
7794                 ClearHighlights();
7795             }
7796             if (OKToStartUserMove(x, y)) {
7797                 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7798                   (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7799                y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7800                  gatingPiece = boards[currentMove][fromY][fromX];
7801                 else gatingPiece = doubleClick ? fromP : EmptySquare;
7802                 fromX = x;
7803                 fromY = y; dragging = 1;
7804                 if(!second) ReportClick("lift", x, y);
7805                 MarkTargetSquares(0);
7806                 DragPieceBegin(xPix, yPix, FALSE);
7807                 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7808                     promoSweep = defaultPromoChoice;
7809                     selectFlag = 0; lastX = xPix; lastY = yPix; *promoRestrict = 0;
7810                     Sweep(0); // Pawn that is going to promote: preview promotion piece
7811                 }
7812             }
7813            }
7814            if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7815            second = FALSE;
7816         }
7817         // ignore clicks on holdings
7818         if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7819     }
7820
7821     if(x == fromX && y == fromY && clickType == Press && gameMode == EditPosition && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7822         gatingPiece = boards[currentMove][fromY][fromX]; // prepare to copy rather than move
7823         DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7824         return;
7825     }
7826
7827     if (clickType == Release && x == fromX && y == fromY && killX < 0 && !sweepSelecting) {
7828         DragPieceEnd(xPix, yPix); dragging = 0;
7829         if(clearFlag) {
7830             // a deferred attempt to click-click move an empty square on top of a piece
7831             boards[currentMove][y][x] = EmptySquare;
7832             ClearHighlights();
7833             DrawPosition(FALSE, boards[currentMove]);
7834             fromX = fromY = -1; clearFlag = 0;
7835             return;
7836         }
7837         if (appData.animateDragging) {
7838             /* Undo animation damage if any */
7839             DrawPosition(FALSE, NULL);
7840         }
7841         if (second) {
7842             /* Second up/down in same square; just abort move */
7843             second = 0;
7844             fromX = fromY = -1;
7845             gatingPiece = EmptySquare;
7846             ClearHighlights();
7847             gotPremove = 0;
7848             ClearPremoveHighlights();
7849             MarkTargetSquares(-1);
7850             DrawPosition(FALSE, NULL); // make user highlights are drawn (and deferred marker clearing)
7851         } else {
7852             /* First upclick in same square; start click-click mode */
7853             SetHighlights(x, y, -1, -1);
7854         }
7855         return;
7856     }
7857
7858     clearFlag = 0;
7859
7860     if(gameMode != EditPosition && !appData.testLegality && !legal[y][x] &&
7861        fromX >= BOARD_LEFT && fromX < BOARD_RGHT && (x != killX || y != killY) && !sweepSelecting) {
7862         if(dragging) DragPieceEnd(xPix, yPix), dragging = 0;
7863         DisplayMessage(_("only marked squares are legal"),"");
7864         DrawPosition(TRUE, NULL);
7865         return; // ignore to-click
7866     }
7867
7868     /* we now have a different from- and (possibly off-board) to-square */
7869     /* Completed move */
7870     if(!sweepSelecting) {
7871         toX = x;
7872         toY = y;
7873     }
7874
7875     piece = boards[currentMove][fromY][fromX];
7876
7877     saveAnimate = appData.animate;
7878     if (clickType == Press) {
7879         if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7880         if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7881             // must be Edit Position mode with empty-square selected
7882             fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7883             if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7884             return;
7885         }
7886         if(dragging == 2) {  // [HGM] lion: just turn buttonless drag into normal drag, and let release to the job
7887             return;
7888         }
7889         if(x == killX && y == killY) {              // second click on this square, which was selected as first-leg target
7890             killX = kill2X; killY = kill2Y; kill2X = kill2Y = -1;   // this informs us no second leg is coming, so treat as to-click without intermediate
7891         } else
7892         if(marker[y][x] == 5) return; // [HGM] lion: to-click on cyan square; defer action to release
7893         if(legal[y][x] == 2 || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7894           if(appData.sweepSelect) {
7895             promoSweep = defaultPromoChoice;
7896             if(gameInfo.variant != VariantChuChess && PieceToChar(CHUPROMOTED(piece)) == '+') promoSweep = CHUPROMOTED(piece);
7897             selectFlag = 0; lastX = xPix; lastY = yPix;
7898             ReportClick("put", x, y); // extra put to prompt engine for 'choice' command
7899             saveFlash = appData.flashCount; appData.flashCount = 0;
7900             Sweep(0); // Pawn that is going to promote: preview promotion piece
7901             sweepSelecting = 1;
7902             DisplayMessage("", _("Pull pawn backwards to under-promote"));
7903             MarkTargetSquares(1);
7904           }
7905           return; // promo popup appears on up-click
7906         }
7907         /* Finish clickclick move */
7908         if (appData.animate || appData.highlightLastMove) {
7909             SetHighlights(fromX, fromY, toX, toY);
7910         } else {
7911             ClearHighlights();
7912         }
7913         MarkTargetSquares(1);
7914     } else if(sweepSelecting) { // this must be the up-click corresponding to the down-click that started the sweep
7915         sweepSelecting = 0; appData.animate = FALSE; // do not animate, a selected piece already on to-square
7916         *promoRestrict = 0; appData.flashCount = saveFlash;
7917         if (appData.animate || appData.highlightLastMove) {
7918             SetHighlights(fromX, fromY, toX, toY);
7919         } else {
7920             ClearHighlights();
7921         }
7922         MarkTargetSquares(1);
7923     } else {
7924 #if 0
7925 // [HGM] this must be done after the move is made, as with arrow it could lead to a board redraw with piece still on from square
7926         /* Finish drag move */
7927         if (appData.highlightLastMove) {
7928             SetHighlights(fromX, fromY, toX, toY);
7929         } else {
7930             ClearHighlights();
7931         }
7932 #endif
7933         if(PieceToChar(CHUPROMOTED(boards[currentMove][fromY][fromX])) == '+')
7934           defaultPromoChoice = CHUPROMOTED(boards[currentMove][fromY][fromX]);
7935         if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7936         if(marker[y][x] == 5) { // [HGM] lion: this was the release of a to-click or drag on a cyan square
7937           dragging *= 2;            // flag button-less dragging if we are dragging
7938           MarkTargetSquares(1);
7939           if(x == killX && y == killY) killX = kill2X, killY = kill2Y, kill2X = kill2Y = -1; // cancel last kill
7940           else {
7941             kill2X = killX; kill2Y = killY;
7942             killX = x; killY = y;     // remember this square as intermediate
7943             ReportClick("put", x, y); // and inform engine
7944             ReportClick("lift", x, y);
7945             MarkTargetSquares(0);
7946             return;
7947           }
7948         }
7949         DragPieceEnd(xPix, yPix); dragging = 0;
7950         /* Don't animate move and drag both */
7951         appData.animate = FALSE;
7952         MarkTargetSquares(-1); // -1 defers displaying marker change to prevent piece reappearing on from-square!
7953     }
7954
7955     // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7956     if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7957         ChessSquare piece = boards[currentMove][fromY][fromX];
7958         if(gameMode == EditPosition && piece != EmptySquare &&
7959            fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7960             int n;
7961
7962             if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7963                 n = PieceToNumber(piece - (int)BlackPawn);
7964                 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7965                 boards[currentMove][handSize-1 - n][0] = piece;
7966                 boards[currentMove][handSize-1 - n][1]++;
7967             } else
7968             if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7969                 n = PieceToNumber(piece);
7970                 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7971                 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7972                 boards[currentMove][n][BOARD_WIDTH-2]++;
7973             }
7974             boards[currentMove][fromY][fromX] = EmptySquare;
7975         }
7976         ClearHighlights();
7977         fromX = fromY = -1;
7978         MarkTargetSquares(1);
7979         DrawPosition(TRUE, boards[currentMove]);
7980         return;
7981     }
7982
7983     // off-board moves should not be highlighted
7984     if(x < 0 || y < 0) {
7985         ClearHighlights();
7986         DrawPosition(FALSE, NULL);
7987     } else ReportClick("put", x, y);
7988
7989     if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7990  }
7991
7992     if(legal[toY][toX] == 2) { // highlight-induced promotion
7993         if(piece == defaultPromoChoice) promoChoice = NULLCHAR; // deferral
7994         else promoChoice = ToLower(PieceToChar(defaultPromoChoice));
7995     } else if(legal[toY][toX] == 4) { // blue target square: engine must supply promotion choice
7996       if(!*promoRestrict) {           // but has not done that yet
7997         deferChoice = TRUE;           // set up retry for when it does
7998         return;                       // and wait for that
7999       }
8000       promoChoice = ToLower(*promoRestrict); // force engine's choice
8001       deferChoice = FALSE;
8002     }
8003
8004     if (legal[toY][toX] == 2 && !appData.sweepSelect || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
8005         SetHighlights(fromX, fromY, toX, toY);
8006         MarkTargetSquares(1);
8007         if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
8008             // [HGM] super: promotion to captured piece selected from holdings
8009             ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
8010             promotionChoice = TRUE;
8011             // kludge follows to temporarily execute move on display, without promoting yet
8012             boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
8013             boards[currentMove][toY][toX] = p;
8014             DrawPosition(FALSE, boards[currentMove]);
8015             boards[currentMove][fromY][fromX] = p; // take back, but display stays
8016             boards[currentMove][toY][toX] = q;
8017             DisplayMessage("Click in holdings to choose piece", "");
8018             return;
8019         }
8020         DrawPosition(FALSE, NULL); // shows piece on from-square during promo popup
8021         PromotionPopUp(promoChoice);
8022     } else {
8023         int oldMove = currentMove;
8024         flashing = 1; // prevent recursive calling (by release of to-click) while flashing piece
8025         UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
8026         if (!appData.highlightLastMove || gotPremove) ClearHighlights();
8027         if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY), DrawPosition(FALSE, NULL);
8028         if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
8029            Explode(boards[currentMove-1], fromX, fromY, toX, toY))
8030             DrawPosition(TRUE, boards[currentMove]);
8031         else DrawPosition(FALSE, NULL);
8032         fromX = fromY = -1;
8033         flashing = 0;
8034     }
8035     appData.animate = saveAnimate;
8036     if (appData.animate || appData.animateDragging) {
8037         /* Undo animation damage if needed */
8038 //      DrawPosition(FALSE, NULL);
8039     }
8040 }
8041
8042 int
8043 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
8044 {   // front-end-free part taken out of PieceMenuPopup
8045     int whichMenu; int xSqr, ySqr;
8046
8047     if(seekGraphUp) { // [HGM] seekgraph
8048         if(action == Press)   SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
8049         if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
8050         return -2;
8051     }
8052
8053     if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
8054          && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
8055         if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
8056         if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
8057         if(action == Press)   {
8058             originalFlip = flipView;
8059             flipView = !flipView; // temporarily flip board to see game from partners perspective
8060             DrawPosition(TRUE, partnerBoard);
8061             DisplayMessage(partnerStatus, "");
8062             partnerUp = TRUE;
8063         } else if(action == Release) {
8064             flipView = originalFlip;
8065             DrawPosition(TRUE, boards[currentMove]);
8066             partnerUp = FALSE;
8067         }
8068         return -2;
8069     }
8070
8071     xSqr = EventToSquare(x, BOARD_WIDTH);
8072     ySqr = EventToSquare(y, BOARD_HEIGHT);
8073     if (action == Release) {
8074         if(pieceSweep != EmptySquare) {
8075             EditPositionMenuEvent(pieceSweep, toX, toY);
8076             pieceSweep = EmptySquare;
8077         } else UnLoadPV(); // [HGM] pv
8078     }
8079     if (action != Press) return -2; // return code to be ignored
8080     switch (gameMode) {
8081       case IcsExamining:
8082         if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
8083       case EditPosition:
8084         if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
8085         if (xSqr < 0 || ySqr < 0) return -1;
8086         if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
8087         if(flipView) xSqr = BOARD_WIDTH - 1 - xSqr; else ySqr = BOARD_HEIGHT - 1 - ySqr;
8088         if(xSqr == createX && ySqr == createY && xSqr != BOARD_LEFT-2 && xSqr != BOARD_RGHT+1) {
8089             ChessSquare p = boards[currentMove][ySqr][xSqr];
8090             do { if(++p == EmptySquare) p = WhitePawn; } while(PieceToChar(p) == '.');
8091             boards[currentMove][ySqr][xSqr] = p; DrawPosition(FALSE, boards[currentMove]);
8092             return -2;
8093         }
8094         pieceSweep = shiftKey ? BlackPawn : WhitePawn;  // [HGM] sweep: prepare selecting piece by mouse sweep
8095         createX = toX = xSqr; createY = toY = ySqr; lastX = x, lastY = y;
8096         NextPiece(0);
8097         return 2; // grab
8098       case IcsObserving:
8099         if(!appData.icsEngineAnalyze) return -1;
8100       case IcsPlayingWhite:
8101       case IcsPlayingBlack:
8102         if(!appData.zippyPlay) goto noZip;
8103       case AnalyzeMode:
8104       case AnalyzeFile:
8105       case MachinePlaysWhite:
8106       case MachinePlaysBlack:
8107       case TwoMachinesPlay: // [HGM] pv: use for showing PV
8108         if (!appData.dropMenu) {
8109           LoadPV(x, y);
8110           return 2; // flag front-end to grab mouse events
8111         }
8112         if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
8113            gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
8114       case EditGame:
8115       noZip:
8116         if (xSqr < 0 || ySqr < 0) return -1;
8117         if (!appData.dropMenu || appData.testLegality &&
8118             gameInfo.variant != VariantBughouse &&
8119             gameInfo.variant != VariantCrazyhouse) return -1;
8120         whichMenu = 1; // drop menu
8121         break;
8122       default:
8123         return -1;
8124     }
8125
8126     if (((*fromX = xSqr) < 0) ||
8127         ((*fromY = ySqr) < 0)) {
8128         *fromX = *fromY = -1;
8129         return -1;
8130     }
8131     if (flipView)
8132       *fromX = BOARD_WIDTH - 1 - *fromX;
8133     else
8134       *fromY = BOARD_HEIGHT - 1 - *fromY;
8135
8136     return whichMenu;
8137 }
8138
8139 void
8140 Wheel (int dir, int x, int y)
8141 {
8142     if(gameMode == EditPosition) {
8143         int xSqr = EventToSquare(x, BOARD_WIDTH);
8144         int ySqr = EventToSquare(y, BOARD_HEIGHT);
8145         if(ySqr < 0 || xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return;
8146         if(flipView) xSqr = BOARD_WIDTH - 1 - xSqr; else ySqr = BOARD_HEIGHT - 1 - ySqr;
8147         do {
8148             boards[currentMove][ySqr][xSqr] += dir;
8149             if((int) boards[currentMove][ySqr][xSqr] < WhitePawn) boards[currentMove][ySqr][xSqr] = BlackKing;
8150             if((int) boards[currentMove][ySqr][xSqr] > BlackKing) boards[currentMove][ySqr][xSqr] = WhitePawn;
8151         } while(PieceToChar(boards[currentMove][ySqr][xSqr]) == '.');
8152         DrawPosition(FALSE, boards[currentMove]);
8153     } else if(dir > 0) ForwardEvent(); else BackwardEvent();
8154 }
8155
8156 void
8157 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
8158 {
8159 //    char * hint = lastHint;
8160     FrontEndProgramStats stats;
8161
8162     stats.which = cps == &first ? 0 : 1;
8163     stats.depth = cpstats->depth;
8164     stats.nodes = cpstats->nodes;
8165     stats.score = cpstats->score;
8166     stats.time = cpstats->time;
8167     stats.pv = cpstats->movelist;
8168     stats.hint = lastHint;
8169     stats.an_move_index = 0;
8170     stats.an_move_count = 0;
8171
8172     if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
8173         stats.hint = cpstats->move_name;
8174         stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
8175         stats.an_move_count = cpstats->nr_moves;
8176     }
8177
8178     if(stats.pv && stats.pv[0]) safeStrCpy(lastPV[stats.which], stats.pv, sizeof(lastPV[stats.which])/sizeof(lastPV[stats.which][0])); // [HGM] pv: remember last PV of each
8179
8180     if( gameMode == AnalyzeMode && stats.pv && stats.pv[0]
8181         && appData.analysisBell && stats.time >= 100*appData.analysisBell ) RingBell();
8182
8183     SetProgramStats( &stats );
8184 }
8185
8186 void
8187 ClearEngineOutputPane (int which)
8188 {
8189     static FrontEndProgramStats dummyStats;
8190     dummyStats.which = which;
8191     dummyStats.pv = "#";
8192     SetProgramStats( &dummyStats );
8193 }
8194
8195 #define MAXPLAYERS 500
8196
8197 char *
8198 TourneyStandings (int display)
8199 {
8200     int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
8201     int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
8202     char result, *p, *names[MAXPLAYERS];
8203
8204     if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
8205         return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
8206     names[0] = p = strdup(appData.participants);
8207     while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
8208
8209     for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
8210
8211     while(result = appData.results[nr]) {
8212         color = Pairing(nr, nPlayers, &w, &b, &dummy);
8213         if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
8214         wScore = bScore = 0;
8215         switch(result) {
8216           case '+': wScore = 2; break;
8217           case '-': bScore = 2; break;
8218           case '=': wScore = bScore = 1; break;
8219           case ' ':
8220           case '*': return strdup("busy"); // tourney not finished
8221         }
8222         score[w] += wScore;
8223         score[b] += bScore;
8224         games[w]++;
8225         games[b]++;
8226         nr++;
8227     }
8228     if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
8229     for(w=0; w<nPlayers; w++) {
8230         bScore = -1;
8231         for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
8232         ranking[w] = b; points[w] = bScore; score[b] = -2;
8233     }
8234     p = malloc(nPlayers*34+1);
8235     for(w=0; w<nPlayers && w<display; w++)
8236         sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
8237     free(names[0]);
8238     return p;
8239 }
8240
8241 void
8242 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
8243 {       // count all piece types
8244         int p, f, r;
8245         *nB = *nW = *wStale = *bStale = *bishopColor = 0;
8246         for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
8247         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
8248                 p = board[r][f];
8249                 pCnt[p]++;
8250                 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
8251                 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
8252                 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
8253                 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
8254                    p == BlackBishop || p == BlackFerz || p == BlackAlfil   )
8255                         *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
8256         }
8257 }
8258
8259 int
8260 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
8261 {
8262         int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
8263         int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
8264
8265         nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
8266         if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
8267         if(myPawns == 2 && nMine == 3) // KPP
8268             return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
8269         if(myPawns == 1 && nMine == 2) // KP
8270             return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]  + pCnt[BlackPawn-side] >= 1;
8271         if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
8272             return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
8273         if(myPawns) return FALSE;
8274         if(pCnt[WhiteRook+side])
8275             return pCnt[BlackRook-side] ||
8276                    pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
8277                    pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
8278                    pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
8279         if(pCnt[WhiteCannon+side]) {
8280             if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
8281             return majorDefense || pCnt[BlackAlfil-side] >= 2;
8282         }
8283         if(pCnt[WhiteKnight+side])
8284             return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
8285         return FALSE;
8286 }
8287
8288 int
8289 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
8290 {
8291         VariantClass v = gameInfo.variant;
8292
8293         if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
8294         if(v == VariantShatranj) return TRUE; // always winnable through baring
8295         if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
8296         if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
8297
8298         if(v == VariantXiangqi) {
8299                 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
8300
8301                 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
8302                 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
8303                 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
8304                 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
8305                 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
8306                 if(stale) // we have at least one last-rank P plus perhaps C
8307                     return majors // KPKX
8308                         || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
8309                 else // KCA*E*
8310                     return pCnt[WhiteFerz+side] // KCAK
8311                         || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
8312                         || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
8313                 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
8314
8315         } else if(v == VariantKnightmate) {
8316                 if(nMine == 1) return FALSE;
8317                 if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
8318         } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
8319                 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
8320
8321                 if(nMine == 1) return FALSE; // bare King
8322                 if(nBishops && bisColor == 3) return TRUE; // There must be a second B/A/F, which can either block (his) or attack (mine) the escape square
8323                 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
8324                 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
8325                 // by now we have King + 1 piece (or multiple Bishops on the same color)
8326                 if(pCnt[WhiteKnight+side])
8327                         return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
8328                                 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
8329                              || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
8330                 if(nBishops)
8331                         return (pCnt[BlackKnight-side]); // KBKN, KFKN
8332                 if(pCnt[WhiteAlfil+side])
8333                         return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
8334                 if(pCnt[WhiteWazir+side])
8335                         return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
8336         }
8337
8338         return TRUE;
8339 }
8340
8341 int
8342 CompareWithRights (Board b1, Board b2)
8343 {
8344     int rights = 0;
8345     if(!CompareBoards(b1, b2)) return FALSE;
8346     if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
8347     /* compare castling rights */
8348     if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
8349            rights++; /* King lost rights, while rook still had them */
8350     if( b1[CASTLING][2] != NoRights ) { /* king has rights */
8351         if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
8352            rights++; /* but at least one rook lost them */
8353     }
8354     if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
8355            rights++;
8356     if( b1[CASTLING][5] != NoRights ) {
8357         if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
8358            rights++;
8359     }
8360     return rights == 0;
8361 }
8362
8363 int
8364 Adjudicate (ChessProgramState *cps)
8365 {       // [HGM] some adjudications useful with buggy engines
8366         // [HGM] adjudicate: made into separate routine, which now can be called after every move
8367         //       In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
8368         //       Actually ending the game is now based on the additional internal condition canAdjudicate.
8369         //       Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
8370         int k, drop, count = 0; static int bare = 1;
8371         ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
8372         Boolean canAdjudicate = !appData.icsActive;
8373
8374         // most tests only when we understand the game, i.e. legality-checking on
8375             if( appData.testLegality )
8376             {   /* [HGM] Some more adjudications for obstinate engines */
8377                 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+2], i;
8378                 static int moveCount = 6;
8379                 ChessMove result;
8380                 char *reason = NULL;
8381
8382                 /* Count what is on board. */
8383                 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
8384
8385                 /* Some material-based adjudications that have to be made before stalemate test */
8386                 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
8387                     // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
8388                      boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
8389                      if(canAdjudicate && appData.checkMates) {
8390                          if(engineOpponent)
8391                            SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8392                          GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
8393                                                         "Xboard adjudication: King destroyed", GE_XBOARD );
8394                          return 1;
8395                      }
8396                 }
8397
8398                 /* Bare King in Shatranj (loses) or Losers (wins) */
8399                 if( nrW == 1 || nrB == 1) {
8400                   if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
8401                      boards[forwardMostMove][EP_STATUS] = EP_WINS;  // mark as win, so it becomes claimable
8402                      if(canAdjudicate && appData.checkMates) {
8403                          if(engineOpponent)
8404                            SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
8405                          GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8406                                                         "Xboard adjudication: Bare king", GE_XBOARD );
8407                          return 1;
8408                      }
8409                   } else
8410                   if( gameInfo.variant == VariantShatranj && --bare < 0)
8411                   {    /* bare King */
8412                         boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
8413                         if(canAdjudicate && appData.checkMates) {
8414                             /* but only adjudicate if adjudication enabled */
8415                             if(engineOpponent)
8416                               SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8417                             GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
8418                                                         "Xboard adjudication: Bare king", GE_XBOARD );
8419                             return 1;
8420                         }
8421                   }
8422                 } else bare = 1;
8423
8424
8425             // don't wait for engine to announce game end if we can judge ourselves
8426             switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8427               case MT_CHECK:
8428                 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
8429                     int i, checkCnt = 0;    // (should really be done by making nr of checks part of game state)
8430                     for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
8431                         if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
8432                             checkCnt++;
8433                         if(checkCnt >= 2) {
8434                             reason = "Xboard adjudication: 3rd check";
8435                             boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
8436                             break;
8437                         }
8438                     }
8439                 }
8440               case MT_NONE:
8441               default:
8442                 break;
8443               case MT_STEALMATE:
8444               case MT_STALEMATE:
8445               case MT_STAINMATE:
8446                 reason = "Xboard adjudication: Stalemate";
8447                 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
8448                     boards[forwardMostMove][EP_STATUS] = EP_STALEMATE;   // default result for stalemate is draw
8449                     if(gameInfo.variant == VariantLosers  || gameInfo.variant == VariantGiveaway) // [HGM] losers:
8450                         boards[forwardMostMove][EP_STATUS] = EP_WINS;    // in these variants stalemated is always a win
8451                     else if(gameInfo.variant == VariantSuicide) // in suicide it depends
8452                         boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
8453                                                    ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
8454                                                                         EP_CHECKMATE : EP_WINS);
8455                     else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
8456                         boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
8457                 }
8458                 break;
8459               case MT_CHECKMATE:
8460                 reason = "Xboard adjudication: Checkmate";
8461                 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
8462                 if(gameInfo.variant == VariantShogi) {
8463                     if(forwardMostMove > backwardMostMove
8464                        && moveList[forwardMostMove-1][1] == '@'
8465                        && CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
8466                         reason = "XBoard adjudication: pawn-drop mate";
8467                         boards[forwardMostMove][EP_STATUS] = EP_WINS;
8468                     }
8469                 }
8470                 break;
8471             }
8472
8473                 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
8474                     case EP_STALEMATE:
8475                         result = GameIsDrawn; break;
8476                     case EP_CHECKMATE:
8477                         result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
8478                     case EP_WINS:
8479                         result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
8480                     default:
8481                         result = EndOfFile;
8482                 }
8483                 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
8484                     if(engineOpponent)
8485                       SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8486                     GameEnds( result, reason, GE_XBOARD );
8487                     return 1;
8488                 }
8489
8490                 /* Next absolutely insufficient mating material. */
8491                 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
8492                    !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
8493                 {    /* includes KBK, KNK, KK of KBKB with like Bishops */
8494
8495                      /* always flag draws, for judging claims */
8496                      boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
8497
8498                      if(canAdjudicate && appData.materialDraws) {
8499                          /* but only adjudicate them if adjudication enabled */
8500                          if(engineOpponent) {
8501                            SendToProgram("force\n", engineOpponent); // suppress reply
8502                            SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
8503                          }
8504                          GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
8505                          return 1;
8506                      }
8507                 }
8508
8509                 /* Then some trivial draws (only adjudicate, cannot be claimed) */
8510                 if(gameInfo.variant == VariantXiangqi ?
8511                        SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
8512                  : nrW + nrB == 4 &&
8513                    (   nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
8514                    || nr[WhiteQueen] && nr[BlackQueen]==1     /* KQKQ */
8515                    || nr[WhiteKnight]==2 || nr[BlackKnight]==2     /* KNNK */
8516                    || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
8517                    ) ) {
8518                      if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
8519                      {    /* if the first 3 moves do not show a tactical win, declare draw */
8520                           if(engineOpponent) {
8521                             SendToProgram("force\n", engineOpponent); // suppress reply
8522                             SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8523                           }
8524                           GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
8525                           return 1;
8526                      }
8527                 } else moveCount = 6;
8528
8529                 if(gameInfo.variant == VariantMakruk && // Makruk counting rules
8530                   (nrW == 1 || nrB == 1 || nr[WhitePawn] + nr[BlackPawn] == 0)) { // which only kick in when pawnless or bare King
8531                     int maxcnt, his, mine, c, wom = WhiteOnMove(forwardMostMove);
8532                     count = forwardMostMove;
8533                     while(count >= backwardMostMove) {
8534                         int np = nr[WhitePawn] + nr[BlackPawn];
8535                         if(wom) mine = nrW, his = nrB, c = BlackPawn;
8536                         else    mine = nrB, his = nrW, c = WhitePawn;
8537                         if(mine > 1 && np) { count++; break; }
8538                         if(mine > 1) maxcnt = 64; else
8539                         maxcnt = (nr[WhiteRook+c] > 1 ? 8 : nr[WhiteRook+c] ? 16 : nr[WhiteMan+c] > 1 ? 22 :
8540                                                             nr[WhiteKnight+c] > 1 ? 32 : nr[WhiteMan+c] ? 44 : 64) - his - 1;
8541                         while(boards[count][EP_STATUS] != EP_CAPTURE && count > backwardMostMove) count--; // seek previous character
8542                         if(count == backwardMostMove) break;
8543                         if(forwardMostMove - count >= 2*maxcnt + 1 - (mine == 1)) break;
8544                         Count(boards[--count], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
8545                     }
8546                     if(forwardMostMove - count >= 2*maxcnt + 1 - (mine == 1)) {
8547                         boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
8548                         if(canAdjudicate && appData.ruleMoves >= 0) {
8549                             GameEnds( GameIsDrawn, "Xboard adjudication: counting rule", GE_XBOARD );
8550                             return 1;
8551                         }
8552                     }
8553                 }
8554             }
8555
8556         // Repetition draws and 50-move rule can be applied independently of legality testing
8557
8558                 /* Check for rep-draws */
8559                 count = 0;
8560                 drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
8561                                               && gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
8562                 for(k = forwardMostMove-2;
8563                     k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
8564                         (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
8565                         (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
8566                     k-=2)
8567                 {   int rights=0;
8568                     if(CompareBoards(boards[k], boards[forwardMostMove])) {
8569                         /* compare castling rights */
8570                         if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
8571                              (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
8572                                 rights++; /* King lost rights, while rook still had them */
8573                         if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
8574                             if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
8575                                 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
8576                                    rights++; /* but at least one rook lost them */
8577                         }
8578                         if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
8579                              (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
8580                                 rights++;
8581                         if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
8582                             if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
8583                                 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
8584                                    rights++;
8585                         }
8586                         if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
8587                             && appData.drawRepeats > 1) {
8588                              /* adjudicate after user-specified nr of repeats */
8589                              int result = GameIsDrawn;
8590                              char *details = "XBoard adjudication: repetition draw";
8591                              if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
8592                                 // [HGM] xiangqi: check for forbidden perpetuals
8593                                 int m, ourPerpetual = 1, hisPerpetual = 1;
8594                                 for(m=forwardMostMove; m>k; m-=2) {
8595                                     if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
8596                                         ourPerpetual = 0; // the current mover did not always check
8597                                     if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
8598                                         hisPerpetual = 0; // the opponent did not always check
8599                                 }
8600                                 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
8601                                                                         ourPerpetual, hisPerpetual);
8602                                 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
8603                                     result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8604                                     details = "Xboard adjudication: perpetual checking";
8605                                 } else
8606                                 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
8607                                     break; // (or we would have caught him before). Abort repetition-checking loop.
8608                                 } else
8609                                 if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
8610                                     if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
8611                                         result = BlackWins;
8612                                         details = "Xboard adjudication: repetition";
8613                                     }
8614                                 } else // it must be XQ
8615                                 // Now check for perpetual chases
8616                                 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
8617                                     hisPerpetual = PerpetualChase(k, forwardMostMove);
8618                                     ourPerpetual = PerpetualChase(k+1, forwardMostMove);
8619                                     if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
8620                                         static char resdet[MSG_SIZ];
8621                                         result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8622                                         details = resdet;
8623                                         snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
8624                                     } else
8625                                     if(hisPerpetual && !ourPerpetual)   // he is chasing us, but did not repeat yet
8626                                         break; // Abort repetition-checking loop.
8627                                 }
8628                                 // if neither of us is checking or chasing all the time, or both are, it is draw
8629                              }
8630                              if(engineOpponent) {
8631                                SendToProgram("force\n", engineOpponent); // suppress reply
8632                                SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8633                              }
8634                              GameEnds( result, details, GE_XBOARD );
8635                              return 1;
8636                         }
8637                         if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
8638                              boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
8639                     }
8640                 }
8641
8642                 /* Now we test for 50-move draws. Determine ply count */
8643                 count = forwardMostMove;
8644                 /* look for last irreversble move */
8645                 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
8646                     count--;
8647                 /* if we hit starting position, add initial plies */
8648                 if( count == backwardMostMove )
8649                     count -= initialRulePlies;
8650                 count = forwardMostMove - count;
8651                 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
8652                         // adjust reversible move counter for checks in Xiangqi
8653                         int i = forwardMostMove - count, inCheck = 0, lastCheck;
8654                         if(i < backwardMostMove) i = backwardMostMove;
8655                         while(i <= forwardMostMove) {
8656                                 lastCheck = inCheck; // check evasion does not count
8657                                 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
8658                                 if(inCheck || lastCheck) count--; // check does not count
8659                                 i++;
8660                         }
8661                 }
8662                 if( count >= 100 && gameInfo.variant != VariantMakruk) // do not accept 50-move claims in Makruk
8663                          boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
8664                          /* this is used to judge if draw claims are legal */
8665                 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
8666                          if(engineOpponent) {
8667                            SendToProgram("force\n", engineOpponent); // suppress reply
8668                            SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8669                          }
8670                          GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
8671                          return 1;
8672                 }
8673
8674                 /* if draw offer is pending, treat it as a draw claim
8675                  * when draw condition present, to allow engines a way to
8676                  * claim draws before making their move to avoid a race
8677                  * condition occurring after their move
8678                  */
8679                 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
8680                          char *p = NULL;
8681                          if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
8682                              p = "Draw claim: 50-move rule";
8683                          if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
8684                              p = "Draw claim: 3-fold repetition";
8685                          if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
8686                              p = "Draw claim: insufficient mating material";
8687                          if( p != NULL && canAdjudicate) {
8688                              if(engineOpponent) {
8689                                SendToProgram("force\n", engineOpponent); // suppress reply
8690                                SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8691                              }
8692                              GameEnds( GameIsDrawn, p, GE_XBOARD );
8693                              return 1;
8694                          }
8695                 }
8696
8697                 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
8698                     if(engineOpponent) {
8699                       SendToProgram("force\n", engineOpponent); // suppress reply
8700                       SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8701                     }
8702                     GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
8703                     return 1;
8704                 }
8705         return 0;
8706 }
8707
8708 typedef int (CDECL *PPROBE_EGBB) (int player, int *piece, int *square);
8709 typedef int (CDECL *PLOAD_EGBB) (char *path, int cache_size, int load_options);
8710 static int egbbCode[] = { 6, 5, 4, 3, 2, 1 };
8711
8712 static int
8713 BitbaseProbe ()
8714 {
8715     int pieces[10], squares[10], cnt=0, r, f, res;
8716     static int loaded;
8717     static PPROBE_EGBB probeBB;
8718     if(!appData.testLegality) return 10;
8719     if(BOARD_HEIGHT != 8 || BOARD_RGHT-BOARD_LEFT != 8) return 12;
8720     if(gameInfo.holdingsSize && gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess) return 12;
8721     if(loaded == 2 && forwardMostMove < 2) loaded = 0; // retry on new game
8722     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
8723         ChessSquare piece = boards[forwardMostMove][r][f];
8724         int black = (piece >= BlackPawn);
8725         int type = piece - black*BlackPawn;
8726         if(piece == EmptySquare) continue;
8727         if(type != WhiteKing && type > WhiteQueen) return 12; // unorthodox piece
8728         if(type == WhiteKing) type = WhiteQueen + 1;
8729         type = egbbCode[type];
8730         squares[cnt] = r*(BOARD_RGHT - BOARD_LEFT) + f - BOARD_LEFT;
8731         pieces[cnt] = type + black*6;
8732         if(++cnt > 5) return 11;
8733     }
8734     pieces[cnt] = squares[cnt] = 0;
8735     // probe EGBB
8736     if(loaded == 2) return 13; // loading failed before
8737     if(loaded == 0) {
8738         char *p, *path = strstr(appData.egtFormats, "scorpio:"), buf[MSG_SIZ];
8739         HMODULE lib;
8740         PLOAD_EGBB loadBB;
8741         loaded = 2; // prepare for failure
8742         if(!path) return 13; // no egbb installed
8743         strncpy(buf, path + 8, MSG_SIZ);
8744         if(p = strchr(buf, ',')) *p = NULLCHAR; else p = buf + strlen(buf);
8745         snprintf(p, MSG_SIZ - strlen(buf), "%c%s", SLASH, EGBB_NAME);
8746         lib = LoadLibrary(buf);
8747         if(!lib) { DisplayError(_("could not load EGBB library"), 0); return 13; }
8748         loadBB = (PLOAD_EGBB) GetProcAddress(lib, "load_egbb_xmen");
8749         probeBB = (PPROBE_EGBB) GetProcAddress(lib, "probe_egbb_xmen");
8750         if(!loadBB || !probeBB) { DisplayError(_("wrong EGBB version"), 0); return 13; }
8751         p[1] = NULLCHAR; loadBB(buf, 64*1028, 2); // 2 = SMART_LOAD
8752         loaded = 1; // success!
8753     }
8754     res = probeBB(forwardMostMove & 1, pieces, squares);
8755     return res > 0 ? 1 : res < 0 ? -1 : 0;
8756 }
8757
8758 char *
8759 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
8760 {   // [HGM] book: this routine intercepts moves to simulate book replies
8761     char *bookHit = NULL;
8762
8763     if(cps->drawDepth && BitbaseProbe() == 0) { // [HG} egbb: reduce depth in drawn position
8764         char buf[MSG_SIZ];
8765         snprintf(buf, MSG_SIZ, "sd %d\n", cps->drawDepth);
8766         SendToProgram(buf, cps);
8767     }
8768     //first determine if the incoming move brings opponent into his book
8769     if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
8770         bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
8771     if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
8772     if(bookHit != NULL && !cps->bookSuspend) {
8773         // make sure opponent is not going to reply after receiving move to book position
8774         SendToProgram("force\n", cps);
8775         cps->bookSuspend = TRUE; // flag indicating it has to be restarted
8776     }
8777     if(bookHit) setboardSpoiledMachineBlack = FALSE; // suppress 'go' in SendMoveToProgram
8778     if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
8779     // now arrange restart after book miss
8780     if(bookHit) {
8781         // after a book hit we never send 'go', and the code after the call to this routine
8782         // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
8783         char buf[MSG_SIZ], *move = bookHit;
8784         if(cps->useSAN) {
8785             int fromX, fromY, toX, toY;
8786             char promoChar;
8787             ChessMove moveType;
8788             move = buf + 30;
8789             if (ParseOneMove(bookHit, forwardMostMove, &moveType,
8790                                  &fromX, &fromY, &toX, &toY, &promoChar)) {
8791                 (void) CoordsToAlgebraic(boards[forwardMostMove],
8792                                     PosFlags(forwardMostMove),
8793                                     fromY, fromX, toY, toX, promoChar, move);
8794             } else {
8795                 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
8796                 bookHit = NULL;
8797             }
8798         }
8799         snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
8800         SendToProgram(buf, cps);
8801         if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
8802     } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
8803         SendToProgram("go\n", cps);
8804         cps->bookSuspend = FALSE; // after a 'go' we are never suspended
8805     } else { // 'go' might be sent based on 'firstMove' after this routine returns
8806         if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
8807             SendToProgram("go\n", cps);
8808         cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
8809     }
8810     return bookHit; // notify caller of hit, so it can take action to send move to opponent
8811 }
8812
8813 int
8814 LoadError (char *errmess, ChessProgramState *cps)
8815 {   // unloads engine and switches back to -ncp mode if it was first
8816     if(cps->initDone) return FALSE;
8817     cps->isr = NULL; // this should suppress further error popups from breaking pipes
8818     DestroyChildProcess(cps->pr, 9 ); // just to be sure
8819     cps->pr = NoProc;
8820     if(cps == &first) {
8821         appData.noChessProgram = TRUE;
8822         gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
8823         gameMode = BeginningOfGame; ModeHighlight();
8824         SetNCPMode();
8825     }
8826     if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
8827     DisplayMessage("", ""); // erase waiting message
8828     if(errmess) DisplayError(errmess, 0); // announce reason, if given
8829     return TRUE;
8830 }
8831
8832 char *savedMessage;
8833 ChessProgramState *savedState;
8834 void
8835 DeferredBookMove (void)
8836 {
8837         if(savedState->lastPing != savedState->lastPong)
8838                     ScheduleDelayedEvent(DeferredBookMove, 10);
8839         else
8840         HandleMachineMove(savedMessage, savedState);
8841 }
8842
8843 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8844 static ChessProgramState *stalledEngine;
8845 static char stashedInputMove[MSG_SIZ], abortEngineThink;
8846
8847 void
8848 HandleMachineMove (char *message, ChessProgramState *cps)
8849 {
8850     static char firstLeg[20], legs;
8851     char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8852     char realname[MSG_SIZ];
8853     int fromX, fromY, toX, toY;
8854     ChessMove moveType;
8855     char promoChar, roar;
8856     char *p, *pv=buf1;
8857     int oldError;
8858     char *bookHit;
8859
8860     if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8861         // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8862         if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8863             DisplayError(_("Invalid pairing from pairing engine"), 0);
8864             return;
8865         }
8866         pairingReceived = 1;
8867         NextMatchGame();
8868         return; // Skim the pairing messages here.
8869     }
8870
8871     oldError = cps->userError; cps->userError = 0;
8872
8873 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8874     /*
8875      * Kludge to ignore BEL characters
8876      */
8877     while (*message == '\007') message++;
8878
8879     /*
8880      * [HGM] engine debug message: ignore lines starting with '#' character
8881      */
8882     if(cps->debug && *message == '#') return;
8883
8884     /*
8885      * Look for book output
8886      */
8887     if (cps == &first && bookRequested) {
8888         if (message[0] == '\t' || message[0] == ' ') {
8889             /* Part of the book output is here; append it */
8890             strcat(bookOutput, message);
8891             strcat(bookOutput, "  \n");
8892             return;
8893         } else if (bookOutput[0] != NULLCHAR) {
8894             /* All of book output has arrived; display it */
8895             char *p = bookOutput;
8896             while (*p != NULLCHAR) {
8897                 if (*p == '\t') *p = ' ';
8898                 p++;
8899             }
8900             DisplayInformation(bookOutput);
8901             bookRequested = FALSE;
8902             /* Fall through to parse the current output */
8903         }
8904     }
8905
8906     /*
8907      * Look for machine move.
8908      */
8909     if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8910         (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8911     {
8912         if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
8913             if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
8914             safeStrCpy(stashedInputMove, message, MSG_SIZ);
8915             stalledEngine = cps;
8916             if(appData.ponderNextMove) { // bring opponent out of ponder
8917                 if(gameMode == TwoMachinesPlay) {
8918                     if(cps->other->pause)
8919                         PauseEngine(cps->other);
8920                     else
8921                         SendToProgram("easy\n", cps->other);
8922                 }
8923             }
8924             StopClocks();
8925             return;
8926         }
8927
8928       if(cps->usePing) {
8929
8930         /* This method is only useful on engines that support ping */
8931         if(abortEngineThink) {
8932             if (appData.debugMode) {
8933                 fprintf(debugFP, "Undoing move from aborted think of %s\n", cps->which);
8934             }
8935             SendToProgram("undo\n", cps);
8936             return;
8937         }
8938
8939         if (cps->lastPing != cps->lastPong) {
8940             /* Extra move from before last new; ignore */
8941             if (appData.debugMode) {
8942                 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8943             }
8944           return;
8945         }
8946
8947       } else {
8948
8949         int machineWhite = FALSE;
8950
8951         switch (gameMode) {
8952           case BeginningOfGame:
8953             /* Extra move from before last reset; ignore */
8954             if (appData.debugMode) {
8955                 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8956             }
8957             return;
8958
8959           case EndOfGame:
8960           case IcsIdle:
8961           default:
8962             /* Extra move after we tried to stop.  The mode test is
8963                not a reliable way of detecting this problem, but it's
8964                the best we can do on engines that don't support ping.
8965             */
8966             if (appData.debugMode) {
8967                 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8968                         cps->which, gameMode);
8969             }
8970             SendToProgram("undo\n", cps);
8971             return;
8972
8973           case MachinePlaysWhite:
8974           case IcsPlayingWhite:
8975             machineWhite = TRUE;
8976             break;
8977
8978           case MachinePlaysBlack:
8979           case IcsPlayingBlack:
8980             machineWhite = FALSE;
8981             break;
8982
8983           case TwoMachinesPlay:
8984             machineWhite = (cps->twoMachinesColor[0] == 'w');
8985             break;
8986         }
8987         if (WhiteOnMove(forwardMostMove) != machineWhite) {
8988             if (appData.debugMode) {
8989                 fprintf(debugFP,
8990                         "Ignoring move out of turn by %s, gameMode %d"
8991                         ", forwardMost %d\n",
8992                         cps->which, gameMode, forwardMostMove);
8993             }
8994             return;
8995         }
8996       }
8997
8998         if(cps->alphaRank) AlphaRank(machineMove, 4);
8999
9000         // [HGM] lion: (some very limited) support for Alien protocol
9001         killX = killY = kill2X = kill2Y = -1;
9002         if(machineMove[strlen(machineMove)-1] == ',') { // move ends in coma: non-final leg of composite move
9003             if(legs++) return;                     // middle leg contains only redundant info, ignore (but count it)
9004             safeStrCpy(firstLeg, machineMove, 20); // just remember it for processing when second leg arrives
9005             return;
9006         }
9007         if(p = strchr(machineMove, ',')) {         // we got both legs in one (happens on book move)
9008             char *q = strchr(p+1, ',');            // second comma?
9009             safeStrCpy(firstLeg, machineMove, 20); // kludge: fake we received the first leg earlier, and clip it off
9010             if(q) legs = 2, p = q; else legs = 1;  // with 3-leg move we clipof first two legs!
9011             safeStrCpy(machineMove, firstLeg + (p - machineMove) + 1, 20);
9012         }
9013         if(firstLeg[0]) { // there was a previous leg;
9014             // only support case where same piece makes two step
9015             char buf[20], *p = machineMove+1, *q = buf+1, f;
9016             safeStrCpy(buf, machineMove, 20);
9017             while(isdigit(*q)) q++; // find start of to-square
9018             safeStrCpy(machineMove, firstLeg, 20);
9019             while(isdigit(*p)) p++; // to-square of first leg (which is now copied to machineMove)
9020             if(legs == 2) sscanf(p, "%c%d", &f, &kill2Y), kill2X = f - AAA, kill2Y -= ONE - '0'; // in 3-leg move 2nd kill is to-sqr of 1st leg
9021             else if(*p == *buf)   // if first-leg to not equal to second-leg from first leg says unmodified (assume it is King move of castling)
9022             safeStrCpy(p, q, 20); // glue to-square of second leg to from-square of first, to process over-all move
9023             sscanf(buf, "%c%d", &f, &killY); killX = f - AAA; killY -= ONE - '0'; // pass intermediate square to MakeMove in global
9024             firstLeg[0] = NULLCHAR; legs = 0;
9025         }
9026
9027         if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
9028                               &fromX, &fromY, &toX, &toY, &promoChar)) {
9029             /* Machine move could not be parsed; ignore it. */
9030           snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
9031                     machineMove, _(cps->which));
9032             DisplayMoveError(buf1);
9033             snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c via %c%c, %c%c) res=%d",
9034                     machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, killX+AAA, killY+ONE, kill2X+AAA, kill2Y+ONE, moveType);
9035             if (gameMode == TwoMachinesPlay) {
9036               GameEnds(cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9037                        buf1, GE_XBOARD);
9038             }
9039             return;
9040         }
9041
9042         /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
9043         /* So we have to redo legality test with true e.p. status here,  */
9044         /* to make sure an illegal e.p. capture does not slip through,   */
9045         /* to cause a forfeit on a justified illegal-move complaint      */
9046         /* of the opponent.                                              */
9047         if( gameMode==TwoMachinesPlay && appData.testLegality ) {
9048            ChessMove moveType;
9049            moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
9050                              fromY, fromX, toY, toX, promoChar);
9051             if(moveType == IllegalMove) {
9052               snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
9053                         machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
9054                 GameEnds(cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9055                            buf1, GE_XBOARD);
9056                 return;
9057            } else if(!appData.fischerCastling)
9058            /* [HGM] Kludge to handle engines that send FRC-style castling
9059               when they shouldn't (like TSCP-Gothic) */
9060            switch(moveType) {
9061              case WhiteASideCastleFR:
9062              case BlackASideCastleFR:
9063                toX+=2;
9064                currentMoveString[2]++;
9065                break;
9066              case WhiteHSideCastleFR:
9067              case BlackHSideCastleFR:
9068                toX--;
9069                currentMoveString[2]--;
9070                break;
9071              default: ; // nothing to do, but suppresses warning of pedantic compilers
9072            }
9073         }
9074         hintRequested = FALSE;
9075         lastHint[0] = NULLCHAR;
9076         bookRequested = FALSE;
9077         /* Program may be pondering now */
9078         cps->maybeThinking = TRUE;
9079         if (cps->sendTime == 2) cps->sendTime = 1;
9080         if (cps->offeredDraw) cps->offeredDraw--;
9081
9082         /* [AS] Save move info*/
9083         pvInfoList[ forwardMostMove ].score = programStats.score;
9084         pvInfoList[ forwardMostMove ].depth = programStats.depth;
9085         pvInfoList[ forwardMostMove ].time =  programStats.time; // [HGM] PGNtime: take time from engine stats
9086
9087         MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
9088
9089         /* Test suites abort the 'game' after one move */
9090         if(*appData.finger) {
9091            static FILE *f;
9092            char *fen = PositionToFEN(backwardMostMove, NULL, 0); // no counts in EPD
9093            if(!f) f = fopen(appData.finger, "w");
9094            if(f) fprintf(f, "%s bm %s;\n", fen, parseList[backwardMostMove]), fflush(f);
9095            else { DisplayFatalError("Bad output file", errno, 0); return; }
9096            free(fen);
9097            GameEnds(GameUnfinished, NULL, GE_XBOARD);
9098         }
9099         if(appData.epd) {
9100            if(solvingTime >= 0) {
9101               snprintf(buf1, MSG_SIZ, "%d. %4.2fs: %s ", matchGame, solvingTime/100., parseList[backwardMostMove]);
9102               totalTime += solvingTime; first.matchWins++; solvingTime = -1;
9103            } else {
9104               snprintf(buf1, MSG_SIZ, "%d. %s?%s ", matchGame, parseList[backwardMostMove], solvingTime == -2 ? " ???" : "");
9105               if(solvingTime == -2) second.matchWins++;
9106            }
9107            OutputKibitz(2, buf1);
9108            GameEnds(GameUnfinished, NULL, GE_XBOARD);
9109         }
9110
9111         /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
9112         if( gameMode == TwoMachinesPlay && appData.adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
9113             int count = 0;
9114
9115             while( count < adjudicateLossPlies ) {
9116                 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
9117
9118                 if( count & 1 ) {
9119                     score = -score; /* Flip score for winning side */
9120                 }
9121
9122                 if( score > appData.adjudicateLossThreshold ) {
9123                     break;
9124                 }
9125
9126                 count++;
9127             }
9128
9129             if( count >= adjudicateLossPlies ) {
9130                 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
9131
9132                 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
9133                     "Xboard adjudication",
9134                     GE_XBOARD );
9135
9136                 return;
9137             }
9138         }
9139
9140         if(Adjudicate(cps)) {
9141             ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
9142             return; // [HGM] adjudicate: for all automatic game ends
9143         }
9144
9145 #if ZIPPY
9146         if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
9147             first.initDone) {
9148           if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
9149                 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
9150                 SendToICS("draw ");
9151                 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
9152           }
9153           SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
9154           ics_user_moved = 1;
9155           if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
9156                 char buf[3*MSG_SIZ];
9157
9158                 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
9159                         programStats.score / 100.,
9160                         programStats.depth,
9161                         programStats.time / 100.,
9162                         (unsigned int)programStats.nodes,
9163                         (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
9164                         programStats.movelist);
9165                 SendToICS(buf);
9166           }
9167         }
9168 #endif
9169
9170         /* [AS] Clear stats for next move */
9171         ClearProgramStats();
9172         thinkOutput[0] = NULLCHAR;
9173         hiddenThinkOutputState = 0;
9174
9175         bookHit = NULL;
9176         if (gameMode == TwoMachinesPlay) {
9177             /* [HGM] relaying draw offers moved to after reception of move */
9178             /* and interpreting offer as claim if it brings draw condition */
9179             if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
9180                 SendToProgram("draw\n", cps->other);
9181             }
9182             if (cps->other->sendTime) {
9183                 SendTimeRemaining(cps->other,
9184                                   cps->other->twoMachinesColor[0] == 'w');
9185             }
9186             bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
9187             if (firstMove && !bookHit) {
9188                 firstMove = FALSE;
9189                 if (cps->other->useColors) {
9190                   SendToProgram(cps->other->twoMachinesColor, cps->other);
9191                 }
9192                 SendToProgram("go\n", cps->other);
9193             }
9194             cps->other->maybeThinking = TRUE;
9195         }
9196
9197         roar = (killX >= 0 && IS_LION(boards[forwardMostMove][toY][toX]));
9198
9199         ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
9200
9201         if (!pausing && appData.ringBellAfterMoves) {
9202             if(!roar) RingBell();
9203         }
9204
9205         /*
9206          * Reenable menu items that were disabled while
9207          * machine was thinking
9208          */
9209         if (gameMode != TwoMachinesPlay)
9210             SetUserThinkingEnables();
9211
9212         // [HGM] book: after book hit opponent has received move and is now in force mode
9213         // force the book reply into it, and then fake that it outputted this move by jumping
9214         // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
9215         if(bookHit) {
9216                 static char bookMove[MSG_SIZ]; // a bit generous?
9217
9218                 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
9219                 strcat(bookMove, bookHit);
9220                 message = bookMove;
9221                 cps = cps->other;
9222                 programStats.nodes = programStats.depth = programStats.time =
9223                 programStats.score = programStats.got_only_move = 0;
9224                 sprintf(programStats.movelist, "%s (xbook)", bookHit);
9225
9226                 if(cps->lastPing != cps->lastPong) {
9227                     savedMessage = message; // args for deferred call
9228                     savedState = cps;
9229                     ScheduleDelayedEvent(DeferredBookMove, 10);
9230                     return;
9231                 }
9232                 goto FakeBookMove;
9233         }
9234
9235         return;
9236     }
9237
9238     /* Set special modes for chess engines.  Later something general
9239      *  could be added here; for now there is just one kludge feature,
9240      *  needed because Crafty 15.10 and earlier don't ignore SIGINT
9241      *  when "xboard" is given as an interactive command.
9242      */
9243     if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
9244         cps->useSigint = FALSE;
9245         cps->useSigterm = FALSE;
9246     }
9247     if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
9248       ParseFeatures(message+8, cps); if(tryNr < 3) tryNr = 3;
9249       return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
9250     }
9251
9252     if (!strncmp(message, "setup ", 6) && 
9253         (!appData.testLegality || gameInfo.variant == VariantFairy || gameInfo.variant == VariantUnknown ||
9254           NonStandardBoardSize(gameInfo.variant, gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize))
9255                                         ) { // [HGM] allow first engine to define opening position
9256       int dummy, w, h, hand, s=6; char buf[MSG_SIZ], varName[MSG_SIZ];
9257       if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
9258       *buf = NULLCHAR;
9259       if(sscanf(message, "setup (%s", buf) == 1) {
9260         s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTableEsc(pieceToChar, buf, SUFFIXES);
9261         ASSIGN(appData.pieceToCharTable, buf);
9262       }
9263       dummy = sscanf(message+s, "%dx%d+%d_%s", &w, &h, &hand, varName);
9264       if(dummy >= 3) {
9265         while(message[s] && message[s++] != ' ');
9266         if(BOARD_HEIGHT != h || BOARD_WIDTH != w + 4*(hand != 0) || gameInfo.holdingsSize != hand ||
9267            dummy == 4 && gameInfo.variant != StringToVariant(varName) ) { // engine wants to change board format or variant
9268 //          if(hand <= h) deadRanks = 0; else deadRanks = hand - h, h = hand; // adapt board to over-sized holdings
9269             if(hand > h) handSize = hand; else handSize = h;
9270             appData.NrFiles = w; appData.NrRanks = h; appData.holdingsSize = hand;
9271             if(dummy == 4) gameInfo.variant = StringToVariant(varName);     // parent variant
9272           InitPosition(1); // calls InitDrawingSizes to let new parameters take effect
9273           if(*buf) SetCharTableEsc(pieceToChar, buf, SUFFIXES); // do again, for it was spoiled by InitPosition
9274           startedFromSetupPosition = FALSE;
9275         }
9276       }
9277       if(startedFromSetupPosition) return;
9278       ParseFEN(boards[0], &dummy, message+s, FALSE);
9279       DrawPosition(TRUE, boards[0]);
9280       CopyBoard(initialPosition, boards[0]);
9281       startedFromSetupPosition = TRUE;
9282       return;
9283     }
9284     if(sscanf(message, "piece %s %s", buf2, buf1) == 2) {
9285       ChessSquare piece = WhitePawn;
9286       char *p=message+6, *q, *s = SUFFIXES, ID = *p, promoted = 0;
9287       if(*p == '+') promoted++, ID = *++p;
9288       if(q = strchr(s, p[1])) ID += 64*(q - s + 1), p++;
9289       piece = CharToPiece(ID & 255); if(promoted) piece = CHUPROMOTED(piece);
9290       if(cps != &first || appData.testLegality && *engineVariant == NULLCHAR
9291       /* always accept definition of  */       && piece != WhiteFalcon && piece != BlackFalcon
9292       /* wild-card pieces.            */       && piece != WhiteCobra  && piece != BlackCobra
9293       /* For variants we don't have   */       && gameInfo.variant != VariantBerolina
9294       /* correct rules for, we cannot */       && gameInfo.variant != VariantCylinder
9295       /* enforce legality on our own! */       && gameInfo.variant != VariantUnknown
9296                                                && gameInfo.variant != VariantGreat
9297                                                && gameInfo.variant != VariantFairy    ) return;
9298       if(piece < EmptySquare) {
9299         pieceDefs = TRUE;
9300         ASSIGN(pieceDesc[piece], buf1);
9301         if((ID & 32) == 0 && p[1] == '&') { ASSIGN(pieceDesc[WHITE_TO_BLACK piece], buf1); }
9302       }
9303       return;
9304     }
9305     if(!appData.testLegality && sscanf(message, "choice %s", promoRestrict) == 1) {
9306       if(deferChoice) {
9307         LeftClick(Press, 0, 0); // finish the click that was interrupted
9308       } else if(promoSweep != EmptySquare) {
9309         promoSweep = CharToPiece(currentMove&1 ? ToLower(*promoRestrict) : ToUpper(*promoRestrict));
9310         if(strlen(promoRestrict) > 1) Sweep(0);
9311       }
9312       return;
9313     }
9314     /* [HGM] Allow engine to set up a position. Don't ask me why one would
9315      * want this, I was asked to put it in, and obliged.
9316      */
9317     if (!strncmp(message, "setboard ", 9)) {
9318         Board initial_position;
9319
9320         GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
9321
9322         if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9, FALSE)) {
9323             DisplayError(_("Bad FEN received from engine"), 0);
9324             return ;
9325         } else {
9326            Reset(TRUE, FALSE);
9327            CopyBoard(boards[0], initial_position);
9328            initialRulePlies = FENrulePlies;
9329            if(blackPlaysFirst) gameMode = MachinePlaysWhite;
9330            else gameMode = MachinePlaysBlack;
9331            DrawPosition(FALSE, boards[currentMove]);
9332         }
9333         return;
9334     }
9335
9336     /*
9337      * Look for communication commands
9338      */
9339     if (!strncmp(message, "telluser ", 9)) {
9340         if(message[9] == '\\' && message[10] == '\\')
9341             EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
9342         PlayTellSound();
9343         DisplayNote(message + 9);
9344         return;
9345     }
9346     if (!strncmp(message, "tellusererror ", 14)) {
9347         cps->userError = 1;
9348         if(message[14] == '\\' && message[15] == '\\')
9349             EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
9350         PlayTellSound();
9351         DisplayError(message + 14, 0);
9352         return;
9353     }
9354     if (!strncmp(message, "tellopponent ", 13)) {
9355       if (appData.icsActive) {
9356         if (loggedOn) {
9357           snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
9358           SendToICS(buf1);
9359         }
9360       } else {
9361         DisplayNote(message + 13);
9362       }
9363       return;
9364     }
9365     if (!strncmp(message, "tellothers ", 11)) {
9366       if (appData.icsActive) {
9367         if (loggedOn) {
9368           snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
9369           SendToICS(buf1);
9370         }
9371       } else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
9372       return;
9373     }
9374     if (!strncmp(message, "tellall ", 8)) {
9375       if (appData.icsActive) {
9376         if (loggedOn) {
9377           snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
9378           SendToICS(buf1);
9379         }
9380       } else {
9381         DisplayNote(message + 8);
9382       }
9383       return;
9384     }
9385     if (strncmp(message, "warning", 7) == 0) {
9386         /* Undocumented feature, use tellusererror in new code */
9387         DisplayError(message, 0);
9388         return;
9389     }
9390     if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
9391         safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
9392         strcat(realname, " query");
9393         AskQuestion(realname, buf2, buf1, cps->pr);
9394         return;
9395     }
9396     /* Commands from the engine directly to ICS.  We don't allow these to be
9397      *  sent until we are logged on. Crafty kibitzes have been known to
9398      *  interfere with the login process.
9399      */
9400     if (loggedOn) {
9401         if (!strncmp(message, "tellics ", 8)) {
9402             SendToICS(message + 8);
9403             SendToICS("\n");
9404             return;
9405         }
9406         if (!strncmp(message, "tellicsnoalias ", 15)) {
9407             SendToICS(ics_prefix);
9408             SendToICS(message + 15);
9409             SendToICS("\n");
9410             return;
9411         }
9412         /* The following are for backward compatibility only */
9413         if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
9414             !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
9415             SendToICS(ics_prefix);
9416             SendToICS(message);
9417             SendToICS("\n");
9418             return;
9419         }
9420     }
9421     if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
9422         if(initPing == cps->lastPong) {
9423             if(gameInfo.variant == VariantUnknown) {
9424                 DisplayError(_("Engine did not send setup for non-standard variant"), 0);
9425                 *engineVariant = NULLCHAR; ASSIGN(appData.variant, "normal"); // back to normal as error recovery?
9426                 GameEnds(GameUnfinished, NULL, GE_XBOARD);
9427             }
9428             initPing = -1;
9429         }
9430         if(cps->lastPing == cps->lastPong && abortEngineThink) {
9431             abortEngineThink = FALSE;
9432             DisplayMessage("", "");
9433             ThawUI();
9434         }
9435         return;
9436     }
9437     if(!strncmp(message, "highlight ", 10)) {
9438         if(appData.testLegality && !*engineVariant && appData.markers) return;
9439         MarkByFEN(message+10); // [HGM] alien: allow engine to mark board squares
9440         return;
9441     }
9442     if(!strncmp(message, "click ", 6)) {
9443         char f, c=0; int x, y; // [HGM] alien: allow engine to finish user moves (i.e. engine-driven one-click moving)
9444         if(appData.testLegality || !appData.oneClick) return;
9445         sscanf(message+6, "%c%d%c", &f, &y, &c);
9446         x = f - 'a' + BOARD_LEFT, y -= ONE - '0';
9447         if(flipView) x = BOARD_WIDTH-1 - x; else y = BOARD_HEIGHT-1 - y;
9448         x = x*squareSize + (x+1)*lineGap + squareSize/2;
9449         y = y*squareSize + (y+1)*lineGap + squareSize/2;
9450         f = first.highlight; first.highlight = 0; // kludge to suppress lift/put in response to own clicks
9451         if(lastClickType == Press) // if button still down, fake release on same square, to be ready for next click
9452             LeftClick(Release, lastLeftX, lastLeftY);
9453         controlKey  = (c == ',');
9454         LeftClick(Press, x, y);
9455         LeftClick(Release, x, y);
9456         first.highlight = f;
9457         return;
9458     }
9459     if(strncmp(message, "uciok", 5) == 0) { // response to "uci" probe
9460         appData.isUCI[0] = isUCI = 1;
9461         ReplaceEngine(&first, 0); // retry install as UCI
9462         return;
9463     }
9464     /*
9465      * If the move is illegal, cancel it and redraw the board.
9466      * Also deal with other error cases.  Matching is rather loose
9467      * here to accommodate engines written before the spec.
9468      */
9469     if (strncmp(message + 1, "llegal move", 11) == 0 ||
9470         strncmp(message, "Error", 5) == 0) {
9471         if (StrStr(message, "name") ||
9472             StrStr(message, "rating") || StrStr(message, "?") ||
9473             StrStr(message, "result") || StrStr(message, "board") ||
9474             StrStr(message, "bk") || StrStr(message, "computer") ||
9475             StrStr(message, "variant") || StrStr(message, "hint") ||
9476             StrStr(message, "random") || StrStr(message, "depth") ||
9477             StrStr(message, "accepted")) {
9478             return;
9479         }
9480         if (StrStr(message, "protover")) {
9481           /* Program is responding to input, so it's apparently done
9482              initializing, and this error message indicates it is
9483              protocol version 1.  So we don't need to wait any longer
9484              for it to initialize and send feature commands. */
9485           FeatureDone(cps, 1);
9486           cps->protocolVersion = 1;
9487           return;
9488         }
9489         cps->maybeThinking = FALSE;
9490
9491         if (StrStr(message, "draw")) {
9492             /* Program doesn't have "draw" command */
9493             cps->sendDrawOffers = 0;
9494             return;
9495         }
9496         if (cps->sendTime != 1 &&
9497             (StrStr(message, "time") || StrStr(message, "otim"))) {
9498           /* Program apparently doesn't have "time" or "otim" command */
9499           cps->sendTime = 0;
9500           return;
9501         }
9502         if (StrStr(message, "analyze")) {
9503             cps->analysisSupport = FALSE;
9504             cps->analyzing = FALSE;
9505 //          Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
9506             EditGameEvent(); // [HGM] try to preserve loaded game
9507             snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
9508             DisplayError(buf2, 0);
9509             return;
9510         }
9511         if (StrStr(message, "(no matching move)st")) {
9512           /* Special kludge for GNU Chess 4 only */
9513           cps->stKludge = TRUE;
9514           SendTimeControl(cps, movesPerSession, timeControl,
9515                           timeIncrement, appData.searchDepth,
9516                           searchTime);
9517           return;
9518         }
9519         if (StrStr(message, "(no matching move)sd")) {
9520           /* Special kludge for GNU Chess 4 only */
9521           cps->sdKludge = TRUE;
9522           SendTimeControl(cps, movesPerSession, timeControl,
9523                           timeIncrement, appData.searchDepth,
9524                           searchTime);
9525           return;
9526         }
9527         if (!StrStr(message, "llegal")) {
9528             return;
9529         }
9530         if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9531             gameMode == IcsIdle) return;
9532         if (forwardMostMove <= backwardMostMove) return;
9533         if (pausing) PauseEvent();
9534       if(appData.forceIllegal) {
9535             // [HGM] illegal: machine refused move; force position after move into it
9536           SendToProgram("force\n", cps);
9537           if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
9538                 // we have a real problem now, as SendBoard will use the a2a3 kludge
9539                 // when black is to move, while there might be nothing on a2 or black
9540                 // might already have the move. So send the board as if white has the move.
9541                 // But first we must change the stm of the engine, as it refused the last move
9542                 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
9543                 if(WhiteOnMove(forwardMostMove)) {
9544                     SendToProgram("a7a6\n", cps); // for the engine black still had the move
9545                     SendBoard(cps, forwardMostMove); // kludgeless board
9546                 } else {
9547                     SendToProgram("a2a3\n", cps); // for the engine white still had the move
9548                     CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9549                     SendBoard(cps, forwardMostMove+1); // kludgeless board
9550                 }
9551           } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
9552             if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
9553                  gameMode == TwoMachinesPlay)
9554               SendToProgram("go\n", cps);
9555             return;
9556       } else
9557         if (gameMode == PlayFromGameFile) {
9558             /* Stop reading this game file */
9559             gameMode = EditGame;
9560             ModeHighlight();
9561         }
9562         /* [HGM] illegal-move claim should forfeit game when Xboard */
9563         /* only passes fully legal moves                            */
9564         if( appData.testLegality && gameMode == TwoMachinesPlay ) {
9565             GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9566                                 "False illegal-move claim", GE_XBOARD );
9567             return; // do not take back move we tested as valid
9568         }
9569         currentMove = forwardMostMove-1;
9570         DisplayMove(currentMove-1); /* before DisplayMoveError */
9571         SwitchClocks(forwardMostMove-1); // [HGM] race
9572         DisplayBothClocks();
9573         snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
9574                 parseList[currentMove], _(cps->which));
9575         DisplayMoveError(buf1);
9576         DrawPosition(FALSE, boards[currentMove]);
9577
9578         SetUserThinkingEnables();
9579         return;
9580     }
9581     if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
9582         /* Program has a broken "time" command that
9583            outputs a string not ending in newline.
9584            Don't use it. */
9585         cps->sendTime = 0;
9586     }
9587     if (cps->pseudo) { // [HGM] pseudo-engine, granted unusual powers
9588         if (sscanf(message, "wtime %ld\n", &whiteTimeRemaining) == 1 || // adjust clock times
9589             sscanf(message, "btime %ld\n", &blackTimeRemaining) == 1   ) return;
9590     }
9591
9592     /*
9593      * If chess program startup fails, exit with an error message.
9594      * Attempts to recover here are futile. [HGM] Well, we try anyway
9595      */
9596     if ((StrStr(message, "unknown host") != NULL)
9597         || (StrStr(message, "No remote directory") != NULL)
9598         || (StrStr(message, "not found") != NULL)
9599         || (StrStr(message, "No such file") != NULL)
9600         || (StrStr(message, "can't alloc") != NULL)
9601         || (StrStr(message, "Permission denied") != NULL)) {
9602
9603         cps->maybeThinking = FALSE;
9604         snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
9605                 _(cps->which), cps->program, cps->host, message);
9606         RemoveInputSource(cps->isr);
9607         if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
9608             if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
9609             if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
9610         }
9611         return;
9612     }
9613
9614     /*
9615      * Look for hint output
9616      */
9617     if (sscanf(message, "Hint: %s", buf1) == 1) {
9618         if (cps == &first && hintRequested) {
9619             hintRequested = FALSE;
9620             if (ParseOneMove(buf1, forwardMostMove, &moveType,
9621                                  &fromX, &fromY, &toX, &toY, &promoChar)) {
9622                 (void) CoordsToAlgebraic(boards[forwardMostMove],
9623                                     PosFlags(forwardMostMove),
9624                                     fromY, fromX, toY, toX, promoChar, buf1);
9625                 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
9626                 DisplayInformation(buf2);
9627             } else {
9628                 /* Hint move could not be parsed!? */
9629               snprintf(buf2, sizeof(buf2),
9630                         _("Illegal hint move \"%s\"\nfrom %s chess program"),
9631                         buf1, _(cps->which));
9632                 DisplayError(buf2, 0);
9633             }
9634         } else {
9635           safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
9636         }
9637         return;
9638     }
9639
9640     /*
9641      * Ignore other messages if game is not in progress
9642      */
9643     if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9644         gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
9645
9646     /*
9647      * look for win, lose, draw, or draw offer
9648      */
9649     if (strncmp(message, "1-0", 3) == 0) {
9650         char *p, *q, *r = "";
9651         p = strchr(message, '{');
9652         if (p) {
9653             q = strchr(p, '}');
9654             if (q) {
9655                 *q = NULLCHAR;
9656                 r = p + 1;
9657             }
9658         }
9659         GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
9660         return;
9661     } else if (strncmp(message, "0-1", 3) == 0) {
9662         char *p, *q, *r = "";
9663         p = strchr(message, '{');
9664         if (p) {
9665             q = strchr(p, '}');
9666             if (q) {
9667                 *q = NULLCHAR;
9668                 r = p + 1;
9669             }
9670         }
9671         /* Kludge for Arasan 4.1 bug */
9672         if (strcmp(r, "Black resigns") == 0) {
9673             GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
9674             return;
9675         }
9676         GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
9677         return;
9678     } else if (strncmp(message, "1/2", 3) == 0) {
9679         char *p, *q, *r = "";
9680         p = strchr(message, '{');
9681         if (p) {
9682             q = strchr(p, '}');
9683             if (q) {
9684                 *q = NULLCHAR;
9685                 r = p + 1;
9686             }
9687         }
9688
9689         GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
9690         return;
9691
9692     } else if (strncmp(message, "White resign", 12) == 0) {
9693         GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9694         return;
9695     } else if (strncmp(message, "Black resign", 12) == 0) {
9696         GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9697         return;
9698     } else if (strncmp(message, "White matches", 13) == 0 ||
9699                strncmp(message, "Black matches", 13) == 0   ) {
9700         /* [HGM] ignore GNUShogi noises */
9701         return;
9702     } else if (strncmp(message, "White", 5) == 0 &&
9703                message[5] != '(' &&
9704                StrStr(message, "Black") == NULL) {
9705         GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9706         return;
9707     } else if (strncmp(message, "Black", 5) == 0 &&
9708                message[5] != '(') {
9709         GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9710         return;
9711     } else if (strcmp(message, "resign") == 0 ||
9712                strcmp(message, "computer resigns") == 0) {
9713         switch (gameMode) {
9714           case MachinePlaysBlack:
9715           case IcsPlayingBlack:
9716             GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
9717             break;
9718           case MachinePlaysWhite:
9719           case IcsPlayingWhite:
9720             GameEnds(BlackWins, "White resigns", GE_ENGINE);
9721             break;
9722           case TwoMachinesPlay:
9723             if (cps->twoMachinesColor[0] == 'w')
9724               GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9725             else
9726               GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9727             break;
9728           default:
9729             /* can't happen */
9730             break;
9731         }
9732         return;
9733     } else if (strncmp(message, "opponent mates", 14) == 0) {
9734         switch (gameMode) {
9735           case MachinePlaysBlack:
9736           case IcsPlayingBlack:
9737             GameEnds(WhiteWins, "White mates", GE_ENGINE);
9738             break;
9739           case MachinePlaysWhite:
9740           case IcsPlayingWhite:
9741             GameEnds(BlackWins, "Black mates", GE_ENGINE);
9742             break;
9743           case TwoMachinesPlay:
9744             if (cps->twoMachinesColor[0] == 'w')
9745               GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9746             else
9747               GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9748             break;
9749           default:
9750             /* can't happen */
9751             break;
9752         }
9753         return;
9754     } else if (strncmp(message, "computer mates", 14) == 0) {
9755         switch (gameMode) {
9756           case MachinePlaysBlack:
9757           case IcsPlayingBlack:
9758             GameEnds(BlackWins, "Black mates", GE_ENGINE1);
9759             break;
9760           case MachinePlaysWhite:
9761           case IcsPlayingWhite:
9762             GameEnds(WhiteWins, "White mates", GE_ENGINE);
9763             break;
9764           case TwoMachinesPlay:
9765             if (cps->twoMachinesColor[0] == 'w')
9766               GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9767             else
9768               GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9769             break;
9770           default:
9771             /* can't happen */
9772             break;
9773         }
9774         return;
9775     } else if (strncmp(message, "checkmate", 9) == 0) {
9776         if (WhiteOnMove(forwardMostMove)) {
9777             GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9778         } else {
9779             GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9780         }
9781         return;
9782     } else if (strstr(message, "Draw") != NULL ||
9783                strstr(message, "game is a draw") != NULL) {
9784         GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
9785         return;
9786     } else if (strstr(message, "offer") != NULL &&
9787                strstr(message, "draw") != NULL) {
9788 #if ZIPPY
9789         if (appData.zippyPlay && first.initDone) {
9790             /* Relay offer to ICS */
9791             SendToICS(ics_prefix);
9792             SendToICS("draw\n");
9793         }
9794 #endif
9795         cps->offeredDraw = 2; /* valid until this engine moves twice */
9796         if (gameMode == TwoMachinesPlay) {
9797             if (cps->other->offeredDraw) {
9798                 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9799             /* [HGM] in two-machine mode we delay relaying draw offer      */
9800             /* until after we also have move, to see if it is really claim */
9801             }
9802         } else if (gameMode == MachinePlaysWhite ||
9803                    gameMode == MachinePlaysBlack) {
9804           if (userOfferedDraw) {
9805             DisplayInformation(_("Machine accepts your draw offer"));
9806             GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9807           } else {
9808             DisplayInformation(_("Machine offers a draw.\nSelect Action / Draw to accept."));
9809           }
9810         }
9811     }
9812
9813
9814     /*
9815      * Look for thinking output
9816      */
9817     if ( appData.showThinking // [HGM] thinking: test all options that cause this output
9818           || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9819                                 ) {
9820         int plylev, mvleft, mvtot, curscore, time;
9821         char mvname[MOVE_LEN];
9822         u64 nodes; // [DM]
9823         char plyext;
9824         int ignore = FALSE;
9825         int prefixHint = FALSE;
9826         mvname[0] = NULLCHAR;
9827
9828         switch (gameMode) {
9829           case MachinePlaysBlack:
9830           case IcsPlayingBlack:
9831             if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9832             break;
9833           case MachinePlaysWhite:
9834           case IcsPlayingWhite:
9835             if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9836             break;
9837           case AnalyzeMode:
9838           case AnalyzeFile:
9839             break;
9840           case IcsObserving: /* [DM] icsEngineAnalyze */
9841             if (!appData.icsEngineAnalyze) ignore = TRUE;
9842             break;
9843           case TwoMachinesPlay:
9844             if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
9845                 ignore = TRUE;
9846             }
9847             break;
9848           default:
9849             ignore = TRUE;
9850             break;
9851         }
9852
9853         if (!ignore) {
9854             ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
9855             int solved = 0;
9856             buf1[0] = NULLCHAR;
9857             if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9858                        &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
9859                 char score_buf[MSG_SIZ];
9860
9861                 if(nodes>>32 == u64Const(0xFFFFFFFF))   // [HGM] negative node count read
9862                     nodes += u64Const(0x100000000);
9863
9864                 if (plyext != ' ' && plyext != '\t') {
9865                     time *= 100;
9866                 }
9867
9868                 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9869                 if( cps->scoreIsAbsolute &&
9870                     ( gameMode == MachinePlaysBlack ||
9871                       gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
9872                       gameMode == IcsPlayingBlack ||     // [HGM] also add other situations where engine should report black POV
9873                      (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
9874                      !WhiteOnMove(currentMove)
9875                     ) )
9876                 {
9877                     curscore = -curscore;
9878                 }
9879
9880                 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
9881
9882                 if(*bestMove) { // rememer time best EPD move was first found
9883                     int ff1, tf1, fr1, tr1, ff2, tf2, fr2, tr2; char pp1, pp2;
9884                     ChessMove mt; char *p = bestMove;
9885                     int ok = ParseOneMove(pv, forwardMostMove, &mt, &ff2, &fr2, &tf2, &tr2, &pp2);
9886                     solved = 0;
9887                     while(ok && *p && ParseOneMove(p, forwardMostMove, &mt, &ff1, &fr1, &tf1, &tr1, &pp1)) {
9888                         if(ff1==ff2 && fr1==fr2 && tf1==tf2 && tr1==tr2 && pp1==pp2) {
9889                             solvingTime = (solvingTime < 0 ? time : solvingTime);
9890                             solved = 1;
9891                             break;
9892                         }
9893                         while(*p && *p != ' ') p++;
9894                         while(*p == ' ') p++;
9895                     }
9896                     if(!solved) solvingTime = -1;
9897                 }
9898                 if(*avoidMove && !solved) {
9899                     int ff1, tf1, fr1, tr1, ff2, tf2, fr2, tr2; char pp1, pp2;
9900                     ChessMove mt; char *p = avoidMove, solved = 1;
9901                     int ok = ParseOneMove(pv, forwardMostMove, &mt, &ff2, &fr2, &tf2, &tr2, &pp2);
9902                     while(ok && *p && ParseOneMove(p, forwardMostMove, &mt, &ff1, &fr1, &tf1, &tr1, &pp1)) {
9903                         if(ff1==ff2 && fr1==fr2 && tf1==tf2 && tr1==tr2 && pp1==pp2) {
9904                             solved = 0; solvingTime = -2;
9905                             break;
9906                         }
9907                         while(*p && *p != ' ') p++;
9908                         while(*p == ' ') p++;
9909                     }
9910                     if(solved && !*bestMove) solvingTime = (solvingTime < 0 ? time : solvingTime);
9911                 }
9912
9913                 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
9914                         char buf[MSG_SIZ];
9915                         FILE *f;
9916                         snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
9917                         buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
9918                                              gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
9919                         if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
9920                         if(f = fopen(buf, "w")) { // export PV to applicable PV file
9921                                 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
9922                                 fclose(f);
9923                         }
9924                         else
9925                           /* TRANSLATORS: PV = principal variation, the variation the chess engine thinks is the best for everyone */
9926                           DisplayError(_("failed writing PV"), 0);
9927                 }
9928
9929                 tempStats.depth = plylev;
9930                 tempStats.nodes = nodes;
9931                 tempStats.time = time;
9932                 tempStats.score = curscore;
9933                 tempStats.got_only_move = 0;
9934
9935                 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
9936                         int ticklen;
9937
9938                         if(cps->nps == 0) ticklen = 10*time;                    // use engine reported time
9939                         else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
9940                         if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
9941                                                 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
9942                              whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
9943                         if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
9944                                                 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
9945                              blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
9946                 }
9947
9948                 /* Buffer overflow protection */
9949                 if (pv[0] != NULLCHAR) {
9950                     if (strlen(pv) >= sizeof(tempStats.movelist)
9951                         && appData.debugMode) {
9952                         fprintf(debugFP,
9953                                 "PV is too long; using the first %u bytes.\n",
9954                                 (unsigned) sizeof(tempStats.movelist) - 1);
9955                     }
9956
9957                     safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
9958                 } else {
9959                     sprintf(tempStats.movelist, " no PV\n");
9960                 }
9961
9962                 if (tempStats.seen_stat) {
9963                     tempStats.ok_to_send = 1;
9964                 }
9965
9966                 if (strchr(tempStats.movelist, '(') != NULL) {
9967                     tempStats.line_is_book = 1;
9968                     tempStats.nr_moves = 0;
9969                     tempStats.moves_left = 0;
9970                 } else {
9971                     tempStats.line_is_book = 0;
9972                 }
9973
9974                     if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
9975                         programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
9976
9977                 SendProgramStatsToFrontend( cps, &tempStats );
9978
9979                 /*
9980                     [AS] Protect the thinkOutput buffer from overflow... this
9981                     is only useful if buf1 hasn't overflowed first!
9982                 */
9983                 if((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(forwardMostMove)) curscore *= -1;
9984                 if(curscore >= MATE_SCORE) 
9985                     snprintf(score_buf, MSG_SIZ, "#%d", curscore - MATE_SCORE);
9986                 else if(curscore <= -MATE_SCORE) 
9987                     snprintf(score_buf, MSG_SIZ, "#%d", curscore + MATE_SCORE);
9988                 else
9989                     snprintf(score_buf, MSG_SIZ, "%+.2f", ((double) curscore) / 100.0);
9990                 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%s %s%s",
9991                          plylev,
9992                          (gameMode == TwoMachinesPlay ?
9993                           ToUpper(cps->twoMachinesColor[0]) : ' '),
9994                          score_buf,
9995                          prefixHint ? lastHint : "",
9996                          prefixHint ? " " : "" );
9997
9998                 if( buf1[0] != NULLCHAR ) {
9999                     unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
10000
10001                     if( strlen(pv) > max_len ) {
10002                         if( appData.debugMode) {
10003                             fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
10004                         }
10005                         pv[max_len+1] = '\0';
10006                     }
10007
10008                     strcat( thinkOutput, pv);
10009                 }
10010
10011                 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
10012                         || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
10013                     DisplayMove(currentMove - 1);
10014                 }
10015                 return;
10016
10017             } else if ((p=StrStr(message, "(only move)")) != NULL) {
10018                 /* crafty (9.25+) says "(only move) <move>"
10019                  * if there is only 1 legal move
10020                  */
10021                 sscanf(p, "(only move) %s", buf1);
10022                 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
10023                 sprintf(programStats.movelist, "%s (only move)", buf1);
10024                 programStats.depth = 1;
10025                 programStats.nr_moves = 1;
10026                 programStats.moves_left = 1;
10027                 programStats.nodes = 1;
10028                 programStats.time = 1;
10029                 programStats.got_only_move = 1;
10030
10031                 /* Not really, but we also use this member to
10032                    mean "line isn't going to change" (Crafty
10033                    isn't searching, so stats won't change) */
10034                 programStats.line_is_book = 1;
10035
10036                 SendProgramStatsToFrontend( cps, &programStats );
10037
10038                 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
10039                            gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
10040                     DisplayMove(currentMove - 1);
10041                 }
10042                 return;
10043             } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
10044                               &time, &nodes, &plylev, &mvleft,
10045                               &mvtot, mvname) >= 5) {
10046                 /* The stat01: line is from Crafty (9.29+) in response
10047                    to the "." command */
10048                 programStats.seen_stat = 1;
10049                 cps->maybeThinking = TRUE;
10050
10051                 if (programStats.got_only_move || !appData.periodicUpdates)
10052                   return;
10053
10054                 programStats.depth = plylev;
10055                 programStats.time = time;
10056                 programStats.nodes = nodes;
10057                 programStats.moves_left = mvleft;
10058                 programStats.nr_moves = mvtot;
10059                 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
10060                 programStats.ok_to_send = 1;
10061                 programStats.movelist[0] = '\0';
10062
10063                 SendProgramStatsToFrontend( cps, &programStats );
10064
10065                 return;
10066
10067             } else if (strncmp(message,"++",2) == 0) {
10068                 /* Crafty 9.29+ outputs this */
10069                 programStats.got_fail = 2;
10070                 return;
10071
10072             } else if (strncmp(message,"--",2) == 0) {
10073                 /* Crafty 9.29+ outputs this */
10074                 programStats.got_fail = 1;
10075                 return;
10076
10077             } else if (thinkOutput[0] != NULLCHAR &&
10078                        strncmp(message, "    ", 4) == 0) {
10079                 unsigned message_len;
10080
10081                 p = message;
10082                 while (*p && *p == ' ') p++;
10083
10084                 message_len = strlen( p );
10085
10086                 /* [AS] Avoid buffer overflow */
10087                 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
10088                     strcat(thinkOutput, " ");
10089                     strcat(thinkOutput, p);
10090                 }
10091
10092                 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
10093                     strcat(programStats.movelist, " ");
10094                     strcat(programStats.movelist, p);
10095                 }
10096
10097                 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
10098                            gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
10099                     DisplayMove(currentMove - 1);
10100                 }
10101                 return;
10102             }
10103         }
10104         else {
10105             buf1[0] = NULLCHAR;
10106
10107             if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
10108                        &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
10109             {
10110                 ChessProgramStats cpstats;
10111
10112                 if (plyext != ' ' && plyext != '\t') {
10113                     time *= 100;
10114                 }
10115
10116                 /* [AS] Negate score if machine is playing black and reporting absolute scores */
10117                 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
10118                     curscore = -curscore;
10119                 }
10120
10121                 cpstats.depth = plylev;
10122                 cpstats.nodes = nodes;
10123                 cpstats.time = time;
10124                 cpstats.score = curscore;
10125                 cpstats.got_only_move = 0;
10126                 cpstats.movelist[0] = '\0';
10127
10128                 if (buf1[0] != NULLCHAR) {
10129                     safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
10130                 }
10131
10132                 cpstats.ok_to_send = 0;
10133                 cpstats.line_is_book = 0;
10134                 cpstats.nr_moves = 0;
10135                 cpstats.moves_left = 0;
10136
10137                 SendProgramStatsToFrontend( cps, &cpstats );
10138             }
10139         }
10140     }
10141 }
10142
10143
10144 /* Parse a game score from the character string "game", and
10145    record it as the history of the current game.  The game
10146    score is NOT assumed to start from the standard position.
10147    The display is not updated in any way.
10148    */
10149 void
10150 ParseGameHistory (char *game)
10151 {
10152     ChessMove moveType;
10153     int fromX, fromY, toX, toY, boardIndex, mask;
10154     char promoChar;
10155     char *p, *q;
10156     char buf[MSG_SIZ];
10157
10158     if (appData.debugMode)
10159       fprintf(debugFP, "Parsing game history: %s\n", game);
10160
10161     if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
10162     gameInfo.site = StrSave(appData.icsHost);
10163     gameInfo.date = PGNDate();
10164     gameInfo.round = StrSave("-");
10165
10166     /* Parse out names of players */
10167     while (*game == ' ') game++;
10168     p = buf;
10169     while (*game != ' ') *p++ = *game++;
10170     *p = NULLCHAR;
10171     gameInfo.white = StrSave(buf);
10172     while (*game == ' ') game++;
10173     p = buf;
10174     while (*game != ' ' && *game != '\n') *p++ = *game++;
10175     *p = NULLCHAR;
10176     gameInfo.black = StrSave(buf);
10177
10178     /* Parse moves */
10179     boardIndex = blackPlaysFirst ? 1 : 0;
10180     yynewstr(game);
10181     for (;;) {
10182         yyboardindex = boardIndex;
10183         moveType = (ChessMove) Myylex();
10184         switch (moveType) {
10185           case IllegalMove:             /* maybe suicide chess, etc. */
10186   if (appData.debugMode) {
10187     fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
10188     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
10189     setbuf(debugFP, NULL);
10190   }
10191           case WhitePromotion:
10192           case BlackPromotion:
10193           case WhiteNonPromotion:
10194           case BlackNonPromotion:
10195           case NormalMove:
10196           case FirstLeg:
10197           case WhiteCapturesEnPassant:
10198           case BlackCapturesEnPassant:
10199           case WhiteKingSideCastle:
10200           case WhiteQueenSideCastle:
10201           case BlackKingSideCastle:
10202           case BlackQueenSideCastle:
10203           case WhiteKingSideCastleWild:
10204           case WhiteQueenSideCastleWild:
10205           case BlackKingSideCastleWild:
10206           case BlackQueenSideCastleWild:
10207           /* PUSH Fabien */
10208           case WhiteHSideCastleFR:
10209           case WhiteASideCastleFR:
10210           case BlackHSideCastleFR:
10211           case BlackASideCastleFR:
10212           /* POP Fabien */
10213             fromX = currentMoveString[0] - AAA;
10214             fromY = currentMoveString[1] - ONE;
10215             toX = currentMoveString[2] - AAA;
10216             toY = currentMoveString[3] - ONE;
10217             promoChar = currentMoveString[4];
10218             break;
10219           case WhiteDrop:
10220           case BlackDrop:
10221             if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
10222             fromX = moveType == WhiteDrop ?
10223               (int) CharToPiece(ToUpper(currentMoveString[0])) :
10224             (int) CharToPiece(ToLower(currentMoveString[0]));
10225             fromY = DROP_RANK;
10226             toX = currentMoveString[2] - AAA;
10227             toY = currentMoveString[3] - ONE;
10228             promoChar = NULLCHAR;
10229             break;
10230           case AmbiguousMove:
10231             /* bug? */
10232             snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
10233   if (appData.debugMode) {
10234     fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
10235     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
10236     setbuf(debugFP, NULL);
10237   }
10238             DisplayError(buf, 0);
10239             return;
10240           case ImpossibleMove:
10241             /* bug? */
10242             snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
10243   if (appData.debugMode) {
10244     fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
10245     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
10246     setbuf(debugFP, NULL);
10247   }
10248             DisplayError(buf, 0);
10249             return;
10250           case EndOfFile:
10251             if (boardIndex < backwardMostMove) {
10252                 /* Oops, gap.  How did that happen? */
10253                 DisplayError(_("Gap in move list"), 0);
10254                 return;
10255             }
10256             backwardMostMove =  blackPlaysFirst ? 1 : 0;
10257             if (boardIndex > forwardMostMove) {
10258                 forwardMostMove = boardIndex;
10259             }
10260             return;
10261           case ElapsedTime:
10262             if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
10263                 strcat(parseList[boardIndex-1], " ");
10264                 strcat(parseList[boardIndex-1], yy_text);
10265             }
10266             continue;
10267           case Comment:
10268           case PGNTag:
10269           case NAG:
10270           default:
10271             /* ignore */
10272             continue;
10273           case WhiteWins:
10274           case BlackWins:
10275           case GameIsDrawn:
10276           case GameUnfinished:
10277             if (gameMode == IcsExamining) {
10278                 if (boardIndex < backwardMostMove) {
10279                     /* Oops, gap.  How did that happen? */
10280                     return;
10281                 }
10282                 backwardMostMove = blackPlaysFirst ? 1 : 0;
10283                 return;
10284             }
10285             gameInfo.result = moveType;
10286             p = strchr(yy_text, '{');
10287             if (p == NULL) p = strchr(yy_text, '(');
10288             if (p == NULL) {
10289                 p = yy_text;
10290                 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
10291             } else {
10292                 q = strchr(p, *p == '{' ? '}' : ')');
10293                 if (q != NULL) *q = NULLCHAR;
10294                 p++;
10295             }
10296             while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
10297             gameInfo.resultDetails = StrSave(p);
10298             continue;
10299         }
10300         if (boardIndex >= forwardMostMove &&
10301             !(gameMode == IcsObserving && ics_gamenum == -1)) {
10302             backwardMostMove = blackPlaysFirst ? 1 : 0;
10303             return;
10304         }
10305         (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
10306                                  fromY, fromX, toY, toX, promoChar,
10307                                  parseList[boardIndex]);
10308         CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
10309         /* currentMoveString is set as a side-effect of yylex */
10310         safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
10311         strcat(moveList[boardIndex], "\n");
10312         boardIndex++;
10313         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
10314         mask = (WhiteOnMove(boardIndex) ? 0xFF : 0xFF00);
10315         switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
10316           case MT_NONE:
10317           case MT_STALEMATE:
10318           default:
10319             break;
10320           case MT_CHECK:
10321             if(boards[boardIndex][CHECK_COUNT]) boards[boardIndex][CHECK_COUNT] -= mask & 0x101;
10322             if(!boards[boardIndex][CHECK_COUNT] || boards[boardIndex][CHECK_COUNT] & mask) {
10323                 if(!IS_SHOGI(gameInfo.variant)) strcat(parseList[boardIndex - 1], "+");
10324                 break;
10325             }
10326           case MT_CHECKMATE:
10327           case MT_STAINMATE:
10328             strcat(parseList[boardIndex - 1], "#");
10329             break;
10330         }
10331     }
10332 }
10333
10334
10335 /* Apply a move to the given board  */
10336 void
10337 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
10338 {
10339   ChessSquare captured = board[toY][toX], piece, pawn, king, killed, killed2; int p, rookX, oldEP, epRank, epFile, lastFile, lastRank, berolina = 0;
10340   int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess ? 3 : 1;
10341
10342     /* [HGM] compute & store e.p. status and castling rights for new position */
10343     /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
10344
10345       if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
10346       oldEP = (signed char)board[EP_STATUS]; epRank = board[EP_RANK]; epFile = board[EP_FILE]; lastFile = board[LAST_TO] & 255,lastRank = board[LAST_TO] >> 8;
10347       board[EP_STATUS] = EP_NONE;
10348       board[EP_FILE] = board[EP_RANK] = 100, board[LAST_TO] = 0x4040;
10349
10350   if (fromY == DROP_RANK) {
10351         /* must be first */
10352         if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
10353             board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
10354             return;
10355         }
10356         piece = board[toY][toX] = (ChessSquare) fromX;
10357   } else {
10358 //      ChessSquare victim;
10359       int i;
10360
10361       if( killX >= 0 && killY >= 0 ) { // [HGM] lion: Lion trampled over something
10362 //           victim = board[killY][killX],
10363            killed = board[killY][killX],
10364            board[killY][killX] = EmptySquare,
10365            board[EP_STATUS] = EP_CAPTURE;
10366            if( kill2X >= 0 && kill2Y >= 0)
10367              killed2 = board[kill2Y][kill2X], board[kill2Y][kill2X] = EmptySquare;
10368       }
10369
10370       if( board[toY][toX] != EmptySquare ) {
10371            board[EP_STATUS] = EP_CAPTURE;
10372            if( (fromX != toX || fromY != toY) && // not igui!
10373                (captured == WhiteLion && board[fromY][fromX] != BlackLion ||
10374                 captured == BlackLion && board[fromY][fromX] != WhiteLion   ) ) { // [HGM] lion: Chu Lion-capture rules
10375                board[EP_STATUS] = EP_IRON_LION; // non-Lion x Lion: no counter-strike allowed
10376            }
10377       }
10378
10379       pawn = board[fromY][fromX];
10380       if(pieceDesc[pawn] && strchr(pieceDesc[pawn], 'e')) { // piece with user-defined e.p. capture
10381         if(captured == EmptySquare && toX == epFile && (toY == (epRank & 127) || toY + (pawn < BlackPawn ? -1 : 1) == epRank - 128)) {
10382             captured = board[lastRank][lastFile]; // remove victim
10383             board[lastRank][lastFile] = EmptySquare;
10384             pawn = EmptySquare; // kludge to suppress old e.p. code
10385         }
10386       }
10387       if( pawn == WhiteLance || pawn == BlackLance ) {
10388            if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu ) {
10389                if(gameInfo.variant == VariantSpartan) board[EP_STATUS] = EP_PAWN_MOVE; // in Spartan no e.p. rights must be set
10390                else pawn += WhitePawn - WhiteLance; // Lance is Pawn-like in most variants, so let Pawn code treat it by this kludge
10391            }
10392       }
10393       if( pawn == WhitePawn ) {
10394            if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
10395                board[EP_STATUS] = EP_PAWN_MOVE;
10396            if( toY-fromY>=2) {
10397                board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY - 1 | 128*(toY - fromY > 2);
10398                if(toX>BOARD_LEFT   && board[toY][toX-1] == BlackPawn &&
10399                         gameInfo.variant != VariantBerolina || toX < fromX)
10400                       board[EP_STATUS] = toX | berolina;
10401                if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
10402                         gameInfo.variant != VariantBerolina || toX > fromX)
10403                       board[EP_STATUS] = toX;
10404                board[LAST_TO] = toX + 256*toY;
10405            }
10406       } else
10407       if( pawn == BlackPawn ) {
10408            if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
10409                board[EP_STATUS] = EP_PAWN_MOVE;
10410            if( toY-fromY<= -2) {
10411                board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY + 1 | 128*(fromY - toY > 2);
10412                if(toX>BOARD_LEFT   && board[toY][toX-1] == WhitePawn &&
10413                         gameInfo.variant != VariantBerolina || toX < fromX)
10414                       board[EP_STATUS] = toX | berolina;
10415                if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
10416                         gameInfo.variant != VariantBerolina || toX > fromX)
10417                       board[EP_STATUS] = toX;
10418                board[LAST_TO] = toX + 256*toY;
10419            }
10420        }
10421
10422        if(fromY == 0) board[TOUCHED_W] |= 1<<fromX; else // new way to keep track of virginity
10423        if(fromY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<fromX;
10424        if(toY == 0) board[TOUCHED_W] |= 1<<toX; else
10425        if(toY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<toX;
10426
10427        for(i=0; i<nrCastlingRights; i++) {
10428            if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
10429               board[CASTLING][i] == toX   && castlingRank[i] == toY
10430              ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
10431        }
10432
10433        if(gameInfo.variant == VariantSChess) { // update virginity
10434            if(fromY == 0)              board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
10435            if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
10436            if(toY == 0)                board[VIRGIN][toX]   &= ~VIRGIN_W; // loss by capture
10437            if(toY == BOARD_HEIGHT-1)   board[VIRGIN][toX]   &= ~VIRGIN_B;
10438        }
10439
10440      if (fromX == toX && fromY == toY && killX < 0) return;
10441
10442      piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
10443      king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
10444      if(gameInfo.variant == VariantKnightmate)
10445          king += (int) WhiteUnicorn - (int) WhiteKing;
10446
10447     if(pieceDesc[piece] && killX >= 0 && strchr(pieceDesc[piece], 'O') // Betza castling-enabled
10448        && (piece < BlackPawn ? killed < BlackPawn : killed >= BlackPawn)) {    // and tramples own
10449         board[toY][toX] = piece; board[fromY][fromX] = EmptySquare;
10450         board[toY][toX + (killX < fromX ? 1 : -1)] = killed;
10451         board[EP_STATUS] = EP_NONE; // capture was fake!
10452     } else
10453     if(nrCastlingRights == 0 && board[toY][toX] < EmptySquare && (piece < BlackPawn) == (board[toY][toX] < BlackPawn)) {
10454         board[fromY][fromX] = board[toY][toX]; // capture own will lead to swapping
10455         board[toY][toX] = piece;
10456         board[EP_STATUS] = EP_NONE; // capture was fake!
10457     } else
10458     /* Code added by Tord: */
10459     /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
10460     if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
10461         board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
10462       board[EP_STATUS] = EP_NONE; // capture was fake!
10463       board[fromY][fromX] = EmptySquare;
10464       board[toY][toX] = EmptySquare;
10465       if((toX > fromX) != (piece == WhiteRook)) {
10466         board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
10467       } else {
10468         board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
10469       }
10470     } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
10471                board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
10472       board[EP_STATUS] = EP_NONE;
10473       board[fromY][fromX] = EmptySquare;
10474       board[toY][toX] = EmptySquare;
10475       if((toX > fromX) != (piece == BlackRook)) {
10476         board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
10477       } else {
10478         board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
10479       }
10480     /* End of code added by Tord */
10481
10482     } else if (pieceDesc[piece] && piece == king && !strchr(pieceDesc[piece], 'O') && strchr(pieceDesc[piece], 'i')) {
10483         board[fromY][fromX] = EmptySquare; // never castle if King has virgin moves defined on it other than castling
10484         board[toY][toX] = piece;
10485     } else if (board[fromY][fromX] == king
10486         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10487         && toY == fromY && toX > fromX+1) {
10488         for(rookX=fromX+1; board[toY][rookX] == EmptySquare && rookX < BOARD_RGHT-1; rookX++)
10489                                                                                              ; // castle with nearest piece
10490         board[fromY][toX-1] = board[fromY][rookX];
10491         board[fromY][rookX] = EmptySquare;
10492         board[fromY][fromX] = EmptySquare;
10493         board[toY][toX] = king;
10494     } else if (board[fromY][fromX] == king
10495         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10496                && toY == fromY && toX < fromX-1) {
10497         for(rookX=fromX-1; board[toY][rookX] == EmptySquare && rookX > 0; rookX--)
10498                                                                                   ; // castle with nearest piece
10499         board[fromY][toX+1] = board[fromY][rookX];
10500         board[fromY][rookX] = EmptySquare;
10501         board[fromY][fromX] = EmptySquare;
10502         board[toY][toX] = king;
10503     } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
10504                 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10505                && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
10506                ) {
10507         /* white pawn promotion */
10508         board[toY][toX] = CharToPiece(ToUpper(promoChar));
10509         if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED(board[toY][toX])) == '~') /* [HGM] use shadow piece (if available) */
10510             board[toY][toX] = (ChessSquare) (PROMOTED(board[toY][toX]));
10511         board[fromY][fromX] = EmptySquare;
10512     } else if ((fromY >= BOARD_HEIGHT>>1)
10513                && (epFile == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10514                && (toX != fromX)
10515                && gameInfo.variant != VariantXiangqi
10516                && gameInfo.variant != VariantBerolina
10517                && (pawn == WhitePawn)
10518                && (board[toY][toX] == EmptySquare)) {
10519         if(lastFile == 100) lastFile = (board[fromY][toX] == BlackPawn ? toX : fromX), lastRank = fromY; // assume FIDE e.p. if victim present
10520         board[fromY][fromX] = EmptySquare;
10521         board[toY][toX] = piece;
10522         captured = board[lastRank][lastFile], board[lastRank][lastFile] = EmptySquare;
10523     } else if ((fromY == BOARD_HEIGHT-4)
10524                && (toX == fromX)
10525                && gameInfo.variant == VariantBerolina
10526                && (board[fromY][fromX] == WhitePawn)
10527                && (board[toY][toX] == EmptySquare)) {
10528         board[fromY][fromX] = EmptySquare;
10529         board[toY][toX] = WhitePawn;
10530         if(oldEP & EP_BEROLIN_A) {
10531                 captured = board[fromY][fromX-1];
10532                 board[fromY][fromX-1] = EmptySquare;
10533         }else{  captured = board[fromY][fromX+1];
10534                 board[fromY][fromX+1] = EmptySquare;
10535         }
10536     } else if (board[fromY][fromX] == king
10537         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10538                && toY == fromY && toX > fromX+1) {
10539         for(rookX=toX+1; board[toY][rookX] == EmptySquare && rookX < BOARD_RGHT - 1; rookX++)
10540                                                                                              ;
10541         board[fromY][toX-1] = board[fromY][rookX];
10542         board[fromY][rookX] = EmptySquare;
10543         board[fromY][fromX] = EmptySquare;
10544         board[toY][toX] = king;
10545     } else if (board[fromY][fromX] == king
10546         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10547                && toY == fromY && toX < fromX-1) {
10548         for(rookX=toX-1; board[toY][rookX] == EmptySquare && rookX > 0; rookX--)
10549                                                                                 ;
10550         board[fromY][toX+1] = board[fromY][rookX];
10551         board[fromY][rookX] = EmptySquare;
10552         board[fromY][fromX] = EmptySquare;
10553         board[toY][toX] = king;
10554     } else if (fromY == 7 && fromX == 3
10555                && board[fromY][fromX] == BlackKing
10556                && toY == 7 && toX == 5) {
10557         board[fromY][fromX] = EmptySquare;
10558         board[toY][toX] = BlackKing;
10559         board[fromY][7] = EmptySquare;
10560         board[toY][4] = BlackRook;
10561     } else if (fromY == 7 && fromX == 3
10562                && board[fromY][fromX] == BlackKing
10563                && toY == 7 && toX == 1) {
10564         board[fromY][fromX] = EmptySquare;
10565         board[toY][toX] = BlackKing;
10566         board[fromY][0] = EmptySquare;
10567         board[toY][2] = BlackRook;
10568     } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
10569                 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10570                && toY < promoRank && promoChar
10571                ) {
10572         /* black pawn promotion */
10573         board[toY][toX] = CharToPiece(ToLower(promoChar));
10574         if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED(board[toY][toX])) == '~') /* [HGM] use shadow piece (if available) */
10575             board[toY][toX] = (ChessSquare) (PROMOTED(board[toY][toX]));
10576         board[fromY][fromX] = EmptySquare;
10577     } else if ((fromY < BOARD_HEIGHT>>1)
10578                && (epFile == toX && epRank == toY || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10579                && (toX != fromX)
10580                && gameInfo.variant != VariantXiangqi
10581                && gameInfo.variant != VariantBerolina
10582                && (pawn == BlackPawn)
10583                && (board[toY][toX] == EmptySquare)) {
10584         if(lastFile == 100) lastFile = (board[fromY][toX] == WhitePawn ? toX : fromX), lastRank = fromY;
10585         board[fromY][fromX] = EmptySquare;
10586         board[toY][toX] = piece;
10587         captured = board[lastRank][lastFile], board[lastRank][lastFile] = EmptySquare;
10588     } else if ((fromY == 3)
10589                && (toX == fromX)
10590                && gameInfo.variant == VariantBerolina
10591                && (board[fromY][fromX] == BlackPawn)
10592                && (board[toY][toX] == EmptySquare)) {
10593         board[fromY][fromX] = EmptySquare;
10594         board[toY][toX] = BlackPawn;
10595         if(oldEP & EP_BEROLIN_A) {
10596                 captured = board[fromY][fromX-1];
10597                 board[fromY][fromX-1] = EmptySquare;
10598         }else{  captured = board[fromY][fromX+1];
10599                 board[fromY][fromX+1] = EmptySquare;
10600         }
10601     } else {
10602         ChessSquare piece = board[fromY][fromX]; // [HGM] lion: allow for igui (where from == to)
10603         board[fromY][fromX] = EmptySquare;
10604         board[toY][toX] = piece;
10605     }
10606   }
10607
10608     if (gameInfo.holdingsWidth != 0) {
10609
10610       /* !!A lot more code needs to be written to support holdings  */
10611       /* [HGM] OK, so I have written it. Holdings are stored in the */
10612       /* penultimate board files, so they are automaticlly stored   */
10613       /* in the game history.                                       */
10614       if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
10615                                 && promoChar && piece != WhitePawn && piece != BlackPawn) {
10616         /* Delete from holdings, by decreasing count */
10617         /* and erasing image if necessary            */
10618         p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
10619         if(p < (int) BlackPawn) { /* white drop */
10620              p -= (int)WhitePawn;
10621                  p = PieceToNumber((ChessSquare)p);
10622              if(p >= gameInfo.holdingsSize) p = 0;
10623              if(--board[p][BOARD_WIDTH-2] <= 0)
10624                   board[p][BOARD_WIDTH-1] = EmptySquare;
10625              if((int)board[p][BOARD_WIDTH-2] < 0)
10626                         board[p][BOARD_WIDTH-2] = 0;
10627         } else {                  /* black drop */
10628              p -= (int)BlackPawn;
10629                  p = PieceToNumber((ChessSquare)p);
10630              if(p >= gameInfo.holdingsSize) p = 0;
10631              if(--board[handSize-1-p][1] <= 0)
10632                   board[handSize-1-p][0] = EmptySquare;
10633              if((int)board[handSize-1-p][1] < 0)
10634                         board[handSize-1-p][1] = 0;
10635         }
10636       }
10637       if (captured != EmptySquare && gameInfo.holdingsSize > 0
10638           && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess        ) {
10639         /* [HGM] holdings: Add to holdings, if holdings exist */
10640         if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
10641                 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
10642                 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
10643         }
10644         p = (int) captured;
10645         if (p >= (int) BlackPawn) {
10646           p -= (int)BlackPawn;
10647           if(DEMOTED(p) >= 0 && PieceToChar(p) == '+') {
10648                   /* Restore shogi-promoted piece to its original  first */
10649                   captured = (ChessSquare) (DEMOTED(captured));
10650                   p = DEMOTED(p);
10651           }
10652           p = PieceToNumber((ChessSquare)p);
10653           if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
10654           board[p][BOARD_WIDTH-2]++;
10655           board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
10656         } else {
10657           p -= (int)WhitePawn;
10658           if(DEMOTED(p) >= 0 && PieceToChar(p) == '+') {
10659                   captured = (ChessSquare) (DEMOTED(captured));
10660                   p = DEMOTED(p);
10661           }
10662           p = PieceToNumber((ChessSquare)p);
10663           if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
10664           board[handSize-1-p][1]++;
10665           board[handSize-1-p][0] = WHITE_TO_BLACK captured;
10666         }
10667       }
10668     } else if (gameInfo.variant == VariantAtomic) {
10669       if (captured != EmptySquare) {
10670         int y, x;
10671         for (y = toY-1; y <= toY+1; y++) {
10672           for (x = toX-1; x <= toX+1; x++) {
10673             if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
10674                 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
10675               board[y][x] = EmptySquare;
10676             }
10677           }
10678         }
10679         board[toY][toX] = EmptySquare;
10680       }
10681     }
10682
10683     if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
10684         board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
10685     } else
10686     if(promoChar == '+') {
10687         /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
10688         board[toY][toX] = (ChessSquare) (CHUPROMOTED(piece));
10689         if(gameInfo.variant == VariantChuChess && (piece == WhiteKnight || piece == BlackKnight))
10690           board[toY][toX] = piece + WhiteLion - WhiteKnight; // adjust Knight promotions to Lion
10691     } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
10692         ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
10693         if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan)  // unpromoted piece specified
10694            && pieceToChar[PROMOTED(newPiece)] == '~') newPiece = PROMOTED(newPiece);// but promoted version available
10695         board[toY][toX] = newPiece;
10696     }
10697     if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10698                 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
10699         // [HGM] superchess: take promotion piece out of holdings
10700         int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
10701         if((int)piece < (int)BlackPawn) { // determine stm from piece color
10702             if(!--board[k][BOARD_WIDTH-2])
10703                 board[k][BOARD_WIDTH-1] = EmptySquare;
10704         } else {
10705             if(!--board[handSize-1-k][1])
10706                 board[handSize-1-k][0] = EmptySquare;
10707         }
10708     }
10709 }
10710
10711 /* Updates forwardMostMove */
10712 void
10713 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
10714 {
10715     int x = toX, y = toY, mask;
10716     char *s = parseList[forwardMostMove];
10717     ChessSquare p = boards[forwardMostMove][toY][toX];
10718 //    forwardMostMove++; // [HGM] bare: moved downstream
10719
10720     if(kill2X >= 0) x = kill2X, y = kill2Y; else
10721     if(killX >= 0 && killY >= 0) x = killX, y = killY; // [HGM] lion: make SAN move to intermediate square, if there is one
10722     (void) CoordsToAlgebraic(boards[forwardMostMove],
10723                              PosFlags(forwardMostMove),
10724                              fromY, fromX, y, x, (killX < 0)*promoChar,
10725                              s);
10726     if(kill2X >= 0 && kill2Y >= 0)
10727         sprintf(s + strlen(s), "x%c%d", killX + AAA, killY + ONE - '0'); // 2nd leg of 3-leg move is always capture
10728     if(killX >= 0 && killY >= 0)
10729         sprintf(s + strlen(s), "%c%c%d%c", p == EmptySquare || toX == fromX && toY == fromY || toX== kill2X && toY == kill2Y ? '-' : 'x',
10730                                            toX + AAA, toY + ONE - '0', promoChar);
10731
10732     if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
10733         int timeLeft; static int lastLoadFlag=0; int king, piece;
10734         piece = boards[forwardMostMove][fromY][fromX];
10735         king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
10736         if(gameInfo.variant == VariantKnightmate)
10737             king += (int) WhiteUnicorn - (int) WhiteKing;
10738         if(forwardMostMove == 0) {
10739             if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
10740                 fprintf(serverMoves, "%s;", UserName());
10741             else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
10742                 fprintf(serverMoves, "%s;", second.tidy);
10743             fprintf(serverMoves, "%s;", first.tidy);
10744             if(gameMode == MachinePlaysWhite)
10745                 fprintf(serverMoves, "%s;", UserName());
10746             else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
10747                 fprintf(serverMoves, "%s;", second.tidy);
10748         } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
10749         lastLoadFlag = loadFlag;
10750         // print base move
10751         fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
10752         // print castling suffix
10753         if( toY == fromY && piece == king ) {
10754             if(toX-fromX > 1)
10755                 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
10756             if(fromX-toX >1)
10757                 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
10758         }
10759         // e.p. suffix
10760         if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
10761              boards[forwardMostMove][fromY][fromX] == BlackPawn   ) &&
10762              boards[forwardMostMove][toY][toX] == EmptySquare
10763              && fromX != toX && fromY != toY)
10764                 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
10765         // promotion suffix
10766         if(promoChar != NULLCHAR) {
10767             if(fromY == 0 || fromY == BOARD_HEIGHT-1)
10768                  fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
10769                                                  ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
10770             else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
10771         }
10772         if(!loadFlag) {
10773                 char buf[MOVE_LEN*2], *p; int len;
10774             fprintf(serverMoves, "/%d/%d",
10775                pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
10776             if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
10777             else                      timeLeft = blackTimeRemaining/1000;
10778             fprintf(serverMoves, "/%d", timeLeft);
10779                 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
10780                 if(p = strchr(buf, '/')) *p = NULLCHAR; else
10781                 if(p = strchr(buf, '=')) *p = NULLCHAR;
10782                 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
10783             fprintf(serverMoves, "/%s", buf);
10784         }
10785         fflush(serverMoves);
10786     }
10787
10788     if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
10789         GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
10790       return;
10791     }
10792     UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
10793     if (commentList[forwardMostMove+1] != NULL) {
10794         free(commentList[forwardMostMove+1]);
10795         commentList[forwardMostMove+1] = NULL;
10796     }
10797     CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
10798     ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
10799     // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
10800     SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
10801     timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10802     timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10803     adjustedClock = FALSE;
10804     gameInfo.result = GameUnfinished;
10805     if (gameInfo.resultDetails != NULL) {
10806         free(gameInfo.resultDetails);
10807         gameInfo.resultDetails = NULL;
10808     }
10809     CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
10810                               moveList[forwardMostMove - 1]);
10811     mask = (WhiteOnMove(forwardMostMove) ? 0xFF : 0xFF00);
10812     switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
10813       case MT_NONE:
10814       case MT_STALEMATE:
10815       default:
10816         break;
10817       case MT_CHECK:
10818         if(boards[forwardMostMove][CHECK_COUNT]) boards[forwardMostMove][CHECK_COUNT] -= mask & 0x101;
10819         if(!boards[forwardMostMove][CHECK_COUNT] || boards[forwardMostMove][CHECK_COUNT] & mask) {
10820             if(!IS_SHOGI(gameInfo.variant)) strcat(parseList[forwardMostMove - 1], "+");
10821             break;
10822         }
10823       case MT_CHECKMATE:
10824       case MT_STAINMATE:
10825         strcat(parseList[forwardMostMove - 1], "#");
10826         break;
10827     }
10828 }
10829
10830 /* Updates currentMove if not pausing */
10831 void
10832 ShowMove (int fromX, int fromY, int toX, int toY)
10833 {
10834     int instant = (gameMode == PlayFromGameFile) ?
10835         (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
10836     if(appData.noGUI) return;
10837     if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10838         if (!instant) {
10839             if (forwardMostMove == currentMove + 1) {
10840                 AnimateMove(boards[forwardMostMove - 1],
10841                             fromX, fromY, toX, toY);
10842             }
10843         }
10844         currentMove = forwardMostMove;
10845     }
10846
10847     killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
10848
10849     if (instant) return;
10850
10851     DisplayMove(currentMove - 1);
10852     if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10853             if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
10854                 SetHighlights(fromX, fromY, toX, toY);
10855             }
10856     }
10857     DrawPosition(FALSE, boards[currentMove]);
10858     DisplayBothClocks();
10859     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
10860 }
10861
10862 void
10863 SendEgtPath (ChessProgramState *cps)
10864 {       /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
10865         char buf[MSG_SIZ], name[MSG_SIZ], *p;
10866
10867         if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
10868
10869         while(*p) {
10870             char c, *q = name+1, *r, *s;
10871
10872             name[0] = ','; // extract next format name from feature and copy with prefixed ','
10873             while(*p && *p != ',') *q++ = *p++;
10874             *q++ = ':'; *q = 0;
10875             if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
10876                 strcmp(name, ",nalimov:") == 0 ) {
10877                 // take nalimov path from the menu-changeable option first, if it is defined
10878               snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
10879                 SendToProgram(buf,cps);     // send egtbpath command for nalimov
10880             } else
10881             if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
10882                 (s = StrStr(appData.egtFormats, name)) != NULL) {
10883                 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
10884                 s = r = StrStr(s, ":") + 1; // beginning of path info
10885                 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
10886                 c = *r; *r = 0;             // temporarily null-terminate path info
10887                     *--q = 0;               // strip of trailig ':' from name
10888                     snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
10889                 *r = c;
10890                 SendToProgram(buf,cps);     // send egtbpath command for this format
10891             }
10892             if(*p == ',') p++; // read away comma to position for next format name
10893         }
10894 }
10895
10896 static int
10897 NonStandardBoardSize (VariantClass v, int boardWidth, int boardHeight, int holdingsSize)
10898 {
10899       int width = 8, height = 8, holdings = 0;             // most common sizes
10900       if( v == VariantUnknown || *engineVariant) return 0; // engine-defined name never needs prefix
10901       // correct the deviations default for each variant
10902       if( v == VariantXiangqi ) width = 9,  height = 10;
10903       if( v == VariantShogi )   width = 9,  height = 9,  holdings = 7;
10904       if( v == VariantBughouse || v == VariantCrazyhouse) holdings = 5;
10905       if( v == VariantCapablanca || v == VariantCapaRandom ||
10906           v == VariantGothic || v == VariantFalcon || v == VariantJanus )
10907                                 width = 10;
10908       if( v == VariantCourier ) width = 12;
10909       if( v == VariantSuper )                            holdings = 8;
10910       if( v == VariantGreat )   width = 10,              holdings = 8;
10911       if( v == VariantSChess )                           holdings = 7;
10912       if( v == VariantGrand )   width = 10, height = 10, holdings = 7;
10913       if( v == VariantChuChess) width = 10, height = 10;
10914       if( v == VariantChu )     width = 12, height = 12;
10915       return boardWidth >= 0   && boardWidth   != width  || // -1 is default,
10916              boardHeight >= 0  && boardHeight  != height || // and thus by definition OK
10917              holdingsSize >= 0 && holdingsSize != holdings;
10918 }
10919
10920 char variantError[MSG_SIZ];
10921
10922 char *
10923 SupportedVariant (char *list, VariantClass v, int boardWidth, int boardHeight, int holdingsSize, int proto, char *engine)
10924 {     // returns error message (recognizable by upper-case) if engine does not support the variant
10925       char *p, *variant = VariantName(v);
10926       static char b[MSG_SIZ];
10927       if(NonStandardBoardSize(v, boardWidth, boardHeight, holdingsSize)) { /* [HGM] make prefix for non-standard board size. */
10928            snprintf(b, MSG_SIZ, "%dx%d+%d_%s", boardWidth, boardHeight,
10929                                                holdingsSize, variant); // cook up sized variant name
10930            /* [HGM] varsize: try first if this deviant size variant is specifically known */
10931            if(StrStr(list, b) == NULL) {
10932                // specific sized variant not known, check if general sizing allowed
10933                if(proto != 1 && StrStr(list, "boardsize") == NULL) {
10934                    snprintf(variantError, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
10935                             boardWidth, boardHeight, holdingsSize, engine);
10936                    return NULL;
10937                }
10938                /* [HGM] here we really should compare with the maximum supported board size */
10939            }
10940       } else snprintf(b, MSG_SIZ,"%s", variant);
10941       if(proto == 1) return b; // for protocol 1 we cannot check and hope for the best
10942       p = StrStr(list, b);
10943       while(p && (p != list && p[-1] != ',' || p[strlen(b)] && p[strlen(b)] != ',') ) p = StrStr(p+1, b);
10944       if(p == NULL) {
10945           // occurs not at all in list, or only as sub-string
10946           snprintf(variantError, MSG_SIZ, _("Variant %s not supported by %s"), b, engine);
10947           if(p = StrStr(list, b)) { // handle requesting parent variant when only size-overridden is supported
10948               int l = strlen(variantError);
10949               char *q;
10950               while(p != list && p[-1] != ',') p--;
10951               q = strchr(p, ',');
10952               if(q) *q = NULLCHAR;
10953               snprintf(variantError + l, MSG_SIZ - l,  _(", but %s is"), p);
10954               if(q) *q= ',';
10955           }
10956           return NULL;
10957       }
10958       return b;
10959 }
10960
10961 void
10962 InitChessProgram (ChessProgramState *cps, int setup)
10963 /* setup needed to setup FRC opening position */
10964 {
10965     char buf[MSG_SIZ], *b;
10966     if (appData.noChessProgram) return;
10967     hintRequested = FALSE;
10968     bookRequested = FALSE;
10969
10970     ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
10971     /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
10972     /*       moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
10973     if(cps->memSize) { /* [HGM] memory */
10974       snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
10975         SendToProgram(buf, cps);
10976     }
10977     SendEgtPath(cps); /* [HGM] EGT */
10978     if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
10979       snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
10980         SendToProgram(buf, cps);
10981     }
10982
10983     setboardSpoiledMachineBlack = FALSE;
10984     SendToProgram(cps->initString, cps);
10985     if (gameInfo.variant != VariantNormal &&
10986         gameInfo.variant != VariantLoadable
10987         /* [HGM] also send variant if board size non-standard */
10988         || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0) {
10989
10990       b = SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
10991                            gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, cps->tidy);
10992
10993       if (b == NULL) {
10994         VariantClass v;
10995         char c, *q = cps->variants, *p = strchr(q, ',');
10996         if(p) *p = NULLCHAR;
10997         v = StringToVariant(q);
10998         DisplayError(variantError, 0);
10999         if(v != VariantUnknown && cps == &first) {
11000             int w, h, s;
11001             if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
11002                 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
11003             ASSIGN(appData.variant, q);
11004             Reset(TRUE, FALSE);
11005         }
11006         if(p) *p = ',';
11007         return;
11008       }
11009
11010       snprintf(buf, MSG_SIZ, "variant %s\n", b);
11011       SendToProgram(buf, cps);
11012     }
11013     currentlyInitializedVariant = gameInfo.variant;
11014
11015     /* [HGM] send opening position in FRC to first engine */
11016     if(setup) {
11017           SendToProgram("force\n", cps);
11018           SendBoard(cps, 0);
11019           /* engine is now in force mode! Set flag to wake it up after first move. */
11020           setboardSpoiledMachineBlack = 1;
11021     }
11022
11023     if (cps->sendICS) {
11024       snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
11025       SendToProgram(buf, cps);
11026     }
11027     cps->maybeThinking = FALSE;
11028     cps->offeredDraw = 0;
11029     if (!appData.icsActive) {
11030         SendTimeControl(cps, movesPerSession, timeControl,
11031                         timeIncrement, appData.searchDepth,
11032                         searchTime);
11033     }
11034     if (appData.showThinking
11035         // [HGM] thinking: four options require thinking output to be sent
11036         || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
11037                                 ) {
11038         SendToProgram("post\n", cps);
11039     }
11040     SendToProgram("hard\n", cps);
11041     if (!appData.ponderNextMove) {
11042         /* Warning: "easy" is a toggle in GNU Chess, so don't send
11043            it without being sure what state we are in first.  "hard"
11044            is not a toggle, so that one is OK.
11045          */
11046         SendToProgram("easy\n", cps);
11047     }
11048     if (cps->usePing) {
11049       snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++cps->lastPing);
11050       SendToProgram(buf, cps);
11051     }
11052     cps->initDone = TRUE;
11053     ClearEngineOutputPane(cps == &second);
11054 }
11055
11056
11057 char *
11058 ResendOptions (ChessProgramState *cps, int toEngine)
11059 { // send the stored value of the options
11060   int i;
11061   static char buf2[MSG_SIZ*10];
11062   char buf[MSG_SIZ], *p = buf2;
11063   Option *opt = cps->option;
11064   *p = NULLCHAR;
11065   for(i=0; i<cps->nrOptions; i++, opt++) {
11066       *buf = NULLCHAR;
11067       switch(opt->type) {
11068         case Spin:
11069         case Slider:
11070         case CheckBox:
11071             if(opt->value != *(int*) (opt->name + MSG_SIZ - 104))
11072             snprintf(buf, MSG_SIZ, "%s=%d", opt->name, opt->value);
11073           break;
11074         case ComboBox:
11075             if(opt->value != *(int*) (opt->name + MSG_SIZ - 104))
11076             snprintf(buf, MSG_SIZ, "%s=%s", opt->name, opt->choice[opt->value]);
11077           break;
11078         default:
11079             if(strcmp(opt->textValue, opt->name + MSG_SIZ - 100))
11080             snprintf(buf, MSG_SIZ, "%s=%s", opt->name, opt->textValue);
11081           break;
11082         case Button:
11083         case SaveButton:
11084           continue;
11085       }
11086       if(*buf) {
11087         if(toEngine) {
11088           snprintf(buf2, MSG_SIZ, "option %s\n", buf);
11089           SendToProgram(buf2, cps);
11090         } else {
11091           if(p != buf2) *p++ = ',';
11092           strncpy(p, buf, 10*MSG_SIZ-1 - (p - buf2));
11093           while(*p) p++;
11094         }
11095       }
11096   }
11097   return buf2;
11098 }
11099
11100 void
11101 StartChessProgram (ChessProgramState *cps)
11102 {
11103     char buf[MSG_SIZ];
11104     int err;
11105
11106     if (appData.noChessProgram) return;
11107     cps->initDone = FALSE;
11108
11109     if (strcmp(cps->host, "localhost") == 0) {
11110         err = StartChildProcess(cps->program, cps->dir, &cps->pr);
11111     } else if (*appData.remoteShell == NULLCHAR) {
11112         err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
11113     } else {
11114         if (*appData.remoteUser == NULLCHAR) {
11115           snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
11116                     cps->program);
11117         } else {
11118           snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
11119                     cps->host, appData.remoteUser, cps->program);
11120         }
11121         err = StartChildProcess(buf, "", &cps->pr);
11122     }
11123
11124     if (err != 0) {
11125       snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
11126         DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
11127         if(cps != &first) return;
11128         appData.noChessProgram = TRUE;
11129         ThawUI();
11130         SetNCPMode();
11131 //      DisplayFatalError(buf, err, 1);
11132 //      cps->pr = NoProc;
11133 //      cps->isr = NULL;
11134         return;
11135     }
11136
11137     cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
11138     if (cps->protocolVersion > 1) {
11139       snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
11140       if(!cps->reload) { // do not clear options when reloading because of -xreuse
11141         cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
11142         cps->comboCnt = 0;  //                and values of combo boxes
11143       }
11144       SendToProgram(buf, cps);
11145       if(cps->reload) ResendOptions(cps, TRUE);
11146     } else {
11147       SendToProgram("xboard\n", cps);
11148     }
11149 }
11150
11151 void
11152 TwoMachinesEventIfReady P((void))
11153 {
11154   static int curMess = 0;
11155   if (first.lastPing != first.lastPong) {
11156     if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
11157     ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
11158     return;
11159   }
11160   if (second.lastPing != second.lastPong) {
11161     if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
11162     ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
11163     return;
11164   }
11165   DisplayMessage("", ""); curMess = 0;
11166   TwoMachinesEvent();
11167 }
11168
11169 char *
11170 MakeName (char *template)
11171 {
11172     time_t clock;
11173     struct tm *tm;
11174     static char buf[MSG_SIZ];
11175     char *p = buf;
11176     int i;
11177
11178     clock = time((time_t *)NULL);
11179     tm = localtime(&clock);
11180
11181     while(*p++ = *template++) if(p[-1] == '%') {
11182         switch(*template++) {
11183           case 0:   *p = 0; return buf;
11184           case 'Y': i = tm->tm_year+1900; break;
11185           case 'y': i = tm->tm_year-100; break;
11186           case 'M': i = tm->tm_mon+1; break;
11187           case 'd': i = tm->tm_mday; break;
11188           case 'h': i = tm->tm_hour; break;
11189           case 'm': i = tm->tm_min; break;
11190           case 's': i = tm->tm_sec; break;
11191           default:  i = 0;
11192         }
11193         snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
11194     }
11195     return buf;
11196 }
11197
11198 int
11199 CountPlayers (char *p)
11200 {
11201     int n = 0;
11202     while(p = strchr(p, '\n')) p++, n++; // count participants
11203     return n;
11204 }
11205
11206 FILE *
11207 WriteTourneyFile (char *results, FILE *f)
11208 {   // write tournament parameters on tourneyFile; on success return the stream pointer for closing
11209     if(f == NULL) f = fopen(appData.tourneyFile, "w");
11210     if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
11211         // create a file with tournament description
11212         fprintf(f, "-participants {%s}\n", appData.participants);
11213         fprintf(f, "-seedBase %d\n", appData.seedBase);
11214         fprintf(f, "-tourneyType %d\n", appData.tourneyType);
11215         fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
11216         fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
11217         fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
11218         fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
11219         fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
11220         fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
11221         fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
11222         fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
11223         fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
11224         fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
11225         fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
11226         fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
11227         fprintf(f, "-bookDepth %d\n", appData.bookDepth);
11228         fprintf(f, "-bookVariation %d\n", appData.bookStrength);
11229         fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
11230         fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
11231         fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
11232         fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
11233         fprintf(f, "-smpCores %d\n", appData.smpCores);
11234         if(searchTime > 0)
11235                 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
11236         else {
11237                 fprintf(f, "-mps %d\n", appData.movesPerSession);
11238                 fprintf(f, "-tc %s\n", appData.timeControl);
11239                 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
11240         }
11241         fprintf(f, "-results \"%s\"\n", results);
11242     }
11243     return f;
11244 }
11245
11246 char *command[MAXENGINES], *mnemonic[MAXENGINES];
11247
11248 void
11249 Substitute (char *participants, int expunge)
11250 {
11251     int i, changed, changes=0, nPlayers=0;
11252     char *p, *q, *r, buf[MSG_SIZ];
11253     if(participants == NULL) return;
11254     if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
11255     r = p = participants; q = appData.participants;
11256     while(*p && *p == *q) {
11257         if(*p == '\n') r = p+1, nPlayers++;
11258         p++; q++;
11259     }
11260     if(*p) { // difference
11261         while(*p && *p++ != '\n')
11262                                  ;
11263         while(*q && *q++ != '\n')
11264                                  ;
11265       changed = nPlayers;
11266         changes = 1 + (strcmp(p, q) != 0);
11267     }
11268     if(changes == 1) { // a single engine mnemonic was changed
11269         q = r; while(*q) nPlayers += (*q++ == '\n');
11270         p = buf; while(*r && (*p = *r++) != '\n') p++;
11271         *p = NULLCHAR;
11272         NamesToList(firstChessProgramNames, command, mnemonic, "all");
11273         for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
11274         if(mnemonic[i]) { // The substitute is valid
11275             FILE *f;
11276             if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
11277                 flock(fileno(f), LOCK_EX);
11278                 ParseArgsFromFile(f);
11279                 fseek(f, 0, SEEK_SET);
11280                 FREE(appData.participants); appData.participants = participants;
11281                 if(expunge) { // erase results of replaced engine
11282                     int len = strlen(appData.results), w, b, dummy;
11283                     for(i=0; i<len; i++) {
11284                         Pairing(i, nPlayers, &w, &b, &dummy);
11285                         if((w == changed || b == changed) && appData.results[i] == '*') {
11286                             DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
11287                             fclose(f);
11288                             return;
11289                         }
11290                     }
11291                     for(i=0; i<len; i++) {
11292                         Pairing(i, nPlayers, &w, &b, &dummy);
11293                         if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
11294                     }
11295                 }
11296                 WriteTourneyFile(appData.results, f);
11297                 fclose(f); // release lock
11298                 return;
11299             }
11300         } else DisplayError(_("No engine with the name you gave is installed"), 0);
11301     }
11302     if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
11303     if(changes > 1)  DisplayError(_("You can only change one engine at the time"), 0);
11304     free(participants);
11305     return;
11306 }
11307
11308 int
11309 CheckPlayers (char *participants)
11310 {
11311         int i;
11312         char buf[MSG_SIZ], *p;
11313         NamesToList(firstChessProgramNames, command, mnemonic, "all");
11314         while(p = strchr(participants, '\n')) {
11315             *p = NULLCHAR;
11316             for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
11317             if(!mnemonic[i]) {
11318                 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
11319                 *p = '\n';
11320                 DisplayError(buf, 0);
11321                 return 1;
11322             }
11323             *p = '\n';
11324             participants = p + 1;
11325         }
11326         return 0;
11327 }
11328
11329 int
11330 CreateTourney (char *name)
11331 {
11332         FILE *f;
11333         if(matchMode && strcmp(name, appData.tourneyFile)) {
11334              ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
11335         }
11336         if(name[0] == NULLCHAR) {
11337             if(appData.participants[0])
11338                 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
11339             return 0;
11340         }
11341         f = fopen(name, "r");
11342         if(f) { // file exists
11343             ASSIGN(appData.tourneyFile, name);
11344             ParseArgsFromFile(f); // parse it
11345         } else {
11346             if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
11347             if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
11348                 DisplayError(_("Not enough participants"), 0);
11349                 return 0;
11350             }
11351             if(CheckPlayers(appData.participants)) return 0;
11352             ASSIGN(appData.tourneyFile, name);
11353             if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
11354             if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
11355         }
11356         fclose(f);
11357         appData.noChessProgram = FALSE;
11358         appData.clockMode = TRUE;
11359         SetGNUMode();
11360         return 1;
11361 }
11362
11363 int
11364 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
11365 {
11366     char buf[2*MSG_SIZ], *p, *q;
11367     int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
11368     insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
11369     skip = !all && group[0]; // if group requested, we start in skip mode
11370     for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
11371         p = names; q = buf; header = 0;
11372         while(*p && *p != '\n') *q++ = *p++;
11373         *q = 0;
11374         if(*p == '\n') p++;
11375         if(buf[0] == '#') {
11376             if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
11377             depth++; // we must be entering a new group
11378             if(all) continue; // suppress printing group headers when complete list requested
11379             header = 1;
11380             if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
11381         }
11382         if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
11383         if(engineList[i]) free(engineList[i]);
11384         engineList[i] = strdup(buf);
11385         if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
11386         if(engineMnemonic[i]) free(engineMnemonic[i]);
11387         if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
11388             strcat(buf, " (");
11389             sscanf(q + 8, "%s", buf + strlen(buf));
11390             strcat(buf, ")");
11391         }
11392         engineMnemonic[i] = strdup(buf);
11393         i++;
11394     }
11395     engineList[i] = engineMnemonic[i] = NULL;
11396     return i;
11397 }
11398
11399 void
11400 SaveEngineSettings (int n)
11401 {
11402     int len; char *p, *q, *s, buf[MSG_SIZ], *optionSettings;
11403     if(!currentEngine[n] || !currentEngine[n][0]) { DisplayMessage("saving failed: engine not from list", ""); return; } // no engine from list is loaded
11404     if(*engineListFile) ParseSettingsFile(engineListFile, &engineListFile); // update engine list
11405     p = strstr(firstChessProgramNames, currentEngine[n]);
11406     if(!p) { DisplayMessage("saving failed: engine not found in list", ""); return; } // sanity check; engine could be deleted from list after loading
11407     optionSettings = ResendOptions(n ? &second : &first, FALSE);
11408     len = strlen(currentEngine[n]);
11409     q = p + len; *p = 0; // cut list into head and tail piece
11410     s = strstr(currentEngine[n], "firstOptions");
11411     if(s && (s[-1] == '-' || s[-1] == '/') && (s[12] == ' ' || s[12] == '=') && (s[13] == '"' || s[13] == '\'')) {
11412         char *r = s + 14;
11413         while(*r && *r != s[13]) r++;
11414         s[14] = 0; // cut currentEngine into head and tail part, removing old settings
11415         snprintf(buf, MSG_SIZ, "%s%s%s", currentEngine[n], optionSettings, *r ? r : "\""); // synthesize new engine line
11416     } else if(*optionSettings) {
11417         snprintf(buf, MSG_SIZ, "%s -firstOptions \"%s\"", currentEngine[n], optionSettings);
11418     }
11419     ASSIGN(currentEngine[n], buf); // updated engine line
11420     len = p - firstChessProgramNames + strlen(q) + strlen(currentEngine[n]) + 1;
11421     s = malloc(len);
11422     snprintf(s, len, "%s%s%s", firstChessProgramNames, currentEngine[n], q);
11423     FREE(firstChessProgramNames); firstChessProgramNames = s; // new list
11424     if(*engineListFile) SaveEngineList();
11425 }
11426
11427 // following implemented as macro to avoid type limitations
11428 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
11429
11430 void
11431 SwapEngines (int n)
11432 {   // swap settings for first engine and other engine (so far only some selected options)
11433     int h;
11434     char *p;
11435     if(n == 0) return;
11436     SWAP(directory, p)
11437     SWAP(chessProgram, p)
11438     SWAP(isUCI, h)
11439     SWAP(hasOwnBookUCI, h)
11440     SWAP(protocolVersion, h)
11441     SWAP(reuse, h)
11442     SWAP(scoreIsAbsolute, h)
11443     SWAP(timeOdds, h)
11444     SWAP(logo, p)
11445     SWAP(pgnName, p)
11446     SWAP(pvSAN, h)
11447     SWAP(engOptions, p)
11448     SWAP(engInitString, p)
11449     SWAP(computerString, p)
11450     SWAP(features, p)
11451     SWAP(fenOverride, p)
11452     SWAP(NPS, h)
11453     SWAP(accumulateTC, h)
11454     SWAP(drawDepth, h)
11455     SWAP(host, p)
11456     SWAP(pseudo, h)
11457 }
11458
11459 int
11460 GetEngineLine (char *s, int n)
11461 {
11462     int i;
11463     char buf[MSG_SIZ];
11464     extern char *icsNames;
11465     if(!s || !*s) return 0;
11466     NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
11467     for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
11468     if(!mnemonic[i]) return 0;
11469     if(n == 11) return 1; // just testing if there was a match
11470     snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
11471     if(n == 1) SwapEngines(n);
11472     ParseArgsFromString(buf);
11473     if(n == 1) SwapEngines(n);
11474     if(n < 2) { ASSIGN(currentEngine[n], command[i]); }
11475     if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
11476         SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
11477         ParseArgsFromString(buf);
11478     }
11479     return 1;
11480 }
11481
11482 int
11483 SetPlayer (int player, char *p)
11484 {   // [HGM] find the engine line of the partcipant given by number, and parse its options.
11485     int i;
11486     char buf[MSG_SIZ], *engineName;
11487     for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
11488     engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
11489     for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
11490     if(mnemonic[i]) {
11491         snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
11492         ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
11493         appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
11494         ParseArgsFromString(buf);
11495     } else { // no engine with this nickname is installed!
11496         snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
11497         ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
11498         matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
11499         ModeHighlight();
11500         DisplayError(buf, 0);
11501         return 0;
11502     }
11503     free(engineName);
11504     return i;
11505 }
11506
11507 char *recentEngines;
11508
11509 void
11510 RecentEngineEvent (int nr)
11511 {
11512     int n;
11513 //    SwapEngines(1); // bump first to second
11514 //    ReplaceEngine(&second, 1); // and load it there
11515     NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11516     n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
11517     if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
11518         ReplaceEngine(&first, 0);
11519         FloatToFront(&appData.recentEngineList, command[n]);
11520         ASSIGN(currentEngine[0], command[n]);
11521     }
11522 }
11523
11524 int
11525 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
11526 {   // determine players from game number
11527     int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
11528
11529     if(appData.tourneyType == 0) {
11530         roundsPerCycle = (nPlayers - 1) | 1;
11531         pairingsPerRound = nPlayers / 2;
11532     } else if(appData.tourneyType > 0) {
11533         roundsPerCycle = nPlayers - appData.tourneyType;
11534         pairingsPerRound = appData.tourneyType;
11535     }
11536     gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
11537     gamesPerCycle = gamesPerRound * roundsPerCycle;
11538     appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
11539     curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
11540     curRound = nr / gamesPerRound; nr %= gamesPerRound;
11541     curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
11542     matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
11543     roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
11544
11545     if(appData.cycleSync) *syncInterval = gamesPerCycle;
11546     if(appData.roundSync) *syncInterval = gamesPerRound;
11547
11548     if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
11549
11550     if(appData.tourneyType == 0) {
11551         if(curPairing == (nPlayers-1)/2 ) {
11552             *whitePlayer = curRound;
11553             *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
11554         } else {
11555             *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
11556             if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
11557             *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
11558             if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
11559         }
11560     } else if(appData.tourneyType > 1) {
11561         *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
11562         *whitePlayer = curRound + appData.tourneyType;
11563     } else if(appData.tourneyType > 0) {
11564         *whitePlayer = curPairing;
11565         *blackPlayer = curRound + appData.tourneyType;
11566     }
11567
11568     // take care of white/black alternation per round.
11569     // For cycles and games this is already taken care of by default, derived from matchGame!
11570     return curRound & 1;
11571 }
11572
11573 int
11574 NextTourneyGame (int nr, int *swapColors)
11575 {   // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
11576     char *p, *q;
11577     int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
11578     FILE *tf;
11579     if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
11580     tf = fopen(appData.tourneyFile, "r");
11581     if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
11582     ParseArgsFromFile(tf); fclose(tf);
11583     InitTimeControls(); // TC might be altered from tourney file
11584
11585     nPlayers = CountPlayers(appData.participants); // count participants
11586     if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
11587     *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
11588
11589     if(syncInterval) {
11590         p = q = appData.results;
11591         while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
11592         if(firstBusy/syncInterval < (nextGame/syncInterval)) {
11593             DisplayMessage(_("Waiting for other game(s)"),"");
11594             waitingForGame = TRUE;
11595             ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
11596             return 0;
11597         }
11598         waitingForGame = FALSE;
11599     }
11600
11601     if(appData.tourneyType < 0) {
11602         if(nr>=0 && !pairingReceived) {
11603             char buf[1<<16];
11604             if(pairing.pr == NoProc) {
11605                 if(!appData.pairingEngine[0]) {
11606                     DisplayFatalError(_("No pairing engine specified"), 0, 1);
11607                     return 0;
11608                 }
11609                 StartChessProgram(&pairing); // starts the pairing engine
11610             }
11611             snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
11612             SendToProgram(buf, &pairing);
11613             snprintf(buf, 1<<16, "pairing %d\n", nr+1);
11614             SendToProgram(buf, &pairing);
11615             return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
11616         }
11617         pairingReceived = 0;                              // ... so we continue here
11618         *swapColors = 0;
11619         appData.matchGames = appData.tourneyCycles * syncInterval - 1;
11620         whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
11621         matchGame = 1; roundNr = nr / syncInterval + 1;
11622     }
11623
11624     if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
11625
11626     // redefine engines, engine dir, etc.
11627     NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11628     if(first.pr == NoProc) {
11629       if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
11630       InitEngine(&first, 0);  // initialize ChessProgramStates based on new settings.
11631     }
11632     if(second.pr == NoProc) {
11633       SwapEngines(1);
11634       if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
11635       SwapEngines(1);         // and make that valid for second engine by swapping
11636       InitEngine(&second, 1);
11637     }
11638     CommonEngineInit();     // after this TwoMachinesEvent will create correct engine processes
11639     UpdateLogos(FALSE);     // leave display to ModeHiglight()
11640     return OK;
11641 }
11642
11643 void
11644 NextMatchGame ()
11645 {   // performs game initialization that does not invoke engines, and then tries to start the game
11646     int res, firstWhite, swapColors = 0;
11647     if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
11648     if(matchMode && appData.debugMode) { // [HGM] debug split: game is part of a match; we might have to create a debug file just for this game
11649         char buf[MSG_SIZ];
11650         snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
11651         if(strcmp(buf, currentDebugFile)) { // name has changed
11652             FILE *f = fopen(buf, "w");
11653             if(f) { // if opening the new file failed, just keep using the old one
11654                 ASSIGN(currentDebugFile, buf);
11655                 fclose(debugFP);
11656                 debugFP = f;
11657             }
11658             if(appData.serverFileName) {
11659                 if(serverFP) fclose(serverFP);
11660                 serverFP = fopen(appData.serverFileName, "w");
11661                 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
11662                 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
11663             }
11664         }
11665     }
11666     firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
11667     firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
11668     first.twoMachinesColor =  firstWhite ? "white\n" : "black\n";   // perform actual color assignement
11669     second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11670     appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
11671     if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
11672     Reset(FALSE, first.pr != NoProc);
11673     res = LoadGameOrPosition(matchGame); // setup game
11674     appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
11675     if(!res) return; // abort when bad game/pos file
11676     if(appData.epd) {// in EPD mode we make sure first engine is to move
11677         firstWhite = !(forwardMostMove & 1);
11678         first.twoMachinesColor =  firstWhite ? "white\n" : "black\n";   // perform actual color assignement
11679         second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11680     }
11681     TwoMachinesEvent();
11682 }
11683
11684 void
11685 UserAdjudicationEvent (int result)
11686 {
11687     ChessMove gameResult = GameIsDrawn;
11688
11689     if( result > 0 ) {
11690         gameResult = WhiteWins;
11691     }
11692     else if( result < 0 ) {
11693         gameResult = BlackWins;
11694     }
11695
11696     if( gameMode == TwoMachinesPlay ) {
11697         GameEnds( gameResult, "User adjudication", GE_XBOARD );
11698     }
11699 }
11700
11701
11702 // [HGM] save: calculate checksum of game to make games easily identifiable
11703 int
11704 StringCheckSum (char *s)
11705 {
11706         int i = 0;
11707         if(s==NULL) return 0;
11708         while(*s) i = i*259 + *s++;
11709         return i;
11710 }
11711
11712 int
11713 GameCheckSum ()
11714 {
11715         int i, sum=0;
11716         for(i=backwardMostMove; i<forwardMostMove; i++) {
11717                 sum += pvInfoList[i].depth;
11718                 sum += StringCheckSum(parseList[i]);
11719                 sum += StringCheckSum(commentList[i]);
11720                 sum *= 261;
11721         }
11722         if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
11723         return sum + StringCheckSum(commentList[i]);
11724 } // end of save patch
11725
11726 void
11727 GameEnds (ChessMove result, char *resultDetails, int whosays)
11728 {
11729     GameMode nextGameMode;
11730     int isIcsGame;
11731     char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
11732
11733     if(endingGame) return; /* [HGM] crash: forbid recursion */
11734     endingGame = 1;
11735     if(twoBoards) { // [HGM] dual: switch back to one board
11736         twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
11737         DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
11738     }
11739     if (appData.debugMode) {
11740       fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
11741               result, resultDetails ? resultDetails : "(null)", whosays);
11742     }
11743
11744     fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move the user is entering. // [HGM] lion
11745
11746     if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
11747
11748     if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
11749         /* If we are playing on ICS, the server decides when the
11750            game is over, but the engine can offer to draw, claim
11751            a draw, or resign.
11752          */
11753 #if ZIPPY
11754         if (appData.zippyPlay && first.initDone) {
11755             if (result == GameIsDrawn) {
11756                 /* In case draw still needs to be claimed */
11757                 SendToICS(ics_prefix);
11758                 SendToICS("draw\n");
11759             } else if (StrCaseStr(resultDetails, "resign")) {
11760                 SendToICS(ics_prefix);
11761                 SendToICS("resign\n");
11762             }
11763         }
11764 #endif
11765         endingGame = 0; /* [HGM] crash */
11766         return;
11767     }
11768
11769     /* If we're loading the game from a file, stop */
11770     if (whosays == GE_FILE) {
11771       (void) StopLoadGameTimer();
11772       gameFileFP = NULL;
11773     }
11774
11775     /* Cancel draw offers */
11776     first.offeredDraw = second.offeredDraw = 0;
11777
11778     /* If this is an ICS game, only ICS can really say it's done;
11779        if not, anyone can. */
11780     isIcsGame = (gameMode == IcsPlayingWhite ||
11781                  gameMode == IcsPlayingBlack ||
11782                  gameMode == IcsObserving    ||
11783                  gameMode == IcsExamining);
11784
11785     if (!isIcsGame || whosays == GE_ICS) {
11786         /* OK -- not an ICS game, or ICS said it was done */
11787         StopClocks();
11788         if (!isIcsGame && !appData.noChessProgram)
11789           SetUserThinkingEnables();
11790
11791         /* [HGM] if a machine claims the game end we verify this claim */
11792         if(gameMode == TwoMachinesPlay && appData.testClaims) {
11793             if(appData.testLegality && whosays >= GE_ENGINE1 ) {
11794                 char claimer;
11795                 ChessMove trueResult = (ChessMove) -1;
11796
11797                 claimer = whosays == GE_ENGINE1 ?      /* color of claimer */
11798                                             first.twoMachinesColor[0] :
11799                                             second.twoMachinesColor[0] ;
11800
11801                 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
11802                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
11803                     /* [HGM] verify: engine mate claims accepted if they were flagged */
11804                     trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
11805                 } else
11806                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
11807                     /* [HGM] verify: engine mate claims accepted if they were flagged */
11808                     trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
11809                 } else
11810                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
11811                     trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
11812                 }
11813
11814                 // now verify win claims, but not in drop games, as we don't understand those yet
11815                 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11816                                                  || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
11817                     (result == WhiteWins && claimer == 'w' ||
11818                      result == BlackWins && claimer == 'b'   ) ) { // case to verify: engine claims own win
11819                       if (appData.debugMode) {
11820                         fprintf(debugFP, "result=%d sp=%d move=%d\n",
11821                                 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
11822                       }
11823                       if(result != trueResult) {
11824                         snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
11825                               result = claimer == 'w' ? BlackWins : WhiteWins;
11826                               resultDetails = buf;
11827                       }
11828                 } else
11829                 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
11830                     && (forwardMostMove <= backwardMostMove ||
11831                         (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
11832                         (claimer=='b')==(forwardMostMove&1))
11833                                                                                   ) {
11834                       /* [HGM] verify: draws that were not flagged are false claims */
11835                   snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
11836                       result = claimer == 'w' ? BlackWins : WhiteWins;
11837                       resultDetails = buf;
11838                 }
11839                 /* (Claiming a loss is accepted no questions asked!) */
11840             } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
11841                 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
11842                 result = GameUnfinished;
11843                 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
11844             }
11845             /* [HGM] bare: don't allow bare King to win */
11846             if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11847                                             || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
11848                && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
11849                && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
11850                && result != GameIsDrawn)
11851             {   int i, j, k=0, oppoKings = 0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
11852                 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
11853                         int p = (int)boards[forwardMostMove][i][j] - color;
11854                         if(p >= 0 && p <= (int)WhiteKing) k++;
11855                         oppoKings += (p + color == WhiteKing + BlackPawn - color);
11856                 }
11857                 if (appData.debugMode) {
11858                      fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
11859                         result, resultDetails ? resultDetails : "(null)", whosays, k, color);
11860                 }
11861                 if(k <= 1 && oppoKings > 0) { // the latter needed in Atomic, where bare K wins if opponent King already destroyed
11862                         result = GameIsDrawn;
11863                         snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
11864                         resultDetails = buf;
11865                 }
11866             }
11867         }
11868
11869
11870         if(serverMoves != NULL && !loadFlag) { char c = '=';
11871             if(result==WhiteWins) c = '+';
11872             if(result==BlackWins) c = '-';
11873             if(resultDetails != NULL)
11874                 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
11875         }
11876         if (resultDetails != NULL) {
11877             gameInfo.result = result;
11878             gameInfo.resultDetails = StrSave(resultDetails);
11879
11880             /* display last move only if game was not loaded from file */
11881             if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
11882                 DisplayMove(currentMove - 1);
11883
11884             if (forwardMostMove != 0) {
11885                 if (gameMode != PlayFromGameFile && gameMode != EditGame
11886                     && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
11887                                                                 ) {
11888                     if (*appData.saveGameFile != NULLCHAR) {
11889                         if(result == GameUnfinished && matchMode && *appData.tourneyFile)
11890                             AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
11891                         else
11892                         SaveGameToFile(appData.saveGameFile, TRUE);
11893                     } else if (appData.autoSaveGames) {
11894                         if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
11895                     }
11896                     if (*appData.savePositionFile != NULLCHAR) {
11897                         SavePositionToFile(appData.savePositionFile);
11898                     }
11899                     AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
11900                 }
11901             }
11902
11903             /* Tell program how game ended in case it is learning */
11904             /* [HGM] Moved this to after saving the PGN, just in case */
11905             /* engine died and we got here through time loss. In that */
11906             /* case we will get a fatal error writing the pipe, which */
11907             /* would otherwise lose us the PGN.                       */
11908             /* [HGM] crash: not needed anymore, but doesn't hurt;     */
11909             /* output during GameEnds should never be fatal anymore   */
11910             if (gameMode == MachinePlaysWhite ||
11911                 gameMode == MachinePlaysBlack ||
11912                 gameMode == TwoMachinesPlay ||
11913                 gameMode == IcsPlayingWhite ||
11914                 gameMode == IcsPlayingBlack ||
11915                 gameMode == BeginningOfGame) {
11916                 char buf[MSG_SIZ];
11917                 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
11918                         resultDetails);
11919                 if (first.pr != NoProc) {
11920                     SendToProgram(buf, &first);
11921                 }
11922                 if (second.pr != NoProc &&
11923                     gameMode == TwoMachinesPlay) {
11924                     SendToProgram(buf, &second);
11925                 }
11926             }
11927         }
11928
11929         if (appData.icsActive) {
11930             if (appData.quietPlay &&
11931                 (gameMode == IcsPlayingWhite ||
11932                  gameMode == IcsPlayingBlack)) {
11933                 SendToICS(ics_prefix);
11934                 SendToICS("set shout 1\n");
11935             }
11936             nextGameMode = IcsIdle;
11937             ics_user_moved = FALSE;
11938             /* clean up premove.  It's ugly when the game has ended and the
11939              * premove highlights are still on the board.
11940              */
11941             if (gotPremove) {
11942               gotPremove = FALSE;
11943               ClearPremoveHighlights();
11944               DrawPosition(FALSE, boards[currentMove]);
11945             }
11946             if (whosays == GE_ICS) {
11947                 switch (result) {
11948                 case WhiteWins:
11949                     if (gameMode == IcsPlayingWhite)
11950                         PlayIcsWinSound();
11951                     else if(gameMode == IcsPlayingBlack)
11952                         PlayIcsLossSound();
11953                     break;
11954                 case BlackWins:
11955                     if (gameMode == IcsPlayingBlack)
11956                         PlayIcsWinSound();
11957                     else if(gameMode == IcsPlayingWhite)
11958                         PlayIcsLossSound();
11959                     break;
11960                 case GameIsDrawn:
11961                     PlayIcsDrawSound();
11962                     break;
11963                 default:
11964                     PlayIcsUnfinishedSound();
11965                 }
11966             }
11967             if(appData.quitNext) { ExitEvent(0); return; }
11968         } else if (gameMode == EditGame ||
11969                    gameMode == PlayFromGameFile ||
11970                    gameMode == AnalyzeMode ||
11971                    gameMode == AnalyzeFile) {
11972             nextGameMode = gameMode;
11973         } else {
11974             nextGameMode = EndOfGame;
11975         }
11976         pausing = FALSE;
11977         ModeHighlight();
11978     } else {
11979         nextGameMode = gameMode;
11980     }
11981
11982     if (appData.noChessProgram) {
11983         gameMode = nextGameMode;
11984         ModeHighlight();
11985         endingGame = 0; /* [HGM] crash */
11986         return;
11987     }
11988
11989     if (first.reuse) {
11990         /* Put first chess program into idle state */
11991         if (first.pr != NoProc &&
11992             (gameMode == MachinePlaysWhite ||
11993              gameMode == MachinePlaysBlack ||
11994              gameMode == TwoMachinesPlay ||
11995              gameMode == IcsPlayingWhite ||
11996              gameMode == IcsPlayingBlack ||
11997              gameMode == BeginningOfGame)) {
11998             SendToProgram("force\n", &first);
11999             if (first.usePing) {
12000               char buf[MSG_SIZ];
12001               snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
12002               SendToProgram(buf, &first);
12003             }
12004         }
12005     } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
12006         /* Kill off first chess program */
12007         if (first.isr != NULL)
12008           RemoveInputSource(first.isr);
12009         first.isr = NULL;
12010
12011         if (first.pr != NoProc) {
12012             ExitAnalyzeMode();
12013             DoSleep( appData.delayBeforeQuit );
12014             SendToProgram("quit\n", &first);
12015             DestroyChildProcess(first.pr, 4 + first.useSigterm);
12016             first.reload = TRUE;
12017         }
12018         first.pr = NoProc;
12019     }
12020     if (second.reuse) {
12021         /* Put second chess program into idle state */
12022         if (second.pr != NoProc &&
12023             gameMode == TwoMachinesPlay) {
12024             SendToProgram("force\n", &second);
12025             if (second.usePing) {
12026               char buf[MSG_SIZ];
12027               snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
12028               SendToProgram(buf, &second);
12029             }
12030         }
12031     } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
12032         /* Kill off second chess program */
12033         if (second.isr != NULL)
12034           RemoveInputSource(second.isr);
12035         second.isr = NULL;
12036
12037         if (second.pr != NoProc) {
12038             DoSleep( appData.delayBeforeQuit );
12039             SendToProgram("quit\n", &second);
12040             DestroyChildProcess(second.pr, 4 + second.useSigterm);
12041             second.reload = TRUE;
12042         }
12043         second.pr = NoProc;
12044     }
12045
12046     if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
12047         char resChar = '=';
12048         switch (result) {
12049         case WhiteWins:
12050           resChar = '+';
12051           if (first.twoMachinesColor[0] == 'w') {
12052             first.matchWins++;
12053           } else {
12054             second.matchWins++;
12055           }
12056           break;
12057         case BlackWins:
12058           resChar = '-';
12059           if (first.twoMachinesColor[0] == 'b') {
12060             first.matchWins++;
12061           } else {
12062             second.matchWins++;
12063           }
12064           break;
12065         case GameUnfinished:
12066           resChar = ' ';
12067         default:
12068           break;
12069         }
12070
12071         if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
12072         if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
12073             if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
12074             ReserveGame(nextGame, resChar); // sets nextGame
12075             if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
12076             else ranking = strdup("busy"); //suppress popup when aborted but not finished
12077         } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
12078
12079         if (nextGame <= appData.matchGames && !abortMatch) {
12080             gameMode = nextGameMode;
12081             matchGame = nextGame; // this will be overruled in tourney mode!
12082             GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
12083             ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
12084             endingGame = 0; /* [HGM] crash */
12085             return;
12086         } else {
12087             gameMode = nextGameMode;
12088             if(appData.epd) {
12089                 snprintf(buf, MSG_SIZ, "-------------------------------------- ");
12090                 OutputKibitz(2, buf);
12091                 snprintf(buf, MSG_SIZ, _("Average solving time %4.2f sec (total time %4.2f sec) "), totalTime/(100.*first.matchWins), totalTime/100.);
12092                 OutputKibitz(2, buf);
12093                 snprintf(buf, MSG_SIZ, _("%d avoid-moves played "), second.matchWins);
12094                 if(second.matchWins) OutputKibitz(2, buf);
12095                 snprintf(buf, MSG_SIZ, _("Solved %d out of %d (%3.1f%%) "), first.matchWins, nextGame-1, first.matchWins*100./(nextGame-1));
12096                 OutputKibitz(2, buf);
12097             }
12098             snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
12099                      first.tidy, second.tidy,
12100                      first.matchWins, second.matchWins,
12101                      appData.matchGames - (first.matchWins + second.matchWins));
12102             if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
12103             if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
12104             popupRequested++; // [HGM] crash: postpone to after resetting endingGame
12105             if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
12106                 first.twoMachinesColor = "black\n";
12107                 second.twoMachinesColor = "white\n";
12108             } else {
12109                 first.twoMachinesColor = "white\n";
12110                 second.twoMachinesColor = "black\n";
12111             }
12112         }
12113     }
12114     if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
12115         !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
12116       ExitAnalyzeMode();
12117     gameMode = nextGameMode;
12118     ModeHighlight();
12119     endingGame = 0;  /* [HGM] crash */
12120     if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
12121         if(matchMode == TRUE) { // match through command line: exit with or without popup
12122             if(ranking) {
12123                 ToNrEvent(forwardMostMove);
12124                 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
12125                 else ExitEvent(0);
12126             } else DisplayFatalError(buf, 0, 0);
12127         } else { // match through menu; just stop, with or without popup
12128             matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
12129             ModeHighlight();
12130             if(ranking){
12131                 if(strcmp(ranking, "busy")) DisplayNote(ranking);
12132             } else DisplayNote(buf);
12133       }
12134       if(ranking) free(ranking);
12135     }
12136 }
12137
12138 /* Assumes program was just initialized (initString sent).
12139    Leaves program in force mode. */
12140 void
12141 FeedMovesToProgram (ChessProgramState *cps, int upto)
12142 {
12143     int i;
12144
12145     if (appData.debugMode)
12146       fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
12147               startedFromSetupPosition ? "position and " : "",
12148               backwardMostMove, upto, cps->which);
12149     if(currentlyInitializedVariant != gameInfo.variant) {
12150       char buf[MSG_SIZ];
12151         // [HGM] variantswitch: make engine aware of new variant
12152         if(!SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
12153                              gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, ""))
12154                 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
12155         snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
12156         SendToProgram(buf, cps);
12157         currentlyInitializedVariant = gameInfo.variant;
12158     }
12159     SendToProgram("force\n", cps);
12160     if (startedFromSetupPosition) {
12161         SendBoard(cps, backwardMostMove);
12162     if (appData.debugMode) {
12163         fprintf(debugFP, "feedMoves\n");
12164     }
12165     }
12166     for (i = backwardMostMove; i < upto; i++) {
12167         SendMoveToProgram(i, cps);
12168     }
12169 }
12170
12171
12172 int
12173 ResurrectChessProgram ()
12174 {
12175      /* The chess program may have exited.
12176         If so, restart it and feed it all the moves made so far. */
12177     static int doInit = 0;
12178
12179     if (appData.noChessProgram) return 1;
12180
12181     if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
12182         if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
12183         if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
12184         doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
12185     } else {
12186         if (first.pr != NoProc) return 1;
12187         StartChessProgram(&first);
12188     }
12189     InitChessProgram(&first, FALSE);
12190     FeedMovesToProgram(&first, currentMove);
12191
12192     if (!first.sendTime) {
12193         /* can't tell gnuchess what its clock should read,
12194            so we bow to its notion. */
12195         ResetClocks();
12196         timeRemaining[0][currentMove] = whiteTimeRemaining;
12197         timeRemaining[1][currentMove] = blackTimeRemaining;
12198     }
12199
12200     if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
12201                 appData.icsEngineAnalyze) && first.analysisSupport) {
12202       SendToProgram("analyze\n", &first);
12203       first.analyzing = TRUE;
12204     }
12205     return 1;
12206 }
12207
12208 /*
12209  * Button procedures
12210  */
12211 void
12212 Reset (int redraw, int init)
12213 {
12214     int i;
12215
12216     if (appData.debugMode) {
12217         fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
12218                 redraw, init, gameMode);
12219     }
12220     pieceDefs = FALSE; // [HGM] gen: reset engine-defined piece moves
12221     deadRanks = 0; // assume entire board is used
12222     handSize = 0;
12223     for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; }
12224     CleanupTail(); // [HGM] vari: delete any stored variations
12225     CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
12226     pausing = pauseExamInvalid = FALSE;
12227     startedFromSetupPosition = blackPlaysFirst = FALSE;
12228     firstMove = TRUE;
12229     whiteFlag = blackFlag = FALSE;
12230     userOfferedDraw = FALSE;
12231     hintRequested = bookRequested = FALSE;
12232     first.maybeThinking = FALSE;
12233     second.maybeThinking = FALSE;
12234     first.bookSuspend = FALSE; // [HGM] book
12235     second.bookSuspend = FALSE;
12236     thinkOutput[0] = NULLCHAR;
12237     lastHint[0] = NULLCHAR;
12238     ClearGameInfo(&gameInfo);
12239     gameInfo.variant = StringToVariant(appData.variant);
12240     if(gameInfo.variant == VariantNormal && strcmp(appData.variant, "normal")) {
12241         gameInfo.variant = VariantUnknown;
12242         strncpy(engineVariant, appData.variant, MSG_SIZ);
12243     }
12244     ics_user_moved = ics_clock_paused = FALSE;
12245     ics_getting_history = H_FALSE;
12246     ics_gamenum = -1;
12247     white_holding[0] = black_holding[0] = NULLCHAR;
12248     ClearProgramStats();
12249     opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
12250
12251     ResetFrontEnd();
12252     ClearHighlights();
12253     flipView = appData.flipView;
12254     ClearPremoveHighlights();
12255     gotPremove = FALSE;
12256     alarmSounded = FALSE;
12257     killX = killY = kill2X = kill2Y = -1; // [HGM] lion
12258
12259     GameEnds(EndOfFile, NULL, GE_PLAYER);
12260     if(appData.serverMovesName != NULL) {
12261         /* [HGM] prepare to make moves file for broadcasting */
12262         clock_t t = clock();
12263         if(serverMoves != NULL) fclose(serverMoves);
12264         serverMoves = fopen(appData.serverMovesName, "r");
12265         if(serverMoves != NULL) {
12266             fclose(serverMoves);
12267             /* delay 15 sec before overwriting, so all clients can see end */
12268             while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
12269         }
12270         serverMoves = fopen(appData.serverMovesName, "w");
12271     }
12272
12273     ExitAnalyzeMode();
12274     gameMode = BeginningOfGame;
12275     ModeHighlight();
12276     if(appData.icsActive) gameInfo.variant = VariantNormal;
12277     currentMove = forwardMostMove = backwardMostMove = 0;
12278     MarkTargetSquares(1);
12279     InitPosition(redraw);
12280     for (i = 0; i < MAX_MOVES; i++) {
12281         if (commentList[i] != NULL) {
12282             free(commentList[i]);
12283             commentList[i] = NULL;
12284         }
12285     }
12286     ResetClocks();
12287     timeRemaining[0][0] = whiteTimeRemaining;
12288     timeRemaining[1][0] = blackTimeRemaining;
12289
12290     if (first.pr == NoProc) {
12291         StartChessProgram(&first);
12292     }
12293     if (init) {
12294             InitChessProgram(&first, startedFromSetupPosition);
12295     }
12296     DisplayTitle("");
12297     DisplayMessage("", "");
12298     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12299     lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
12300     ClearMap();        // [HGM] exclude: invalidate map
12301 }
12302
12303 void
12304 AutoPlayGameLoop ()
12305 {
12306     for (;;) {
12307         if (!AutoPlayOneMove())
12308           return;
12309         if (matchMode || appData.timeDelay == 0)
12310           continue;
12311         if (appData.timeDelay < 0)
12312           return;
12313         StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
12314         break;
12315     }
12316 }
12317
12318 void
12319 AnalyzeNextGame()
12320 {
12321     ReloadGame(1); // next game
12322 }
12323
12324 int
12325 AutoPlayOneMove ()
12326 {
12327     int fromX, fromY, toX, toY;
12328
12329     if (appData.debugMode) {
12330       fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
12331     }
12332
12333     if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
12334       return FALSE;
12335
12336     if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
12337       pvInfoList[currentMove].depth = programStats.depth;
12338       pvInfoList[currentMove].score = programStats.score;
12339       pvInfoList[currentMove].time  = 0;
12340       if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
12341       else { // append analysis of final position as comment
12342         char buf[MSG_SIZ];
12343         snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
12344         AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
12345       }
12346       programStats.depth = 0;
12347     }
12348
12349     if (currentMove >= forwardMostMove) {
12350       if(gameMode == AnalyzeFile) {
12351           if(appData.loadGameIndex == -1) {
12352             GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
12353           ScheduleDelayedEvent(AnalyzeNextGame, 10);
12354           } else {
12355           ExitAnalyzeMode(); SendToProgram("force\n", &first);
12356         }
12357       }
12358 //      gameMode = EndOfGame;
12359 //      ModeHighlight();
12360
12361       /* [AS] Clear current move marker at the end of a game */
12362       /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
12363
12364       return FALSE;
12365     }
12366
12367     toX = moveList[currentMove][2] - AAA;
12368     toY = moveList[currentMove][3] - ONE;
12369
12370     if (moveList[currentMove][1] == '@') {
12371         if (appData.highlightLastMove) {
12372             SetHighlights(-1, -1, toX, toY);
12373         }
12374     } else {
12375         fromX = moveList[currentMove][0] - AAA;
12376         fromY = moveList[currentMove][1] - ONE;
12377
12378         HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
12379
12380         if(moveList[currentMove][4] == ';') { // multi-leg
12381             killX = moveList[currentMove][5] - AAA;
12382             killY = moveList[currentMove][6] - ONE;
12383         }
12384         AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12385         killX = killY = -1;
12386
12387         if (appData.highlightLastMove) {
12388             SetHighlights(fromX, fromY, toX, toY);
12389         }
12390     }
12391     DisplayMove(currentMove);
12392     SendMoveToProgram(currentMove++, &first);
12393     DisplayBothClocks();
12394     DrawPosition(FALSE, boards[currentMove]);
12395     // [HGM] PV info: always display, routine tests if empty
12396     DisplayComment(currentMove - 1, commentList[currentMove]);
12397     return TRUE;
12398 }
12399
12400
12401 int
12402 LoadGameOneMove (ChessMove readAhead)
12403 {
12404     int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
12405     char promoChar = NULLCHAR;
12406     ChessMove moveType;
12407     char move[MSG_SIZ];
12408     char *p, *q;
12409
12410     if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
12411         gameMode != AnalyzeMode && gameMode != Training) {
12412         gameFileFP = NULL;
12413         return FALSE;
12414     }
12415
12416     yyboardindex = forwardMostMove;
12417     if (readAhead != EndOfFile) {
12418       moveType = readAhead;
12419     } else {
12420       if (gameFileFP == NULL)
12421           return FALSE;
12422       moveType = (ChessMove) Myylex();
12423     }
12424
12425     done = FALSE;
12426     switch (moveType) {
12427       case Comment:
12428         if (appData.debugMode)
12429           fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12430         p = yy_text;
12431
12432         /* append the comment but don't display it */
12433         AppendComment(currentMove, p, FALSE);
12434         return TRUE;
12435
12436       case WhiteCapturesEnPassant:
12437       case BlackCapturesEnPassant:
12438       case WhitePromotion:
12439       case BlackPromotion:
12440       case WhiteNonPromotion:
12441       case BlackNonPromotion:
12442       case NormalMove:
12443       case FirstLeg:
12444       case WhiteKingSideCastle:
12445       case WhiteQueenSideCastle:
12446       case BlackKingSideCastle:
12447       case BlackQueenSideCastle:
12448       case WhiteKingSideCastleWild:
12449       case WhiteQueenSideCastleWild:
12450       case BlackKingSideCastleWild:
12451       case BlackQueenSideCastleWild:
12452       /* PUSH Fabien */
12453       case WhiteHSideCastleFR:
12454       case WhiteASideCastleFR:
12455       case BlackHSideCastleFR:
12456       case BlackASideCastleFR:
12457       /* POP Fabien */
12458         if (appData.debugMode)
12459           fprintf(debugFP, "Parsed %s into %s virgin=%x,%x\n", yy_text, currentMoveString, boards[forwardMostMove][TOUCHED_W], boards[forwardMostMove][TOUCHED_B]);
12460         fromX = currentMoveString[0] - AAA;
12461         fromY = currentMoveString[1] - ONE;
12462         toX = currentMoveString[2] - AAA;
12463         toY = currentMoveString[3] - ONE;
12464         promoChar = currentMoveString[4];
12465         if(promoChar == ';') promoChar = currentMoveString[7];
12466         break;
12467
12468       case WhiteDrop:
12469       case BlackDrop:
12470         if (appData.debugMode)
12471           fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
12472         fromX = moveType == WhiteDrop ?
12473           (int) CharToPiece(ToUpper(currentMoveString[0])) :
12474         (int) CharToPiece(ToLower(currentMoveString[0]));
12475         fromY = DROP_RANK;
12476         toX = currentMoveString[2] - AAA;
12477         toY = currentMoveString[3] - ONE;
12478         break;
12479
12480       case WhiteWins:
12481       case BlackWins:
12482       case GameIsDrawn:
12483       case GameUnfinished:
12484         if (appData.debugMode)
12485           fprintf(debugFP, "Parsed game end: %s\n", yy_text);
12486         p = strchr(yy_text, '{');
12487         if (p == NULL) p = strchr(yy_text, '(');
12488         if (p == NULL) {
12489             p = yy_text;
12490             if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
12491         } else {
12492             q = strchr(p, *p == '{' ? '}' : ')');
12493             if (q != NULL) *q = NULLCHAR;
12494             p++;
12495         }
12496         while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
12497         GameEnds(moveType, p, GE_FILE);
12498         done = TRUE;
12499         if (cmailMsgLoaded) {
12500             ClearHighlights();
12501             flipView = WhiteOnMove(currentMove);
12502             if (moveType == GameUnfinished) flipView = !flipView;
12503             if (appData.debugMode)
12504               fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
12505         }
12506         break;
12507
12508       case EndOfFile:
12509         if (appData.debugMode)
12510           fprintf(debugFP, "Parser hit end of file\n");
12511         switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12512           case MT_NONE:
12513           case MT_CHECK:
12514             break;
12515           case MT_CHECKMATE:
12516           case MT_STAINMATE:
12517             if (WhiteOnMove(currentMove)) {
12518                 GameEnds(BlackWins, "Black mates", GE_FILE);
12519             } else {
12520                 GameEnds(WhiteWins, "White mates", GE_FILE);
12521             }
12522             break;
12523           case MT_STALEMATE:
12524             GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12525             break;
12526         }
12527         done = TRUE;
12528         break;
12529
12530       case MoveNumberOne:
12531         if (lastLoadGameStart == GNUChessGame) {
12532             /* GNUChessGames have numbers, but they aren't move numbers */
12533             if (appData.debugMode)
12534               fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12535                       yy_text, (int) moveType);
12536             return LoadGameOneMove(EndOfFile); /* tail recursion */
12537         }
12538         /* else fall thru */
12539
12540       case XBoardGame:
12541       case GNUChessGame:
12542       case PGNTag:
12543         /* Reached start of next game in file */
12544         if (appData.debugMode)
12545           fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
12546         switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12547           case MT_NONE:
12548           case MT_CHECK:
12549             break;
12550           case MT_CHECKMATE:
12551           case MT_STAINMATE:
12552             if (WhiteOnMove(currentMove)) {
12553                 GameEnds(BlackWins, "Black mates", GE_FILE);
12554             } else {
12555                 GameEnds(WhiteWins, "White mates", GE_FILE);
12556             }
12557             break;
12558           case MT_STALEMATE:
12559             GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12560             break;
12561         }
12562         done = TRUE;
12563         break;
12564
12565       case PositionDiagram:     /* should not happen; ignore */
12566       case ElapsedTime:         /* ignore */
12567       case NAG:                 /* ignore */
12568         if (appData.debugMode)
12569           fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12570                   yy_text, (int) moveType);
12571         return LoadGameOneMove(EndOfFile); /* tail recursion */
12572
12573       case IllegalMove:
12574         if (appData.testLegality) {
12575             if (appData.debugMode)
12576               fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
12577             snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12578                     (forwardMostMove / 2) + 1,
12579                     WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12580             DisplayError(move, 0);
12581             done = TRUE;
12582         } else {
12583             if (appData.debugMode)
12584               fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
12585                       yy_text, currentMoveString);
12586             if(currentMoveString[1] == '@') {
12587                 fromX = CharToPiece(WhiteOnMove(currentMove) ? ToUpper(currentMoveString[0]) : ToLower(currentMoveString[0]));
12588                 fromY = DROP_RANK;
12589             } else {
12590                 fromX = currentMoveString[0] - AAA;
12591                 fromY = currentMoveString[1] - ONE;
12592             }
12593             toX = currentMoveString[2] - AAA;
12594             toY = currentMoveString[3] - ONE;
12595             promoChar = currentMoveString[4];
12596         }
12597         break;
12598
12599       case AmbiguousMove:
12600         if (appData.debugMode)
12601           fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
12602         snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
12603                 (forwardMostMove / 2) + 1,
12604                 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12605         DisplayError(move, 0);
12606         done = TRUE;
12607         break;
12608
12609       default:
12610       case ImpossibleMove:
12611         if (appData.debugMode)
12612           fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
12613         snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12614                 (forwardMostMove / 2) + 1,
12615                 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12616         DisplayError(move, 0);
12617         done = TRUE;
12618         break;
12619     }
12620
12621     if (done) {
12622         if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
12623             DrawPosition(FALSE, boards[currentMove]);
12624             DisplayBothClocks();
12625             if (!appData.matchMode) // [HGM] PV info: routine tests if empty
12626               DisplayComment(currentMove - 1, commentList[currentMove]);
12627         }
12628         (void) StopLoadGameTimer();
12629         gameFileFP = NULL;
12630         cmailOldMove = forwardMostMove;
12631         return FALSE;
12632     } else {
12633         /* currentMoveString is set as a side-effect of yylex */
12634
12635         thinkOutput[0] = NULLCHAR;
12636         MakeMove(fromX, fromY, toX, toY, promoChar);
12637         killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
12638         currentMove = forwardMostMove;
12639         return TRUE;
12640     }
12641 }
12642
12643 /* Load the nth game from the given file */
12644 int
12645 LoadGameFromFile (char *filename, int n, char *title, int useList)
12646 {
12647     FILE *f;
12648     char buf[MSG_SIZ];
12649
12650     if (strcmp(filename, "-") == 0) {
12651         f = stdin;
12652         title = "stdin";
12653     } else {
12654         f = fopen(filename, "rb");
12655         if (f == NULL) {
12656           snprintf(buf, sizeof(buf),  _("Can't open \"%s\""), filename);
12657             DisplayError(buf, errno);
12658             return FALSE;
12659         }
12660     }
12661     if (fseek(f, 0, 0) == -1) {
12662         /* f is not seekable; probably a pipe */
12663         useList = FALSE;
12664     }
12665     if (useList && n == 0) {
12666         int error = GameListBuild(f);
12667         if (error) {
12668             DisplayError(_("Cannot build game list"), error);
12669         } else if (!ListEmpty(&gameList) &&
12670                    ((ListGame *) gameList.tailPred)->number > 1) {
12671             GameListPopUp(f, title);
12672             return TRUE;
12673         }
12674         GameListDestroy();
12675         n = 1;
12676     }
12677     if (n == 0) n = 1;
12678     return LoadGame(f, n, title, FALSE);
12679 }
12680
12681
12682 void
12683 MakeRegisteredMove ()
12684 {
12685     int fromX, fromY, toX, toY;
12686     char promoChar;
12687     if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12688         switch (cmailMoveType[lastLoadGameNumber - 1]) {
12689           case CMAIL_MOVE:
12690           case CMAIL_DRAW:
12691             if (appData.debugMode)
12692               fprintf(debugFP, "Restoring %s for game %d\n",
12693                       cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12694
12695             thinkOutput[0] = NULLCHAR;
12696             safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
12697             fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
12698             fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
12699             toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
12700             toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
12701             promoChar = cmailMove[lastLoadGameNumber - 1][4];
12702             MakeMove(fromX, fromY, toX, toY, promoChar);
12703             ShowMove(fromX, fromY, toX, toY);
12704
12705             switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12706               case MT_NONE:
12707               case MT_CHECK:
12708                 break;
12709
12710               case MT_CHECKMATE:
12711               case MT_STAINMATE:
12712                 if (WhiteOnMove(currentMove)) {
12713                     GameEnds(BlackWins, "Black mates", GE_PLAYER);
12714                 } else {
12715                     GameEnds(WhiteWins, "White mates", GE_PLAYER);
12716                 }
12717                 break;
12718
12719               case MT_STALEMATE:
12720                 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
12721                 break;
12722             }
12723
12724             break;
12725
12726           case CMAIL_RESIGN:
12727             if (WhiteOnMove(currentMove)) {
12728                 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12729             } else {
12730                 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12731             }
12732             break;
12733
12734           case CMAIL_ACCEPT:
12735             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12736             break;
12737
12738           default:
12739             break;
12740         }
12741     }
12742
12743     return;
12744 }
12745
12746 /* Wrapper around LoadGame for use when a Cmail message is loaded */
12747 int
12748 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
12749 {
12750     int retVal;
12751
12752     if (gameNumber > nCmailGames) {
12753         DisplayError(_("No more games in this message"), 0);
12754         return FALSE;
12755     }
12756     if (f == lastLoadGameFP) {
12757         int offset = gameNumber - lastLoadGameNumber;
12758         if (offset == 0) {
12759             cmailMsg[0] = NULLCHAR;
12760             if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12761                 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12762                 nCmailMovesRegistered--;
12763             }
12764             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12765             if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
12766                 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
12767             }
12768         } else {
12769             if (! RegisterMove()) return FALSE;
12770         }
12771     }
12772
12773     retVal = LoadGame(f, gameNumber, title, useList);
12774
12775     /* Make move registered during previous look at this game, if any */
12776     MakeRegisteredMove();
12777
12778     if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
12779         commentList[currentMove]
12780           = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
12781         DisplayComment(currentMove - 1, commentList[currentMove]);
12782     }
12783
12784     return retVal;
12785 }
12786
12787 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
12788 int
12789 ReloadGame (int offset)
12790 {
12791     int gameNumber = lastLoadGameNumber + offset;
12792     if (lastLoadGameFP == NULL) {
12793         DisplayError(_("No game has been loaded yet"), 0);
12794         return FALSE;
12795     }
12796     if (gameNumber <= 0) {
12797         DisplayError(_("Can't back up any further"), 0);
12798         return FALSE;
12799     }
12800     if (cmailMsgLoaded) {
12801         return CmailLoadGame(lastLoadGameFP, gameNumber,
12802                              lastLoadGameTitle, lastLoadGameUseList);
12803     } else {
12804         return LoadGame(lastLoadGameFP, gameNumber,
12805                         lastLoadGameTitle, lastLoadGameUseList);
12806     }
12807 }
12808
12809 int keys[EmptySquare+1];
12810
12811 int
12812 PositionMatches (Board b1, Board b2)
12813 {
12814     int r, f, sum=0;
12815     switch(appData.searchMode) {
12816         case 1: return CompareWithRights(b1, b2);
12817         case 2:
12818             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12819                 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
12820             }
12821             return TRUE;
12822         case 3:
12823             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12824               if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
12825                 sum += keys[b1[r][f]] - keys[b2[r][f]];
12826             }
12827             return sum==0;
12828         case 4:
12829             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12830                 sum += keys[b1[r][f]] - keys[b2[r][f]];
12831             }
12832             return sum==0;
12833     }
12834     return TRUE;
12835 }
12836
12837 #define Q_PROMO  4
12838 #define Q_EP     3
12839 #define Q_BCASTL 2
12840 #define Q_WCASTL 1
12841
12842 int pieceList[256], quickBoard[256];
12843 ChessSquare pieceType[256] = { EmptySquare };
12844 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
12845 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
12846 int soughtTotal, turn;
12847 Boolean epOK, flipSearch;
12848
12849 typedef struct {
12850     unsigned char piece, to;
12851 } Move;
12852
12853 #define DSIZE (250000)
12854
12855 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
12856 Move *moveDatabase = initialSpace;
12857 unsigned int movePtr, dataSize = DSIZE;
12858
12859 int
12860 MakePieceList (Board board, int *counts)
12861 {
12862     int r, f, n=Q_PROMO, total=0;
12863     for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
12864     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12865         int sq = f + (r<<4);
12866         if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
12867             quickBoard[sq] = ++n;
12868             pieceList[n] = sq;
12869             pieceType[n] = board[r][f];
12870             counts[board[r][f]]++;
12871             if(board[r][f] == WhiteKing) pieceList[1] = n; else
12872             if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
12873             total++;
12874         }
12875     }
12876     epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
12877     return total;
12878 }
12879
12880 void
12881 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
12882 {
12883     int sq = fromX + (fromY<<4);
12884     int piece = quickBoard[sq], rook;
12885     quickBoard[sq] = 0;
12886     moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
12887     if(piece == pieceList[1] && fromY == toY) {
12888       if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12889         int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
12890         moveDatabase[movePtr++].piece = Q_WCASTL;
12891         quickBoard[sq] = piece;
12892         piece = quickBoard[from]; quickBoard[from] = 0;
12893         moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12894       } else if((rook = quickBoard[sq]) && pieceType[rook] == WhiteRook) { // FRC castling
12895         quickBoard[sq] = 0; // remove Rook
12896         moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2); // King to-square
12897         moveDatabase[movePtr++].piece = Q_WCASTL;
12898         quickBoard[sq] = pieceList[1]; // put King
12899         piece = rook;
12900         moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12901       }
12902     } else
12903     if(piece == pieceList[2] && fromY == toY) {
12904       if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12905         int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
12906         moveDatabase[movePtr++].piece = Q_BCASTL;
12907         quickBoard[sq] = piece;
12908         piece = quickBoard[from]; quickBoard[from] = 0;
12909         moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12910       } else if((rook = quickBoard[sq]) && pieceType[rook] == BlackRook) { // FRC castling
12911         quickBoard[sq] = 0; // remove Rook
12912         moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2);
12913         moveDatabase[movePtr++].piece = Q_BCASTL;
12914         quickBoard[sq] = pieceList[2]; // put King
12915         piece = rook;
12916         moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12917       }
12918     } else
12919     if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
12920         quickBoard[(fromY<<4)+toX] = 0;
12921         moveDatabase[movePtr].piece = Q_EP;
12922         moveDatabase[movePtr++].to = (fromY<<4)+toX;
12923         moveDatabase[movePtr].to = sq;
12924     } else
12925     if(promoPiece != pieceType[piece]) {
12926         moveDatabase[movePtr++].piece = Q_PROMO;
12927         moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
12928     }
12929     moveDatabase[movePtr].piece = piece;
12930     quickBoard[sq] = piece;
12931     movePtr++;
12932 }
12933
12934 int
12935 PackGame (Board board)
12936 {
12937     Move *newSpace = NULL;
12938     moveDatabase[movePtr].piece = 0; // terminate previous game
12939     if(movePtr > dataSize) {
12940         if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
12941         dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
12942         if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
12943         if(newSpace) {
12944             int i;
12945             Move *p = moveDatabase, *q = newSpace;
12946             for(i=0; i<movePtr; i++) *q++ = *p++;    // copy to newly allocated space
12947             if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
12948             moveDatabase = newSpace;
12949         } else { // calloc failed, we must be out of memory. Too bad...
12950             dataSize = 0; // prevent calloc events for all subsequent games
12951             return 0;     // and signal this one isn't cached
12952         }
12953     }
12954     movePtr++;
12955     MakePieceList(board, counts);
12956     return movePtr;
12957 }
12958
12959 int
12960 QuickCompare (Board board, int *minCounts, int *maxCounts)
12961 {   // compare according to search mode
12962     int r, f;
12963     switch(appData.searchMode)
12964     {
12965       case 1: // exact position match
12966         if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
12967         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12968             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12969         }
12970         break;
12971       case 2: // can have extra material on empty squares
12972         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12973             if(board[r][f] == EmptySquare) continue;
12974             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12975         }
12976         break;
12977       case 3: // material with exact Pawn structure
12978         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12979             if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
12980             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12981         } // fall through to material comparison
12982       case 4: // exact material
12983         for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
12984         break;
12985       case 6: // material range with given imbalance
12986         for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
12987         // fall through to range comparison
12988       case 5: // material range
12989         for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
12990     }
12991     return TRUE;
12992 }
12993
12994 int
12995 QuickScan (Board board, Move *move)
12996 {   // reconstruct game,and compare all positions in it
12997     int cnt=0, stretch=0, found = -1, total = MakePieceList(board, counts);
12998     do {
12999         int piece = move->piece;
13000         int to = move->to, from = pieceList[piece];
13001         if(found < 0) { // if already found just scan to game end for final piece count
13002           if(QuickCompare(soughtBoard, minSought, maxSought) ||
13003            appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
13004            flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
13005                                 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
13006             ) {
13007             static int lastCounts[EmptySquare+1];
13008             int i;
13009             if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
13010             if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
13011           } else stretch = 0;
13012           if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) found = cnt + 1 - stretch;
13013           if(found >= 0 && !appData.minPieces) return found;
13014         }
13015         if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
13016           if(!piece) return (appData.minPieces && (total < appData.minPieces || total > appData.maxPieces) ? -1 : found);
13017           if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
13018             piece = (++move)->piece;
13019             from = pieceList[piece];
13020             counts[pieceType[piece]]--;
13021             pieceType[piece] = (ChessSquare) move->to;
13022             counts[move->to]++;
13023           } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
13024             counts[pieceType[quickBoard[to]]]--;
13025             quickBoard[to] = 0; total--;
13026             move++;
13027             continue;
13028           } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
13029             piece = pieceList[piece]; // first two elements of pieceList contain King numbers
13030             from  = pieceList[piece]; // so this must be King
13031             quickBoard[from] = 0;
13032             pieceList[piece] = to;
13033             from = pieceList[(++move)->piece]; // for FRC this has to be done here
13034             quickBoard[from] = 0; // rook
13035             quickBoard[to] = piece;
13036             to = move->to; piece = move->piece;
13037             goto aftercastle;
13038           }
13039         }
13040         if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
13041         if((total -= (quickBoard[to] != 0)) < soughtTotal && found < 0) return -1; // piece count dropped below what we search for
13042         quickBoard[from] = 0;
13043       aftercastle:
13044         quickBoard[to] = piece;
13045         pieceList[piece] = to;
13046         cnt++; turn ^= 3;
13047         move++;
13048     } while(1);
13049 }
13050
13051 void
13052 InitSearch ()
13053 {
13054     int r, f;
13055     flipSearch = FALSE;
13056     CopyBoard(soughtBoard, boards[currentMove]);
13057     soughtTotal = MakePieceList(soughtBoard, maxSought);
13058     soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
13059     if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
13060     CopyBoard(reverseBoard, boards[currentMove]);
13061     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
13062         int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
13063         if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
13064         reverseBoard[r][f] = piece;
13065     }
13066     reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
13067     for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
13068     if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
13069                  || (boards[currentMove][CASTLING][2] == NoRights ||
13070                      boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
13071                  && (boards[currentMove][CASTLING][5] == NoRights ||
13072                      boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
13073       ) {
13074         flipSearch = TRUE;
13075         CopyBoard(flipBoard, soughtBoard);
13076         CopyBoard(rotateBoard, reverseBoard);
13077         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
13078             flipBoard[r][f]    = soughtBoard[r][BOARD_WIDTH-1-f];
13079             rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
13080         }
13081     }
13082     for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
13083     if(appData.searchMode >= 5) {
13084         for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
13085         MakePieceList(soughtBoard, minSought);
13086         for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
13087     }
13088     if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
13089         soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
13090 }
13091
13092 GameInfo dummyInfo;
13093 static int creatingBook;
13094
13095 int
13096 GameContainsPosition (FILE *f, ListGame *lg)
13097 {
13098     int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
13099     int fromX, fromY, toX, toY;
13100     char promoChar;
13101     static int initDone=FALSE;
13102
13103     // weed out games based on numerical tag comparison
13104     if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
13105     if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
13106     if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
13107     if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
13108     if(!initDone) {
13109         for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
13110         initDone = TRUE;
13111     }
13112     if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen, FALSE);
13113     else CopyBoard(boards[scratch], initialPosition); // default start position
13114     if(lg->moves) {
13115         turn = btm + 1;
13116         if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
13117         if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
13118     }
13119     if(btm) plyNr++;
13120     if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
13121     fseek(f, lg->offset, 0);
13122     yynewfile(f);
13123     while(1) {
13124         yyboardindex = scratch;
13125         quickFlag = plyNr+1;
13126         next = Myylex();
13127         quickFlag = 0;
13128         switch(next) {
13129             case PGNTag:
13130                 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
13131             default:
13132                 continue;
13133
13134             case XBoardGame:
13135             case GNUChessGame:
13136                 if(plyNr) return -1; // after we have seen moves, this is for new game
13137               continue;
13138
13139             case AmbiguousMove: // we cannot reconstruct the game beyond these two
13140             case ImpossibleMove:
13141             case WhiteWins: // game ends here with these four
13142             case BlackWins:
13143             case GameIsDrawn:
13144             case GameUnfinished:
13145                 return -1;
13146
13147             case IllegalMove:
13148                 if(appData.testLegality) return -1;
13149             case WhiteCapturesEnPassant:
13150             case BlackCapturesEnPassant:
13151             case WhitePromotion:
13152             case BlackPromotion:
13153             case WhiteNonPromotion:
13154             case BlackNonPromotion:
13155             case NormalMove:
13156             case FirstLeg:
13157             case WhiteKingSideCastle:
13158             case WhiteQueenSideCastle:
13159             case BlackKingSideCastle:
13160             case BlackQueenSideCastle:
13161             case WhiteKingSideCastleWild:
13162             case WhiteQueenSideCastleWild:
13163             case BlackKingSideCastleWild:
13164             case BlackQueenSideCastleWild:
13165             case WhiteHSideCastleFR:
13166             case WhiteASideCastleFR:
13167             case BlackHSideCastleFR:
13168             case BlackASideCastleFR:
13169                 fromX = currentMoveString[0] - AAA;
13170                 fromY = currentMoveString[1] - ONE;
13171                 toX = currentMoveString[2] - AAA;
13172                 toY = currentMoveString[3] - ONE;
13173                 promoChar = currentMoveString[4];
13174                 break;
13175             case WhiteDrop:
13176             case BlackDrop:
13177                 fromX = next == WhiteDrop ?
13178                   (int) CharToPiece(ToUpper(currentMoveString[0])) :
13179                   (int) CharToPiece(ToLower(currentMoveString[0]));
13180                 fromY = DROP_RANK;
13181                 toX = currentMoveString[2] - AAA;
13182                 toY = currentMoveString[3] - ONE;
13183                 promoChar = 0;
13184                 break;
13185         }
13186         // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
13187         plyNr++;
13188         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
13189         if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
13190         if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
13191         if(appData.findMirror) {
13192             if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
13193             if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
13194         }
13195     }
13196 }
13197
13198 /* Load the nth game from open file f */
13199 int
13200 LoadGame (FILE *f, int gameNumber, char *title, int useList)
13201 {
13202     ChessMove cm;
13203     char buf[MSG_SIZ];
13204     int gn = gameNumber;
13205     ListGame *lg = NULL;
13206     int numPGNTags = 0, i;
13207     int err, pos = -1;
13208     GameMode oldGameMode;
13209     VariantClass v, oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
13210     char oldName[MSG_SIZ];
13211
13212     safeStrCpy(oldName, engineVariant, MSG_SIZ); v = oldVariant;
13213
13214     if (appData.debugMode)
13215         fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
13216
13217     if (gameMode == Training )
13218         SetTrainingModeOff();
13219
13220     oldGameMode = gameMode;
13221     if (gameMode != BeginningOfGame) {
13222       Reset(FALSE, TRUE);
13223     }
13224     killX = killY = kill2X = kill2Y = -1; // [HGM] lion: in case we did not Reset
13225
13226     gameFileFP = f;
13227     if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
13228         fclose(lastLoadGameFP);
13229     }
13230
13231     if (useList) {
13232         lg = (ListGame *) ListElem(&gameList, gameNumber-1);
13233
13234         if (lg) {
13235             fseek(f, lg->offset, 0);
13236             GameListHighlight(gameNumber);
13237             pos = lg->position;
13238             gn = 1;
13239         }
13240         else {
13241             if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
13242               appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
13243             else
13244             DisplayError(_("Game number out of range"), 0);
13245             return FALSE;
13246         }
13247     } else {
13248         GameListDestroy();
13249         if (fseek(f, 0, 0) == -1) {
13250             if (f == lastLoadGameFP ?
13251                 gameNumber == lastLoadGameNumber + 1 :
13252                 gameNumber == 1) {
13253                 gn = 1;
13254             } else {
13255                 DisplayError(_("Can't seek on game file"), 0);
13256                 return FALSE;
13257             }
13258         }
13259     }
13260     lastLoadGameFP = f;
13261     lastLoadGameNumber = gameNumber;
13262     safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
13263     lastLoadGameUseList = useList;
13264
13265     yynewfile(f);
13266
13267     if (lg && lg->gameInfo.white && lg->gameInfo.black) {
13268       snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
13269                 lg->gameInfo.black);
13270             DisplayTitle(buf);
13271     } else if (*title != NULLCHAR) {
13272         if (gameNumber > 1) {
13273           snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
13274             DisplayTitle(buf);
13275         } else {
13276             DisplayTitle(title);
13277         }
13278     }
13279
13280     if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
13281         gameMode = PlayFromGameFile;
13282         ModeHighlight();
13283     }
13284
13285     currentMove = forwardMostMove = backwardMostMove = 0;
13286     CopyBoard(boards[0], initialPosition);
13287     StopClocks();
13288
13289     /*
13290      * Skip the first gn-1 games in the file.
13291      * Also skip over anything that precedes an identifiable
13292      * start of game marker, to avoid being confused by
13293      * garbage at the start of the file.  Currently
13294      * recognized start of game markers are the move number "1",
13295      * the pattern "gnuchess .* game", the pattern
13296      * "^[#;%] [^ ]* game file", and a PGN tag block.
13297      * A game that starts with one of the latter two patterns
13298      * will also have a move number 1, possibly
13299      * following a position diagram.
13300      * 5-4-02: Let's try being more lenient and allowing a game to
13301      * start with an unnumbered move.  Does that break anything?
13302      */
13303     cm = lastLoadGameStart = EndOfFile;
13304     while (gn > 0) {
13305         yyboardindex = forwardMostMove;
13306         cm = (ChessMove) Myylex();
13307         switch (cm) {
13308           case EndOfFile:
13309             if (cmailMsgLoaded) {
13310                 nCmailGames = CMAIL_MAX_GAMES - gn;
13311             } else {
13312                 Reset(TRUE, TRUE);
13313                 DisplayError(_("Game not found in file"), 0);
13314             }
13315             return FALSE;
13316
13317           case GNUChessGame:
13318           case XBoardGame:
13319             gn--;
13320             lastLoadGameStart = cm;
13321             break;
13322
13323           case MoveNumberOne:
13324             switch (lastLoadGameStart) {
13325               case GNUChessGame:
13326               case XBoardGame:
13327               case PGNTag:
13328                 break;
13329               case MoveNumberOne:
13330               case EndOfFile:
13331                 gn--;           /* count this game */
13332                 lastLoadGameStart = cm;
13333                 break;
13334               default:
13335                 /* impossible */
13336                 break;
13337             }
13338             break;
13339
13340           case PGNTag:
13341             switch (lastLoadGameStart) {
13342               case GNUChessGame:
13343               case PGNTag:
13344               case MoveNumberOne:
13345               case EndOfFile:
13346                 gn--;           /* count this game */
13347                 lastLoadGameStart = cm;
13348                 break;
13349               case XBoardGame:
13350                 lastLoadGameStart = cm; /* game counted already */
13351                 break;
13352               default:
13353                 /* impossible */
13354                 break;
13355             }
13356             if (gn > 0) {
13357                 do {
13358                     yyboardindex = forwardMostMove;
13359                     cm = (ChessMove) Myylex();
13360                 } while (cm == PGNTag || cm == Comment);
13361             }
13362             break;
13363
13364           case WhiteWins:
13365           case BlackWins:
13366           case GameIsDrawn:
13367             if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
13368                 if (   cmailResult[CMAIL_MAX_GAMES - gn - 1]
13369                     != CMAIL_OLD_RESULT) {
13370                     nCmailResults ++ ;
13371                     cmailResult[  CMAIL_MAX_GAMES
13372                                 - gn - 1] = CMAIL_OLD_RESULT;
13373                 }
13374             }
13375             break;
13376
13377           case NormalMove:
13378           case FirstLeg:
13379             /* Only a NormalMove can be at the start of a game
13380              * without a position diagram. */
13381             if (lastLoadGameStart == EndOfFile ) {
13382               gn--;
13383               lastLoadGameStart = MoveNumberOne;
13384             }
13385             break;
13386
13387           default:
13388             break;
13389         }
13390     }
13391
13392     if (appData.debugMode)
13393       fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
13394
13395     for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; } // reset VariantMen
13396
13397     if (cm == XBoardGame) {
13398         /* Skip any header junk before position diagram and/or move 1 */
13399         for (;;) {
13400             yyboardindex = forwardMostMove;
13401             cm = (ChessMove) Myylex();
13402
13403             if (cm == EndOfFile ||
13404                 cm == GNUChessGame || cm == XBoardGame) {
13405                 /* Empty game; pretend end-of-file and handle later */
13406                 cm = EndOfFile;
13407                 break;
13408             }
13409
13410             if (cm == MoveNumberOne || cm == PositionDiagram ||
13411                 cm == PGNTag || cm == Comment)
13412               break;
13413         }
13414     } else if (cm == GNUChessGame) {
13415         if (gameInfo.event != NULL) {
13416             free(gameInfo.event);
13417         }
13418         gameInfo.event = StrSave(yy_text);
13419     }
13420
13421     startedFromSetupPosition = startedFromPositionFile; // [HGM]
13422     while (cm == PGNTag) {
13423         if (appData.debugMode)
13424           fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
13425         err = ParsePGNTag(yy_text, &gameInfo);
13426         if (!err) numPGNTags++;
13427
13428         /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
13429         if(gameInfo.variant != oldVariant && (gameInfo.variant != VariantNormal || gameInfo.variantName == NULL || *gameInfo.variantName == NULLCHAR)) {
13430             startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
13431             ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
13432             InitPosition(TRUE);
13433             oldVariant = gameInfo.variant;
13434             if (appData.debugMode)
13435               fprintf(debugFP, "New variant %d\n", (int) oldVariant);
13436         }
13437
13438
13439         if (gameInfo.fen != NULL) {
13440           Board initial_position;
13441           startedFromSetupPosition = TRUE;
13442           if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen, TRUE)) {
13443             Reset(TRUE, TRUE);
13444             DisplayError(_("Bad FEN position in file"), 0);
13445             return FALSE;
13446           }
13447           CopyBoard(boards[0], initial_position);
13448           if(*engineVariant || gameInfo.variant == VariantFairy) // [HGM] for now, assume FEN in engine-defined variant game is default initial position
13449             CopyBoard(initialPosition, initial_position);
13450           if (blackPlaysFirst) {
13451             currentMove = forwardMostMove = backwardMostMove = 1;
13452             CopyBoard(boards[1], initial_position);
13453             safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13454             safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13455             timeRemaining[0][1] = whiteTimeRemaining;
13456             timeRemaining[1][1] = blackTimeRemaining;
13457             if (commentList[0] != NULL) {
13458               commentList[1] = commentList[0];
13459               commentList[0] = NULL;
13460             }
13461           } else {
13462             currentMove = forwardMostMove = backwardMostMove = 0;
13463           }
13464           /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
13465           {   int i;
13466               initialRulePlies = FENrulePlies;
13467               for( i=0; i< nrCastlingRights; i++ )
13468                   initialRights[i] = initial_position[CASTLING][i];
13469           }
13470           yyboardindex = forwardMostMove;
13471           free(gameInfo.fen);
13472           gameInfo.fen = NULL;
13473         }
13474
13475         yyboardindex = forwardMostMove;
13476         cm = (ChessMove) Myylex();
13477
13478         /* Handle comments interspersed among the tags */
13479         while (cm == Comment) {
13480             char *p;
13481             if (appData.debugMode)
13482               fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13483             p = yy_text;
13484             AppendComment(currentMove, p, FALSE);
13485             yyboardindex = forwardMostMove;
13486             cm = (ChessMove) Myylex();
13487         }
13488     }
13489
13490     /* don't rely on existence of Event tag since if game was
13491      * pasted from clipboard the Event tag may not exist
13492      */
13493     if (numPGNTags > 0){
13494         char *tags;
13495         if (gameInfo.variant == VariantNormal) {
13496           VariantClass v = StringToVariant(gameInfo.event);
13497           // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
13498           if(v < VariantShogi) gameInfo.variant = v;
13499         }
13500         if (!matchMode) {
13501           if( appData.autoDisplayTags ) {
13502             tags = PGNTags(&gameInfo);
13503             TagsPopUp(tags, CmailMsg());
13504             free(tags);
13505           }
13506         }
13507     } else {
13508         /* Make something up, but don't display it now */
13509         SetGameInfo();
13510         TagsPopDown();
13511     }
13512
13513     if (cm == PositionDiagram) {
13514         int i, j;
13515         char *p;
13516         Board initial_position;
13517
13518         if (appData.debugMode)
13519           fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
13520
13521         if (!startedFromSetupPosition) {
13522             p = yy_text;
13523             for (i = BOARD_HEIGHT - 1; i >= 0; i--)
13524               for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
13525                 switch (*p) {
13526                   case '{':
13527                   case '[':
13528                   case '-':
13529                   case ' ':
13530                   case '\t':
13531                   case '\n':
13532                   case '\r':
13533                     break;
13534                   default:
13535                     initial_position[i][j++] = CharToPiece(*p);
13536                     break;
13537                 }
13538             while (*p == ' ' || *p == '\t' ||
13539                    *p == '\n' || *p == '\r') p++;
13540
13541             if (strncmp(p, "black", strlen("black"))==0)
13542               blackPlaysFirst = TRUE;
13543             else
13544               blackPlaysFirst = FALSE;
13545             startedFromSetupPosition = TRUE;
13546
13547             CopyBoard(boards[0], initial_position);
13548             if (blackPlaysFirst) {
13549                 currentMove = forwardMostMove = backwardMostMove = 1;
13550                 CopyBoard(boards[1], initial_position);
13551                 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13552                 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13553                 timeRemaining[0][1] = whiteTimeRemaining;
13554                 timeRemaining[1][1] = blackTimeRemaining;
13555                 if (commentList[0] != NULL) {
13556                     commentList[1] = commentList[0];
13557                     commentList[0] = NULL;
13558                 }
13559             } else {
13560                 currentMove = forwardMostMove = backwardMostMove = 0;
13561             }
13562         }
13563         yyboardindex = forwardMostMove;
13564         cm = (ChessMove) Myylex();
13565     }
13566
13567   if(!creatingBook) {
13568     if (first.pr == NoProc) {
13569         StartChessProgram(&first);
13570     }
13571     InitChessProgram(&first, FALSE);
13572     if(gameInfo.variant == VariantUnknown && *oldName) {
13573         safeStrCpy(engineVariant, oldName, MSG_SIZ);
13574         gameInfo.variant = v;
13575     }
13576     SendToProgram("force\n", &first);
13577     if (startedFromSetupPosition) {
13578         SendBoard(&first, forwardMostMove);
13579     if (appData.debugMode) {
13580         fprintf(debugFP, "Load Game\n");
13581     }
13582         DisplayBothClocks();
13583     }
13584   }
13585
13586     /* [HGM] server: flag to write setup moves in broadcast file as one */
13587     loadFlag = appData.suppressLoadMoves;
13588
13589     while (cm == Comment) {
13590         char *p;
13591         if (appData.debugMode)
13592           fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13593         p = yy_text;
13594         AppendComment(currentMove, p, FALSE);
13595         yyboardindex = forwardMostMove;
13596         cm = (ChessMove) Myylex();
13597     }
13598
13599     if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
13600         cm == WhiteWins || cm == BlackWins ||
13601         cm == GameIsDrawn || cm == GameUnfinished) {
13602         DisplayMessage("", _("No moves in game"));
13603         if (cmailMsgLoaded) {
13604             if (appData.debugMode)
13605               fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
13606             ClearHighlights();
13607             flipView = FALSE;
13608         }
13609         DrawPosition(FALSE, boards[currentMove]);
13610         DisplayBothClocks();
13611         gameMode = EditGame;
13612         ModeHighlight();
13613         gameFileFP = NULL;
13614         cmailOldMove = 0;
13615         return TRUE;
13616     }
13617
13618     // [HGM] PV info: routine tests if comment empty
13619     if (!matchMode && (pausing || appData.timeDelay != 0)) {
13620         DisplayComment(currentMove - 1, commentList[currentMove]);
13621     }
13622     if (!matchMode && appData.timeDelay != 0)
13623       DrawPosition(FALSE, boards[currentMove]);
13624
13625     if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
13626       programStats.ok_to_send = 1;
13627     }
13628
13629     /* if the first token after the PGN tags is a move
13630      * and not move number 1, retrieve it from the parser
13631      */
13632     if (cm != MoveNumberOne)
13633         LoadGameOneMove(cm);
13634
13635     /* load the remaining moves from the file */
13636     while (LoadGameOneMove(EndOfFile)) {
13637       timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13638       timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13639     }
13640
13641     /* rewind to the start of the game */
13642     currentMove = backwardMostMove;
13643
13644     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13645
13646     if (oldGameMode == AnalyzeFile) {
13647       appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
13648       AnalyzeFileEvent();
13649     } else
13650     if (oldGameMode == AnalyzeMode) {
13651       AnalyzeFileEvent();
13652     }
13653
13654     if(gameInfo.result == GameUnfinished && gameInfo.resultDetails && appData.clockMode) {
13655         long int w, b; // [HGM] adjourn: restore saved clock times
13656         char *p = strstr(gameInfo.resultDetails, "(Clocks:");
13657         if(p && sscanf(p+8, "%ld,%ld", &w, &b) == 2) {
13658             timeRemaining[0][forwardMostMove] = whiteTimeRemaining = 1000*w + 500;
13659             timeRemaining[1][forwardMostMove] = blackTimeRemaining = 1000*b + 500;
13660         }
13661     }
13662
13663     if(creatingBook) return TRUE;
13664     if (!matchMode && pos > 0) {
13665         ToNrEvent(pos); // [HGM] no autoplay if selected on position
13666     } else
13667     if (matchMode || appData.timeDelay == 0) {
13668       ToEndEvent();
13669     } else if (appData.timeDelay > 0) {
13670       AutoPlayGameLoop();
13671     }
13672
13673     if (appData.debugMode)
13674         fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
13675
13676     loadFlag = 0; /* [HGM] true game starts */
13677     return TRUE;
13678 }
13679
13680 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
13681 int
13682 ReloadPosition (int offset)
13683 {
13684     int positionNumber = lastLoadPositionNumber + offset;
13685     if (lastLoadPositionFP == NULL) {
13686         DisplayError(_("No position has been loaded yet"), 0);
13687         return FALSE;
13688     }
13689     if (positionNumber <= 0) {
13690         DisplayError(_("Can't back up any further"), 0);
13691         return FALSE;
13692     }
13693     return LoadPosition(lastLoadPositionFP, positionNumber,
13694                         lastLoadPositionTitle);
13695 }
13696
13697 /* Load the nth position from the given file */
13698 int
13699 LoadPositionFromFile (char *filename, int n, char *title)
13700 {
13701     FILE *f;
13702     char buf[MSG_SIZ];
13703
13704     if (strcmp(filename, "-") == 0) {
13705         return LoadPosition(stdin, n, "stdin");
13706     } else {
13707         f = fopen(filename, "rb");
13708         if (f == NULL) {
13709             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13710             DisplayError(buf, errno);
13711             return FALSE;
13712         } else {
13713             return LoadPosition(f, n, title);
13714         }
13715     }
13716 }
13717
13718 /* Load the nth position from the given open file, and close it */
13719 int
13720 LoadPosition (FILE *f, int positionNumber, char *title)
13721 {
13722     char *p, line[MSG_SIZ];
13723     Board initial_position;
13724     int i, j, fenMode, pn;
13725
13726     if (gameMode == Training )
13727         SetTrainingModeOff();
13728
13729     if (gameMode != BeginningOfGame) {
13730         Reset(FALSE, TRUE);
13731     }
13732     if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
13733         fclose(lastLoadPositionFP);
13734     }
13735     if (positionNumber == 0) positionNumber = 1;
13736     lastLoadPositionFP = f;
13737     lastLoadPositionNumber = positionNumber;
13738     safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
13739     if (first.pr == NoProc && !appData.noChessProgram) {
13740       StartChessProgram(&first);
13741       InitChessProgram(&first, FALSE);
13742     }
13743     pn = positionNumber;
13744     if (positionNumber < 0) {
13745         /* Negative position number means to seek to that byte offset */
13746         if (fseek(f, -positionNumber, 0) == -1) {
13747             DisplayError(_("Can't seek on position file"), 0);
13748             return FALSE;
13749         };
13750         pn = 1;
13751     } else {
13752         if (fseek(f, 0, 0) == -1) {
13753             if (f == lastLoadPositionFP ?
13754                 positionNumber == lastLoadPositionNumber + 1 :
13755                 positionNumber == 1) {
13756                 pn = 1;
13757             } else {
13758                 DisplayError(_("Can't seek on position file"), 0);
13759                 return FALSE;
13760             }
13761         }
13762     }
13763     /* See if this file is FEN or old-style xboard */
13764     if (fgets(line, MSG_SIZ, f) == NULL) {
13765         DisplayError(_("Position not found in file"), 0);
13766         return FALSE;
13767     }
13768     // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces (or * for blackout)
13769     fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || line[0] == '*' || CharToPiece(line[0]) != EmptySquare;
13770
13771     if (pn >= 2) {
13772         if (fenMode || line[0] == '#') pn--;
13773         while (pn > 0) {
13774             /* skip positions before number pn */
13775             if (fgets(line, MSG_SIZ, f) == NULL) {
13776                 Reset(TRUE, TRUE);
13777                 DisplayError(_("Position not found in file"), 0);
13778                 return FALSE;
13779             }
13780             if (fenMode || line[0] == '#') pn--;
13781         }
13782     }
13783
13784     if (fenMode) {
13785         char *p;
13786         if (!ParseFEN(initial_position, &blackPlaysFirst, line, TRUE)) {
13787             DisplayError(_("Bad FEN position in file"), 0);
13788             return FALSE;
13789         }
13790         if((strchr(line, ';')) && (p = strstr(line, " bm "))) { // EPD with best move
13791             sscanf(p+4, "%[^;]", bestMove);
13792         } else *bestMove = NULLCHAR;
13793         if((strchr(line, ';')) && (p = strstr(line, " am "))) { // EPD with avoid move
13794             sscanf(p+4, "%[^;]", avoidMove);
13795         } else *avoidMove = NULLCHAR;
13796     } else {
13797         (void) fgets(line, MSG_SIZ, f);
13798         (void) fgets(line, MSG_SIZ, f);
13799
13800         for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13801             (void) fgets(line, MSG_SIZ, f);
13802             for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
13803                 if (*p == ' ')
13804                   continue;
13805                 initial_position[i][j++] = CharToPiece(*p);
13806             }
13807         }
13808
13809         blackPlaysFirst = FALSE;
13810         if (!feof(f)) {
13811             (void) fgets(line, MSG_SIZ, f);
13812             if (strncmp(line, "black", strlen("black"))==0)
13813               blackPlaysFirst = TRUE;
13814         }
13815     }
13816     startedFromSetupPosition = TRUE;
13817
13818     CopyBoard(boards[0], initial_position);
13819     if (blackPlaysFirst) {
13820         currentMove = forwardMostMove = backwardMostMove = 1;
13821         safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13822         safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13823         CopyBoard(boards[1], initial_position);
13824         DisplayMessage("", _("Black to play"));
13825     } else {
13826         currentMove = forwardMostMove = backwardMostMove = 0;
13827         DisplayMessage("", _("White to play"));
13828     }
13829     initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
13830     if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
13831         SendToProgram("force\n", &first);
13832         SendBoard(&first, forwardMostMove);
13833     }
13834     if (appData.debugMode) {
13835 int i, j;
13836   for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
13837   for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
13838         fprintf(debugFP, "Load Position\n");
13839     }
13840
13841     if (positionNumber > 1) {
13842       snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
13843         DisplayTitle(line);
13844     } else {
13845         DisplayTitle(title);
13846     }
13847     gameMode = EditGame;
13848     ModeHighlight();
13849     ResetClocks();
13850     timeRemaining[0][1] = whiteTimeRemaining;
13851     timeRemaining[1][1] = blackTimeRemaining;
13852     DrawPosition(FALSE, boards[currentMove]);
13853
13854     return TRUE;
13855 }
13856
13857
13858 void
13859 CopyPlayerNameIntoFileName (char **dest, char *src)
13860 {
13861     while (*src != NULLCHAR && *src != ',') {
13862         if (*src == ' ') {
13863             *(*dest)++ = '_';
13864             src++;
13865         } else {
13866             *(*dest)++ = *src++;
13867         }
13868     }
13869 }
13870
13871 char *
13872 DefaultFileName (char *ext)
13873 {
13874     static char def[MSG_SIZ];
13875     char *p;
13876
13877     if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
13878         p = def;
13879         CopyPlayerNameIntoFileName(&p, gameInfo.white);
13880         *p++ = '-';
13881         CopyPlayerNameIntoFileName(&p, gameInfo.black);
13882         *p++ = '.';
13883         safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
13884     } else {
13885         def[0] = NULLCHAR;
13886     }
13887     return def;
13888 }
13889
13890 /* Save the current game to the given file */
13891 int
13892 SaveGameToFile (char *filename, int append)
13893 {
13894     FILE *f;
13895     char buf[MSG_SIZ];
13896     int result, i, t,tot=0;
13897
13898     if (strcmp(filename, "-") == 0) {
13899         return SaveGame(stdout, 0, NULL);
13900     } else {
13901         for(i=0; i<10; i++) { // upto 10 tries
13902              f = fopen(filename, append ? "a" : "w");
13903              if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
13904              if(f || errno != 13) break;
13905              DoSleep(t = 5 + random()%11); // wait 5-15 msec
13906              tot += t;
13907         }
13908         if (f == NULL) {
13909             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13910             DisplayError(buf, errno);
13911             return FALSE;
13912         } else {
13913             safeStrCpy(buf, lastMsg, MSG_SIZ);
13914             DisplayMessage(_("Waiting for access to save file"), "");
13915             flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
13916             DisplayMessage(_("Saving game"), "");
13917             if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno);     // better safe than sorry...
13918             result = SaveGame(f, 0, NULL);
13919             DisplayMessage(buf, "");
13920             return result;
13921         }
13922     }
13923 }
13924
13925 char *
13926 SavePart (char *str)
13927 {
13928     static char buf[MSG_SIZ];
13929     char *p;
13930
13931     p = strchr(str, ' ');
13932     if (p == NULL) return str;
13933     strncpy(buf, str, p - str);
13934     buf[p - str] = NULLCHAR;
13935     return buf;
13936 }
13937
13938 #define PGN_MAX_LINE 75
13939
13940 #define PGN_SIDE_WHITE  0
13941 #define PGN_SIDE_BLACK  1
13942
13943 static int
13944 FindFirstMoveOutOfBook (int side)
13945 {
13946     int result = -1;
13947
13948     if( backwardMostMove == 0 && ! startedFromSetupPosition) {
13949         int index = backwardMostMove;
13950         int has_book_hit = 0;
13951
13952         if( (index % 2) != side ) {
13953             index++;
13954         }
13955
13956         while( index < forwardMostMove ) {
13957             /* Check to see if engine is in book */
13958             int depth = pvInfoList[index].depth;
13959             int score = pvInfoList[index].score;
13960             int in_book = 0;
13961
13962             if( depth <= 2 ) {
13963                 in_book = 1;
13964             }
13965             else if( score == 0 && depth == 63 ) {
13966                 in_book = 1; /* Zappa */
13967             }
13968             else if( score == 2 && depth == 99 ) {
13969                 in_book = 1; /* Abrok */
13970             }
13971
13972             has_book_hit += in_book;
13973
13974             if( ! in_book ) {
13975                 result = index;
13976
13977                 break;
13978             }
13979
13980             index += 2;
13981         }
13982     }
13983
13984     return result;
13985 }
13986
13987 void
13988 GetOutOfBookInfo (char * buf)
13989 {
13990     int oob[2];
13991     int i;
13992     int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13993
13994     oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
13995     oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
13996
13997     *buf = '\0';
13998
13999     if( oob[0] >= 0 || oob[1] >= 0 ) {
14000         for( i=0; i<2; i++ ) {
14001             int idx = oob[i];
14002
14003             if( idx >= 0 ) {
14004                 if( i > 0 && oob[0] >= 0 ) {
14005                     strcat( buf, "   " );
14006                 }
14007
14008                 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
14009                 sprintf( buf+strlen(buf), "%s%.2f",
14010                     pvInfoList[idx].score >= 0 ? "+" : "",
14011                     pvInfoList[idx].score / 100.0 );
14012             }
14013         }
14014     }
14015 }
14016
14017 /* Save game in PGN style */
14018 static void
14019 SaveGamePGN2 (FILE *f)
14020 {
14021     int i, offset, linelen, newblock;
14022 //    char *movetext;
14023     char numtext[32];
14024     int movelen, numlen, blank;
14025     char move_buffer[100]; /* [AS] Buffer for move+PV info */
14026
14027     offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
14028
14029     PrintPGNTags(f, &gameInfo);
14030
14031     if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
14032
14033     if (backwardMostMove > 0 || startedFromSetupPosition) {
14034         char *fen = PositionToFEN(backwardMostMove, NULL, 1);
14035         fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
14036         fprintf(f, "\n{--------------\n");
14037         PrintPosition(f, backwardMostMove);
14038         fprintf(f, "--------------}\n");
14039         free(fen);
14040     }
14041     else {
14042         /* [AS] Out of book annotation */
14043         if( appData.saveOutOfBookInfo ) {
14044             char buf[64];
14045
14046             GetOutOfBookInfo( buf );
14047
14048             if( buf[0] != '\0' ) {
14049                 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
14050             }
14051         }
14052
14053         fprintf(f, "\n");
14054     }
14055
14056     i = backwardMostMove;
14057     linelen = 0;
14058     newblock = TRUE;
14059
14060     while (i < forwardMostMove) {
14061         /* Print comments preceding this move */
14062         if (commentList[i] != NULL) {
14063             if (linelen > 0) fprintf(f, "\n");
14064             fprintf(f, "%s", commentList[i]);
14065             linelen = 0;
14066             newblock = TRUE;
14067         }
14068
14069         /* Format move number */
14070         if ((i % 2) == 0)
14071           snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
14072         else
14073           if (newblock)
14074             snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
14075           else
14076             numtext[0] = NULLCHAR;
14077
14078         numlen = strlen(numtext);
14079         newblock = FALSE;
14080
14081         /* Print move number */
14082         blank = linelen > 0 && numlen > 0;
14083         if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
14084             fprintf(f, "\n");
14085             linelen = 0;
14086             blank = 0;
14087         }
14088         if (blank) {
14089             fprintf(f, " ");
14090             linelen++;
14091         }
14092         fprintf(f, "%s", numtext);
14093         linelen += numlen;
14094
14095         /* Get move */
14096         safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
14097         movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
14098
14099         /* Print move */
14100         blank = linelen > 0 && movelen > 0;
14101         if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
14102             fprintf(f, "\n");
14103             linelen = 0;
14104             blank = 0;
14105         }
14106         if (blank) {
14107             fprintf(f, " ");
14108             linelen++;
14109         }
14110         fprintf(f, "%s", move_buffer);
14111         linelen += movelen;
14112
14113         /* [AS] Add PV info if present */
14114         if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
14115             /* [HGM] add time */
14116             char buf[MSG_SIZ]; int seconds;
14117
14118             seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
14119
14120             if( seconds <= 0)
14121               buf[0] = 0;
14122             else
14123               if( seconds < 30 )
14124                 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
14125               else
14126                 {
14127                   seconds = (seconds + 4)/10; // round to full seconds
14128                   if( seconds < 60 )
14129                     snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
14130                   else
14131                     snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
14132                 }
14133
14134             if(appData.cumulativeTimePGN) {
14135                 snprintf(buf, MSG_SIZ, " %+ld", timeRemaining[i & 1][i+1]/1000);
14136             }
14137
14138             snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
14139                       pvInfoList[i].score >= 0 ? "+" : "",
14140                       pvInfoList[i].score / 100.0,
14141                       pvInfoList[i].depth,
14142                       buf );
14143
14144             movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
14145
14146             /* Print score/depth */
14147             blank = linelen > 0 && movelen > 0;
14148             if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
14149                 fprintf(f, "\n");
14150                 linelen = 0;
14151                 blank = 0;
14152             }
14153             if (blank) {
14154                 fprintf(f, " ");
14155                 linelen++;
14156             }
14157             fprintf(f, "%s", move_buffer);
14158             linelen += movelen;
14159         }
14160
14161         i++;
14162     }
14163
14164     /* Start a new line */
14165     if (linelen > 0) fprintf(f, "\n");
14166
14167     /* Print comments after last move */
14168     if (commentList[i] != NULL) {
14169         fprintf(f, "%s\n", commentList[i]);
14170     }
14171
14172     /* Print result */
14173     if (gameInfo.resultDetails != NULL &&
14174         gameInfo.resultDetails[0] != NULLCHAR) {
14175         char buf[MSG_SIZ], *p = gameInfo.resultDetails;
14176         if(gameInfo.result == GameUnfinished && appData.clockMode &&
14177            (gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay)) // [HGM] adjourn: save clock settings
14178             snprintf(buf, MSG_SIZ, "%s (Clocks: %ld, %ld)", p, whiteTimeRemaining/1000, blackTimeRemaining/1000), p = buf;
14179         fprintf(f, "{%s} %s\n\n", p, PGNResult(gameInfo.result));
14180     } else {
14181         fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
14182     }
14183 }
14184
14185 /* Save game in PGN style and close the file */
14186 int
14187 SaveGamePGN (FILE *f)
14188 {
14189     SaveGamePGN2(f);
14190     fclose(f);
14191     lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
14192     return TRUE;
14193 }
14194
14195 /* Save game in old style and close the file */
14196 int
14197 SaveGameOldStyle (FILE *f)
14198 {
14199     int i, offset;
14200     time_t tm;
14201
14202     tm = time((time_t *) NULL);
14203
14204     fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
14205     PrintOpponents(f);
14206
14207     if (backwardMostMove > 0 || startedFromSetupPosition) {
14208         fprintf(f, "\n[--------------\n");
14209         PrintPosition(f, backwardMostMove);
14210         fprintf(f, "--------------]\n");
14211     } else {
14212         fprintf(f, "\n");
14213     }
14214
14215     i = backwardMostMove;
14216     offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
14217
14218     while (i < forwardMostMove) {
14219         if (commentList[i] != NULL) {
14220             fprintf(f, "[%s]\n", commentList[i]);
14221         }
14222
14223         if ((i % 2) == 1) {
14224             fprintf(f, "%d. ...  %s\n", (i - offset)/2 + 1, parseList[i]);
14225             i++;
14226         } else {
14227             fprintf(f, "%d. %s  ", (i - offset)/2 + 1, parseList[i]);
14228             i++;
14229             if (commentList[i] != NULL) {
14230                 fprintf(f, "\n");
14231                 continue;
14232             }
14233             if (i >= forwardMostMove) {
14234                 fprintf(f, "\n");
14235                 break;
14236             }
14237             fprintf(f, "%s\n", parseList[i]);
14238             i++;
14239         }
14240     }
14241
14242     if (commentList[i] != NULL) {
14243         fprintf(f, "[%s]\n", commentList[i]);
14244     }
14245
14246     /* This isn't really the old style, but it's close enough */
14247     if (gameInfo.resultDetails != NULL &&
14248         gameInfo.resultDetails[0] != NULLCHAR) {
14249         fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
14250                 gameInfo.resultDetails);
14251     } else {
14252         fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
14253     }
14254
14255     fclose(f);
14256     return TRUE;
14257 }
14258
14259 /* Save the current game to open file f and close the file */
14260 int
14261 SaveGame (FILE *f, int dummy, char *dummy2)
14262 {
14263     if (gameMode == EditPosition) EditPositionDone(TRUE);
14264     lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
14265     if (appData.oldSaveStyle)
14266       return SaveGameOldStyle(f);
14267     else
14268       return SaveGamePGN(f);
14269 }
14270
14271 /* Save the current position to the given file */
14272 int
14273 SavePositionToFile (char *filename)
14274 {
14275     FILE *f;
14276     char buf[MSG_SIZ];
14277
14278     if (strcmp(filename, "-") == 0) {
14279         return SavePosition(stdout, 0, NULL);
14280     } else {
14281         f = fopen(filename, "a");
14282         if (f == NULL) {
14283             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
14284             DisplayError(buf, errno);
14285             return FALSE;
14286         } else {
14287             safeStrCpy(buf, lastMsg, MSG_SIZ);
14288             DisplayMessage(_("Waiting for access to save file"), "");
14289             flock(fileno(f), LOCK_EX); // [HGM] lock
14290             DisplayMessage(_("Saving position"), "");
14291             lseek(fileno(f), 0, SEEK_END);     // better safe than sorry...
14292             SavePosition(f, 0, NULL);
14293             DisplayMessage(buf, "");
14294             return TRUE;
14295         }
14296     }
14297 }
14298
14299 /* Save the current position to the given open file and close the file */
14300 int
14301 SavePosition (FILE *f, int dummy, char *dummy2)
14302 {
14303     time_t tm;
14304     char *fen;
14305
14306     if (gameMode == EditPosition) EditPositionDone(TRUE);
14307     if (appData.oldSaveStyle) {
14308         tm = time((time_t *) NULL);
14309
14310         fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
14311         PrintOpponents(f);
14312         fprintf(f, "[--------------\n");
14313         PrintPosition(f, currentMove);
14314         fprintf(f, "--------------]\n");
14315     } else {
14316         fen = PositionToFEN(currentMove, NULL, 1);
14317         fprintf(f, "%s\n", fen);
14318         free(fen);
14319     }
14320     fclose(f);
14321     return TRUE;
14322 }
14323
14324 void
14325 ReloadCmailMsgEvent (int unregister)
14326 {
14327 #if !WIN32
14328     static char *inFilename = NULL;
14329     static char *outFilename;
14330     int i;
14331     struct stat inbuf, outbuf;
14332     int status;
14333
14334     /* Any registered moves are unregistered if unregister is set, */
14335     /* i.e. invoked by the signal handler */
14336     if (unregister) {
14337         for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
14338             cmailMoveRegistered[i] = FALSE;
14339             if (cmailCommentList[i] != NULL) {
14340                 free(cmailCommentList[i]);
14341                 cmailCommentList[i] = NULL;
14342             }
14343         }
14344         nCmailMovesRegistered = 0;
14345     }
14346
14347     for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
14348         cmailResult[i] = CMAIL_NOT_RESULT;
14349     }
14350     nCmailResults = 0;
14351
14352     if (inFilename == NULL) {
14353         /* Because the filenames are static they only get malloced once  */
14354         /* and they never get freed                                      */
14355         inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
14356         sprintf(inFilename, "%s.game.in", appData.cmailGameName);
14357
14358         outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
14359         sprintf(outFilename, "%s.out", appData.cmailGameName);
14360     }
14361
14362     status = stat(outFilename, &outbuf);
14363     if (status < 0) {
14364         cmailMailedMove = FALSE;
14365     } else {
14366         status = stat(inFilename, &inbuf);
14367         cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
14368     }
14369
14370     /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
14371        counts the games, notes how each one terminated, etc.
14372
14373        It would be nice to remove this kludge and instead gather all
14374        the information while building the game list.  (And to keep it
14375        in the game list nodes instead of having a bunch of fixed-size
14376        parallel arrays.)  Note this will require getting each game's
14377        termination from the PGN tags, as the game list builder does
14378        not process the game moves.  --mann
14379        */
14380     cmailMsgLoaded = TRUE;
14381     LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
14382
14383     /* Load first game in the file or popup game menu */
14384     LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
14385
14386 #endif /* !WIN32 */
14387     return;
14388 }
14389
14390 int
14391 RegisterMove ()
14392 {
14393     FILE *f;
14394     char string[MSG_SIZ];
14395
14396     if (   cmailMailedMove
14397         || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
14398         return TRUE;            /* Allow free viewing  */
14399     }
14400
14401     /* Unregister move to ensure that we don't leave RegisterMove        */
14402     /* with the move registered when the conditions for registering no   */
14403     /* longer hold                                                       */
14404     if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
14405         cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
14406         nCmailMovesRegistered --;
14407
14408         if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
14409           {
14410               free(cmailCommentList[lastLoadGameNumber - 1]);
14411               cmailCommentList[lastLoadGameNumber - 1] = NULL;
14412           }
14413     }
14414
14415     if (cmailOldMove == -1) {
14416         DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
14417         return FALSE;
14418     }
14419
14420     if (currentMove > cmailOldMove + 1) {
14421         DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
14422         return FALSE;
14423     }
14424
14425     if (currentMove < cmailOldMove) {
14426         DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
14427         return FALSE;
14428     }
14429
14430     if (forwardMostMove > currentMove) {
14431         /* Silently truncate extra moves */
14432         TruncateGame();
14433     }
14434
14435     if (   (currentMove == cmailOldMove + 1)
14436         || (   (currentMove == cmailOldMove)
14437             && (   (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
14438                 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
14439         if (gameInfo.result != GameUnfinished) {
14440             cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
14441         }
14442
14443         if (commentList[currentMove] != NULL) {
14444             cmailCommentList[lastLoadGameNumber - 1]
14445               = StrSave(commentList[currentMove]);
14446         }
14447         safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
14448
14449         if (appData.debugMode)
14450           fprintf(debugFP, "Saving %s for game %d\n",
14451                   cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
14452
14453         snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
14454
14455         f = fopen(string, "w");
14456         if (appData.oldSaveStyle) {
14457             SaveGameOldStyle(f); /* also closes the file */
14458
14459             snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
14460             f = fopen(string, "w");
14461             SavePosition(f, 0, NULL); /* also closes the file */
14462         } else {
14463             fprintf(f, "{--------------\n");
14464             PrintPosition(f, currentMove);
14465             fprintf(f, "--------------}\n\n");
14466
14467             SaveGame(f, 0, NULL); /* also closes the file*/
14468         }
14469
14470         cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
14471         nCmailMovesRegistered ++;
14472     } else if (nCmailGames == 1) {
14473         DisplayError(_("You have not made a move yet"), 0);
14474         return FALSE;
14475     }
14476
14477     return TRUE;
14478 }
14479
14480 void
14481 MailMoveEvent ()
14482 {
14483 #if !WIN32
14484     static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
14485     FILE *commandOutput;
14486     char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
14487     int nBytes = 0;             /*  Suppress warnings on uninitialized variables    */
14488     int nBuffers;
14489     int i;
14490     int archived;
14491     char *arcDir;
14492
14493     if (! cmailMsgLoaded) {
14494         DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
14495         return;
14496     }
14497
14498     if (nCmailGames == nCmailResults) {
14499         DisplayError(_("No unfinished games"), 0);
14500         return;
14501     }
14502
14503 #if CMAIL_PROHIBIT_REMAIL
14504     if (cmailMailedMove) {
14505       snprintf(msg, MSG_SIZ, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName);
14506         DisplayError(msg, 0);
14507         return;
14508     }
14509 #endif
14510
14511     if (! (cmailMailedMove || RegisterMove())) return;
14512
14513     if (   cmailMailedMove
14514         || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
14515       snprintf(string, MSG_SIZ, partCommandString,
14516                appData.debugMode ? " -v" : "", appData.cmailGameName);
14517         commandOutput = popen(string, "r");
14518
14519         if (commandOutput == NULL) {
14520             DisplayError(_("Failed to invoke cmail"), 0);
14521         } else {
14522             for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
14523                 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
14524             }
14525             if (nBuffers > 1) {
14526                 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
14527                 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
14528                 nBytes = MSG_SIZ - 1;
14529             } else {
14530                 (void) memcpy(msg, buffer, nBytes);
14531             }
14532             *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
14533
14534             if(StrStr(msg, "Mailed cmail message to ") != NULL) {
14535                 cmailMailedMove = TRUE; /* Prevent >1 moves    */
14536
14537                 archived = TRUE;
14538                 for (i = 0; i < nCmailGames; i ++) {
14539                     if (cmailResult[i] == CMAIL_NOT_RESULT) {
14540                         archived = FALSE;
14541                     }
14542                 }
14543                 if (   archived
14544                     && (   (arcDir = (char *) getenv("CMAIL_ARCDIR"))
14545                         != NULL)) {
14546                   snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
14547                            arcDir,
14548                            appData.cmailGameName,
14549                            gameInfo.date);
14550                     LoadGameFromFile(buffer, 1, buffer, FALSE);
14551                     cmailMsgLoaded = FALSE;
14552                 }
14553             }
14554
14555             DisplayInformation(msg);
14556             pclose(commandOutput);
14557         }
14558     } else {
14559         if ((*cmailMsg) != '\0') {
14560             DisplayInformation(cmailMsg);
14561         }
14562     }
14563
14564     return;
14565 #endif /* !WIN32 */
14566 }
14567
14568 char *
14569 CmailMsg ()
14570 {
14571 #if WIN32
14572     return NULL;
14573 #else
14574     int  prependComma = 0;
14575     char number[5];
14576     char string[MSG_SIZ];       /* Space for game-list */
14577     int  i;
14578
14579     if (!cmailMsgLoaded) return "";
14580
14581     if (cmailMailedMove) {
14582       snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
14583     } else {
14584         /* Create a list of games left */
14585       snprintf(string, MSG_SIZ, "[");
14586         for (i = 0; i < nCmailGames; i ++) {
14587             if (! (   cmailMoveRegistered[i]
14588                    || (cmailResult[i] == CMAIL_OLD_RESULT))) {
14589                 if (prependComma) {
14590                     snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
14591                 } else {
14592                     snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
14593                     prependComma = 1;
14594                 }
14595
14596                 strcat(string, number);
14597             }
14598         }
14599         strcat(string, "]");
14600
14601         if (nCmailMovesRegistered + nCmailResults == 0) {
14602             switch (nCmailGames) {
14603               case 1:
14604                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
14605                 break;
14606
14607               case 2:
14608                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
14609                 break;
14610
14611               default:
14612                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
14613                          nCmailGames);
14614                 break;
14615             }
14616         } else {
14617             switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
14618               case 1:
14619                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
14620                          string);
14621                 break;
14622
14623               case 0:
14624                 if (nCmailResults == nCmailGames) {
14625                   snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
14626                 } else {
14627                   snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
14628                 }
14629                 break;
14630
14631               default:
14632                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
14633                          string);
14634             }
14635         }
14636     }
14637     return cmailMsg;
14638 #endif /* WIN32 */
14639 }
14640
14641 void
14642 ResetGameEvent ()
14643 {
14644     if (gameMode == Training)
14645       SetTrainingModeOff();
14646
14647     Reset(TRUE, TRUE);
14648     cmailMsgLoaded = FALSE;
14649     if (appData.icsActive) {
14650       SendToICS(ics_prefix);
14651       SendToICS("refresh\n");
14652     }
14653 }
14654
14655 void
14656 ExitEvent (int status)
14657 {
14658     exiting++;
14659     if (exiting > 2) {
14660       /* Give up on clean exit */
14661       exit(status);
14662     }
14663     if (exiting > 1) {
14664       /* Keep trying for clean exit */
14665       return;
14666     }
14667
14668     if (appData.icsActive) printf("\n"); // [HGM] end on new line after closing XBoard
14669     if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
14670
14671     if (telnetISR != NULL) {
14672       RemoveInputSource(telnetISR);
14673     }
14674     if (icsPR != NoProc) {
14675       DestroyChildProcess(icsPR, TRUE);
14676     }
14677
14678     /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
14679     GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
14680
14681     /* [HGM] crash: the above GameEnds() is a dud if another one was running */
14682     /* make sure this other one finishes before killing it!                  */
14683     if(endingGame) { int count = 0;
14684         if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
14685         while(endingGame && count++ < 10) DoSleep(1);
14686         if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
14687     }
14688
14689     /* Kill off chess programs */
14690     if (first.pr != NoProc) {
14691         ExitAnalyzeMode();
14692
14693         DoSleep( appData.delayBeforeQuit );
14694         SendToProgram("quit\n", &first);
14695         DestroyChildProcess(first.pr, 4 + first.useSigterm /* [AS] first.useSigterm */ );
14696     }
14697     if (second.pr != NoProc) {
14698         DoSleep( appData.delayBeforeQuit );
14699         SendToProgram("quit\n", &second);
14700         DestroyChildProcess(second.pr, 4 + second.useSigterm /* [AS] second.useSigterm */ );
14701     }
14702     if (first.isr != NULL) {
14703         RemoveInputSource(first.isr);
14704     }
14705     if (second.isr != NULL) {
14706         RemoveInputSource(second.isr);
14707     }
14708
14709     if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
14710     if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
14711
14712     ShutDownFrontEnd();
14713     exit(status);
14714 }
14715
14716 void
14717 PauseEngine (ChessProgramState *cps)
14718 {
14719     SendToProgram("pause\n", cps);
14720     cps->pause = 2;
14721 }
14722
14723 void
14724 UnPauseEngine (ChessProgramState *cps)
14725 {
14726     SendToProgram("resume\n", cps);
14727     cps->pause = 1;
14728 }
14729
14730 void
14731 PauseEvent ()
14732 {
14733     if (appData.debugMode)
14734         fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
14735     if (pausing) {
14736         pausing = FALSE;
14737         ModeHighlight();
14738         if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
14739             StartClocks();
14740             if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
14741                 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
14742                 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
14743             }
14744             if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
14745             HandleMachineMove(stashedInputMove, stalledEngine);
14746             stalledEngine = NULL;
14747             return;
14748         }
14749         if (gameMode == MachinePlaysWhite ||
14750             gameMode == TwoMachinesPlay   ||
14751             gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
14752             if(first.pause)  UnPauseEngine(&first);
14753             else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
14754             if(second.pause) UnPauseEngine(&second);
14755             else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
14756             StartClocks();
14757         } else {
14758             DisplayBothClocks();
14759         }
14760         if (gameMode == PlayFromGameFile) {
14761             if (appData.timeDelay >= 0)
14762                 AutoPlayGameLoop();
14763         } else if (gameMode == IcsExamining && pauseExamInvalid) {
14764             Reset(FALSE, TRUE);
14765             SendToICS(ics_prefix);
14766             SendToICS("refresh\n");
14767         } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
14768             ForwardInner(forwardMostMove);
14769         }
14770         pauseExamInvalid = FALSE;
14771     } else {
14772         switch (gameMode) {
14773           default:
14774             return;
14775           case IcsExamining:
14776             pauseExamForwardMostMove = forwardMostMove;
14777             pauseExamInvalid = FALSE;
14778             /* fall through */
14779           case IcsObserving:
14780           case IcsPlayingWhite:
14781           case IcsPlayingBlack:
14782             pausing = TRUE;
14783             ModeHighlight();
14784             return;
14785           case PlayFromGameFile:
14786             (void) StopLoadGameTimer();
14787             pausing = TRUE;
14788             ModeHighlight();
14789             break;
14790           case BeginningOfGame:
14791             if (appData.icsActive) return;
14792             /* else fall through */
14793           case MachinePlaysWhite:
14794           case MachinePlaysBlack:
14795           case TwoMachinesPlay:
14796             if (forwardMostMove == 0)
14797               return;           /* don't pause if no one has moved */
14798             if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
14799                 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
14800                 if(onMove->pause) {           // thinking engine can be paused
14801                     PauseEngine(onMove);      // do it
14802                     if(onMove->other->pause)  // pondering opponent can always be paused immediately
14803                         PauseEngine(onMove->other);
14804                     else
14805                         SendToProgram("easy\n", onMove->other);
14806                     StopClocks();
14807                 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
14808             } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
14809                 if(first.pause) {
14810                     PauseEngine(&first);
14811                     StopClocks();
14812                 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
14813             } else { // human on move, pause pondering by either method
14814                 if(first.pause)
14815                     PauseEngine(&first);
14816                 else if(appData.ponderNextMove)
14817                     SendToProgram("easy\n", &first);
14818                 StopClocks();
14819             }
14820             // if no immediate pausing is possible, wait for engine to move, and stop clocks then
14821           case AnalyzeMode:
14822             pausing = TRUE;
14823             ModeHighlight();
14824             break;
14825         }
14826     }
14827 }
14828
14829 void
14830 EditCommentEvent ()
14831 {
14832     char title[MSG_SIZ];
14833
14834     if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
14835       safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
14836     } else {
14837       snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
14838                WhiteOnMove(currentMove - 1) ? " " : ".. ",
14839                parseList[currentMove - 1]);
14840     }
14841
14842     EditCommentPopUp(currentMove, title, commentList[currentMove]);
14843 }
14844
14845
14846 void
14847 EditTagsEvent ()
14848 {
14849     char *tags = PGNTags(&gameInfo);
14850     bookUp = FALSE;
14851     EditTagsPopUp(tags, NULL);
14852     free(tags);
14853 }
14854
14855 void
14856 StartSecond ()
14857 {
14858     if(WaitForEngine(&second, StartSecond)) return;
14859     InitChessProgram(&second, FALSE);
14860     FeedMovesToProgram(&second, currentMove);
14861
14862     SendToProgram("analyze\n", &second);
14863     second.analyzing = TRUE;
14864     ThawUI();
14865 }
14866
14867 void
14868 ToggleSecond ()
14869 {
14870   if(second.analyzing) {
14871     SendToProgram("exit\n", &second);
14872     second.analyzing = FALSE;
14873   } else {
14874     StartSecond();
14875   }
14876 }
14877
14878 /* Toggle ShowThinking */
14879 void
14880 ToggleShowThinking()
14881 {
14882   appData.showThinking = !appData.showThinking;
14883   ShowThinkingEvent();
14884 }
14885
14886 int
14887 AnalyzeModeEvent ()
14888 {
14889     char buf[MSG_SIZ];
14890
14891     if (!first.analysisSupport) {
14892       snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14893       DisplayError(buf, 0);
14894       return 0;
14895     }
14896     /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
14897     if (appData.icsActive) {
14898         if (gameMode != IcsObserving) {
14899           snprintf(buf, MSG_SIZ, _("You are not observing a game"));
14900             DisplayError(buf, 0);
14901             /* secure check */
14902             if (appData.icsEngineAnalyze) {
14903                 if (appData.debugMode)
14904                     fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
14905                 ExitAnalyzeMode();
14906                 ModeHighlight();
14907             }
14908             return 0;
14909         }
14910         /* if enable, user wants to disable icsEngineAnalyze */
14911         if (appData.icsEngineAnalyze) {
14912                 ExitAnalyzeMode();
14913                 ModeHighlight();
14914                 return 0;
14915         }
14916         appData.icsEngineAnalyze = TRUE;
14917         if (appData.debugMode)
14918             fprintf(debugFP, "ICS engine analyze starting... \n");
14919     }
14920
14921     if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
14922     if (appData.noChessProgram || gameMode == AnalyzeMode)
14923       return 0;
14924
14925     if (gameMode != AnalyzeFile) {
14926         if (!appData.icsEngineAnalyze) {
14927                EditGameEvent();
14928                if (gameMode != EditGame) return 0;
14929         }
14930         if (!appData.showThinking) ToggleShowThinking();
14931         ResurrectChessProgram();
14932         SendToProgram("analyze\n", &first);
14933         first.analyzing = TRUE;
14934         /*first.maybeThinking = TRUE;*/
14935         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14936         EngineOutputPopUp();
14937     }
14938     if (!appData.icsEngineAnalyze) {
14939         gameMode = AnalyzeMode;
14940         ClearEngineOutputPane(0); // [TK] exclude: to print exclusion/multipv header
14941     }
14942     pausing = FALSE;
14943     ModeHighlight();
14944     SetGameInfo();
14945
14946     StartAnalysisClock();
14947     GetTimeMark(&lastNodeCountTime);
14948     lastNodeCount = 0;
14949     return 1;
14950 }
14951
14952 void
14953 AnalyzeFileEvent ()
14954 {
14955     if (appData.noChessProgram || gameMode == AnalyzeFile)
14956       return;
14957
14958     if (!first.analysisSupport) {
14959       char buf[MSG_SIZ];
14960       snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14961       DisplayError(buf, 0);
14962       return;
14963     }
14964
14965     if (gameMode != AnalyzeMode) {
14966         keepInfo = 1; // mere annotating should not alter PGN tags
14967         EditGameEvent();
14968         keepInfo = 0;
14969         if (gameMode != EditGame) return;
14970         if (!appData.showThinking) ToggleShowThinking();
14971         ResurrectChessProgram();
14972         SendToProgram("analyze\n", &first);
14973         first.analyzing = TRUE;
14974         /*first.maybeThinking = TRUE;*/
14975         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14976         EngineOutputPopUp();
14977     }
14978     gameMode = AnalyzeFile;
14979     pausing = FALSE;
14980     ModeHighlight();
14981
14982     StartAnalysisClock();
14983     GetTimeMark(&lastNodeCountTime);
14984     lastNodeCount = 0;
14985     if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
14986     AnalysisPeriodicEvent(1);
14987 }
14988
14989 void
14990 MachineWhiteEvent ()
14991 {
14992     char buf[MSG_SIZ];
14993     char *bookHit = NULL;
14994
14995     if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
14996       return;
14997
14998
14999     if (gameMode == PlayFromGameFile ||
15000         gameMode == TwoMachinesPlay  ||
15001         gameMode == Training         ||
15002         gameMode == AnalyzeMode      ||
15003         gameMode == EndOfGame)
15004         EditGameEvent();
15005
15006     if (gameMode == EditPosition)
15007         EditPositionDone(TRUE);
15008
15009     if (!WhiteOnMove(currentMove)) {
15010         DisplayError(_("It is not White's turn"), 0);
15011         return;
15012     }
15013
15014     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
15015       ExitAnalyzeMode();
15016
15017     if (gameMode == EditGame || gameMode == AnalyzeMode ||
15018         gameMode == AnalyzeFile)
15019         TruncateGame();
15020
15021     ResurrectChessProgram();    /* in case it isn't running */
15022     if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
15023         gameMode = MachinePlaysWhite;
15024         ResetClocks();
15025     } else
15026     gameMode = MachinePlaysWhite;
15027     pausing = FALSE;
15028     ModeHighlight();
15029     SetGameInfo();
15030     snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15031     DisplayTitle(buf);
15032     if (first.sendName) {
15033       snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
15034       SendToProgram(buf, &first);
15035     }
15036     if (first.sendTime) {
15037       if (first.useColors) {
15038         SendToProgram("black\n", &first); /*gnu kludge*/
15039       }
15040       SendTimeRemaining(&first, TRUE);
15041     }
15042     if (first.useColors) {
15043       SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
15044     }
15045     bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
15046     SetMachineThinkingEnables();
15047     first.maybeThinking = TRUE;
15048     StartClocks();
15049     firstMove = FALSE;
15050
15051     if (appData.autoFlipView && !flipView) {
15052       flipView = !flipView;
15053       DrawPosition(FALSE, NULL);
15054       DisplayBothClocks();       // [HGM] logo: clocks might have to be exchanged;
15055     }
15056
15057     if(bookHit) { // [HGM] book: simulate book reply
15058         static char bookMove[MSG_SIZ]; // a bit generous?
15059
15060         programStats.nodes = programStats.depth = programStats.time =
15061         programStats.score = programStats.got_only_move = 0;
15062         sprintf(programStats.movelist, "%s (xbook)", bookHit);
15063
15064         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15065         strcat(bookMove, bookHit);
15066         savedMessage = bookMove; // args for deferred call
15067         savedState = &first;
15068         ScheduleDelayedEvent(DeferredBookMove, 1);
15069     }
15070 }
15071
15072 void
15073 MachineBlackEvent ()
15074 {
15075   char buf[MSG_SIZ];
15076   char *bookHit = NULL;
15077
15078     if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
15079         return;
15080
15081
15082     if (gameMode == PlayFromGameFile ||
15083         gameMode == TwoMachinesPlay  ||
15084         gameMode == Training         ||
15085         gameMode == AnalyzeMode      ||
15086         gameMode == EndOfGame)
15087         EditGameEvent();
15088
15089     if (gameMode == EditPosition)
15090         EditPositionDone(TRUE);
15091
15092     if (WhiteOnMove(currentMove)) {
15093         DisplayError(_("It is not Black's turn"), 0);
15094         return;
15095     }
15096
15097     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
15098       ExitAnalyzeMode();
15099
15100     if (gameMode == EditGame || gameMode == AnalyzeMode ||
15101         gameMode == AnalyzeFile)
15102         TruncateGame();
15103
15104     ResurrectChessProgram();    /* in case it isn't running */
15105     gameMode = MachinePlaysBlack;
15106     pausing = FALSE;
15107     ModeHighlight();
15108     SetGameInfo();
15109     snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15110     DisplayTitle(buf);
15111     if (first.sendName) {
15112       snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
15113       SendToProgram(buf, &first);
15114     }
15115     if (first.sendTime) {
15116       if (first.useColors) {
15117         SendToProgram("white\n", &first); /*gnu kludge*/
15118       }
15119       SendTimeRemaining(&first, FALSE);
15120     }
15121     if (first.useColors) {
15122       SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
15123     }
15124     bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
15125     SetMachineThinkingEnables();
15126     first.maybeThinking = TRUE;
15127     StartClocks();
15128
15129     if (appData.autoFlipView && flipView) {
15130       flipView = !flipView;
15131       DrawPosition(FALSE, NULL);
15132       DisplayBothClocks();       // [HGM] logo: clocks might have to be exchanged;
15133     }
15134     if(bookHit) { // [HGM] book: simulate book reply
15135         static char bookMove[MSG_SIZ]; // a bit generous?
15136
15137         programStats.nodes = programStats.depth = programStats.time =
15138         programStats.score = programStats.got_only_move = 0;
15139         sprintf(programStats.movelist, "%s (xbook)", bookHit);
15140
15141         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15142         strcat(bookMove, bookHit);
15143         savedMessage = bookMove; // args for deferred call
15144         savedState = &first;
15145         ScheduleDelayedEvent(DeferredBookMove, 1);
15146     }
15147 }
15148
15149
15150 void
15151 DisplayTwoMachinesTitle ()
15152 {
15153     char buf[MSG_SIZ];
15154     if (appData.matchGames > 0) {
15155         if(appData.tourneyFile[0]) {
15156           snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
15157                    gameInfo.white, _("vs."), gameInfo.black,
15158                    nextGame+1, appData.matchGames+1,
15159                    appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
15160         } else
15161         if (first.twoMachinesColor[0] == 'w') {
15162           snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
15163                    gameInfo.white, _("vs."),  gameInfo.black,
15164                    first.matchWins, second.matchWins,
15165                    matchGame - 1 - (first.matchWins + second.matchWins));
15166         } else {
15167           snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
15168                    gameInfo.white, _("vs."), gameInfo.black,
15169                    second.matchWins, first.matchWins,
15170                    matchGame - 1 - (first.matchWins + second.matchWins));
15171         }
15172     } else {
15173       snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15174     }
15175     DisplayTitle(buf);
15176 }
15177
15178 void
15179 SettingsMenuIfReady ()
15180 {
15181   if (second.lastPing != second.lastPong) {
15182     DisplayMessage("", _("Waiting for second chess program"));
15183     ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
15184     return;
15185   }
15186   ThawUI();
15187   DisplayMessage("", "");
15188   SettingsPopUp(&second);
15189 }
15190
15191 int
15192 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
15193 {
15194     char buf[MSG_SIZ];
15195     if (cps->pr == NoProc) {
15196         StartChessProgram(cps);
15197         if (cps->protocolVersion == 1) {
15198           retry();
15199           ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
15200         } else {
15201           /* kludge: allow timeout for initial "feature" command */
15202           if(retry != TwoMachinesEventIfReady) FreezeUI();
15203           snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
15204           DisplayMessage("", buf);
15205           ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
15206         }
15207         return 1;
15208     }
15209     return 0;
15210 }
15211
15212 void
15213 TwoMachinesEvent P((void))
15214 {
15215     int i, move = forwardMostMove;
15216     char buf[MSG_SIZ];
15217     ChessProgramState *onmove;
15218     char *bookHit = NULL;
15219     static int stalling = 0;
15220     TimeMark now;
15221     long wait;
15222
15223     if (appData.noChessProgram) return;
15224
15225     switch (gameMode) {
15226       case TwoMachinesPlay:
15227         return;
15228       case MachinePlaysWhite:
15229       case MachinePlaysBlack:
15230         if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15231             DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
15232             return;
15233         }
15234         /* fall through */
15235       case BeginningOfGame:
15236       case PlayFromGameFile:
15237       case EndOfGame:
15238         EditGameEvent();
15239         if (gameMode != EditGame) return;
15240         break;
15241       case EditPosition:
15242         EditPositionDone(TRUE);
15243         break;
15244       case AnalyzeMode:
15245       case AnalyzeFile:
15246         ExitAnalyzeMode();
15247         break;
15248       case EditGame:
15249       default:
15250         break;
15251     }
15252
15253 //    forwardMostMove = currentMove;
15254     TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
15255     startingEngine = TRUE;
15256
15257     if(!ResurrectChessProgram()) return;   /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
15258
15259     if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
15260     if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
15261       ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
15262       return;
15263     }
15264   if(!appData.epd) {
15265     if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
15266
15267     if(!SupportedVariant(second.variants, gameInfo.variant, gameInfo.boardWidth,
15268                          gameInfo.boardHeight, gameInfo.holdingsSize, second.protocolVersion, second.tidy)) {
15269         startingEngine = matchMode = FALSE;
15270         DisplayError("second engine does not play this", 0);
15271         gameMode = TwoMachinesPlay; ModeHighlight(); // Needed to make sure menu item is unchecked
15272         EditGameEvent(); // switch back to EditGame mode
15273         return;
15274     }
15275
15276     if(!stalling) {
15277       InitChessProgram(&second, FALSE); // unbalances ping of second engine
15278       SendToProgram("force\n", &second);
15279       stalling = 1;
15280       ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
15281       return;
15282     }
15283   }
15284     GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
15285     if(appData.matchPause>10000 || appData.matchPause<10)
15286                 appData.matchPause = 10000; /* [HGM] make pause adjustable */
15287     wait = SubtractTimeMarks(&now, &pauseStart);
15288     if(wait < appData.matchPause) {
15289         ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
15290         return;
15291     }
15292     // we are now committed to starting the game
15293     stalling = 0;
15294     DisplayMessage("", "");
15295   if(!appData.epd) {
15296     if (startedFromSetupPosition) {
15297         SendBoard(&second, backwardMostMove);
15298     if (appData.debugMode) {
15299         fprintf(debugFP, "Two Machines\n");
15300     }
15301     }
15302     for (i = backwardMostMove; i < forwardMostMove; i++) {
15303         SendMoveToProgram(i, &second);
15304     }
15305   }
15306
15307     gameMode = TwoMachinesPlay;
15308     pausing = startingEngine = FALSE;
15309     ModeHighlight(); // [HGM] logo: this triggers display update of logos
15310     SetGameInfo();
15311     DisplayTwoMachinesTitle();
15312     firstMove = TRUE;
15313     if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
15314         onmove = &first;
15315     } else {
15316         onmove = &second;
15317     }
15318     if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
15319     SendToProgram(first.computerString, &first);
15320     if (first.sendName) {
15321       snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
15322       SendToProgram(buf, &first);
15323     }
15324   if(!appData.epd) {
15325     SendToProgram(second.computerString, &second);
15326     if (second.sendName) {
15327       snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
15328       SendToProgram(buf, &second);
15329     }
15330   }
15331
15332     if (!first.sendTime || !second.sendTime || move == 0) { // [HGM] first engine changed sides from Reset, so recalc time odds
15333         ResetClocks();
15334         timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15335         timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15336     }
15337     if (onmove->sendTime) {
15338       if (onmove->useColors) {
15339         SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
15340       }
15341       SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
15342     }
15343     if (onmove->useColors) {
15344       SendToProgram(onmove->twoMachinesColor, onmove);
15345     }
15346     bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
15347 //    SendToProgram("go\n", onmove);
15348     onmove->maybeThinking = TRUE;
15349     SetMachineThinkingEnables();
15350
15351     StartClocks();
15352
15353     if(bookHit) { // [HGM] book: simulate book reply
15354         static char bookMove[MSG_SIZ]; // a bit generous?
15355
15356         programStats.nodes = programStats.depth = programStats.time =
15357         programStats.score = programStats.got_only_move = 0;
15358         sprintf(programStats.movelist, "%s (xbook)", bookHit);
15359
15360         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15361         strcat(bookMove, bookHit);
15362         savedMessage = bookMove; // args for deferred call
15363         savedState = onmove;
15364         ScheduleDelayedEvent(DeferredBookMove, 1);
15365     }
15366 }
15367
15368 void
15369 TrainingEvent ()
15370 {
15371     if (gameMode == Training) {
15372       SetTrainingModeOff();
15373       gameMode = PlayFromGameFile;
15374       DisplayMessage("", _("Training mode off"));
15375     } else {
15376       gameMode = Training;
15377       animateTraining = appData.animate;
15378
15379       /* make sure we are not already at the end of the game */
15380       if (currentMove < forwardMostMove) {
15381         SetTrainingModeOn();
15382         DisplayMessage("", _("Training mode on"));
15383       } else {
15384         gameMode = PlayFromGameFile;
15385         DisplayError(_("Already at end of game"), 0);
15386       }
15387     }
15388     ModeHighlight();
15389 }
15390
15391 void
15392 IcsClientEvent ()
15393 {
15394     if (!appData.icsActive) return;
15395     switch (gameMode) {
15396       case IcsPlayingWhite:
15397       case IcsPlayingBlack:
15398       case IcsObserving:
15399       case IcsIdle:
15400       case BeginningOfGame:
15401       case IcsExamining:
15402         return;
15403
15404       case EditGame:
15405         break;
15406
15407       case EditPosition:
15408         EditPositionDone(TRUE);
15409         break;
15410
15411       case AnalyzeMode:
15412       case AnalyzeFile:
15413         ExitAnalyzeMode();
15414         break;
15415
15416       default:
15417         EditGameEvent();
15418         break;
15419     }
15420
15421     gameMode = IcsIdle;
15422     ModeHighlight();
15423     return;
15424 }
15425
15426 void
15427 EditGameEvent ()
15428 {
15429     int i;
15430
15431     switch (gameMode) {
15432       case Training:
15433         SetTrainingModeOff();
15434         break;
15435       case MachinePlaysWhite:
15436       case MachinePlaysBlack:
15437       case BeginningOfGame:
15438         SendToProgram("force\n", &first);
15439         if(gameMode == (forwardMostMove & 1 ? MachinePlaysBlack : MachinePlaysWhite)) { // engine is thinking
15440             if (first.usePing) { // [HGM] always send ping when we might interrupt machine thinking
15441                 char buf[MSG_SIZ];
15442                 abortEngineThink = TRUE;
15443                 snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++first.lastPing);
15444                 SendToProgram(buf, &first);
15445                 DisplayMessage("Aborting engine think", "");
15446                 FreezeUI();
15447             }
15448         }
15449         SetUserThinkingEnables();
15450         break;
15451       case PlayFromGameFile:
15452         (void) StopLoadGameTimer();
15453         if (gameFileFP != NULL) {
15454             gameFileFP = NULL;
15455         }
15456         break;
15457       case EditPosition:
15458         EditPositionDone(TRUE);
15459         break;
15460       case AnalyzeMode:
15461       case AnalyzeFile:
15462         ExitAnalyzeMode();
15463         SendToProgram("force\n", &first);
15464         break;
15465       case TwoMachinesPlay:
15466         GameEnds(EndOfFile, NULL, GE_PLAYER);
15467         ResurrectChessProgram();
15468         SetUserThinkingEnables();
15469         break;
15470       case EndOfGame:
15471         ResurrectChessProgram();
15472         break;
15473       case IcsPlayingBlack:
15474       case IcsPlayingWhite:
15475         DisplayError(_("Warning: You are still playing a game"), 0);
15476         break;
15477       case IcsObserving:
15478         DisplayError(_("Warning: You are still observing a game"), 0);
15479         break;
15480       case IcsExamining:
15481         DisplayError(_("Warning: You are still examining a game"), 0);
15482         break;
15483       case IcsIdle:
15484         break;
15485       case EditGame:
15486       default:
15487         return;
15488     }
15489
15490     pausing = FALSE;
15491     StopClocks();
15492     first.offeredDraw = second.offeredDraw = 0;
15493
15494     if (gameMode == PlayFromGameFile) {
15495         whiteTimeRemaining = timeRemaining[0][currentMove];
15496         blackTimeRemaining = timeRemaining[1][currentMove];
15497         DisplayTitle("");
15498     }
15499
15500     if (gameMode == MachinePlaysWhite ||
15501         gameMode == MachinePlaysBlack ||
15502         gameMode == TwoMachinesPlay ||
15503         gameMode == EndOfGame) {
15504         i = forwardMostMove;
15505         while (i > currentMove) {
15506             SendToProgram("undo\n", &first);
15507             i--;
15508         }
15509         if(!adjustedClock) {
15510         whiteTimeRemaining = timeRemaining[0][currentMove];
15511         blackTimeRemaining = timeRemaining[1][currentMove];
15512         DisplayBothClocks();
15513         }
15514         if (whiteFlag || blackFlag) {
15515             whiteFlag = blackFlag = 0;
15516         }
15517         DisplayTitle("");
15518     }
15519
15520     gameMode = EditGame;
15521     ModeHighlight();
15522     SetGameInfo();
15523 }
15524
15525 void
15526 EditPositionEvent ()
15527 {
15528     int i;
15529     if (gameMode == EditPosition) {
15530         EditGameEvent();
15531         return;
15532     }
15533
15534     EditGameEvent();
15535     if (gameMode != EditGame) return;
15536
15537     gameMode = EditPosition;
15538     ModeHighlight();
15539     SetGameInfo();
15540     CopyBoard(rightsBoard, nullBoard);
15541     if (currentMove > 0)
15542       CopyBoard(boards[0], boards[currentMove]);
15543     for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
15544       rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
15545
15546     blackPlaysFirst = !WhiteOnMove(currentMove);
15547     ResetClocks();
15548     currentMove = forwardMostMove = backwardMostMove = 0;
15549     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15550     DisplayMove(-1);
15551     if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
15552 }
15553
15554 void
15555 ExitAnalyzeMode ()
15556 {
15557     /* [DM] icsEngineAnalyze - possible call from other functions */
15558     if (appData.icsEngineAnalyze) {
15559         appData.icsEngineAnalyze = FALSE;
15560
15561         DisplayMessage("",_("Close ICS engine analyze..."));
15562     }
15563     if (first.analysisSupport && first.analyzing) {
15564       SendToBoth("exit\n");
15565       first.analyzing = second.analyzing = FALSE;
15566     }
15567     thinkOutput[0] = NULLCHAR;
15568 }
15569
15570 void
15571 EditPositionDone (Boolean fakeRights)
15572 {
15573     int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
15574
15575     startedFromSetupPosition = TRUE;
15576     InitChessProgram(&first, FALSE);
15577     if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
15578       int r, f;
15579       boards[0][EP_STATUS] = EP_NONE;
15580       for(f=0; f<=nrCastlingRights; f++) boards[0][CASTLING][f] = NoRights;
15581       for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // first pass: Kings & e.p.
15582         if(rightsBoard[r][f]) {
15583           ChessSquare p = boards[0][r][f];
15584           if(p == (blackPlaysFirst ? WhitePawn : BlackPawn)) boards[0][EP_STATUS] = f;
15585           else if(p == king) boards[0][CASTLING][2] = f;
15586           else if(p == WHITE_TO_BLACK king) boards[0][CASTLING][5] = f;
15587           else rightsBoard[r][f] = 2; // mark for second pass
15588         }
15589       }
15590       for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // second pass: Rooks
15591         if(rightsBoard[r][f] == 2) {
15592           ChessSquare p = boards[0][r][f];
15593           if(p == WhiteRook) boards[0][CASTLING][(f < boards[0][CASTLING][2])] = f; else
15594           if(p == BlackRook) boards[0][CASTLING][(f < boards[0][CASTLING][5])+3] = f;
15595         }
15596       }
15597     }
15598     SendToProgram("force\n", &first);
15599     if (blackPlaysFirst) {
15600         safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
15601         safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
15602         currentMove = forwardMostMove = backwardMostMove = 1;
15603         CopyBoard(boards[1], boards[0]);
15604     } else {
15605         currentMove = forwardMostMove = backwardMostMove = 0;
15606     }
15607     SendBoard(&first, forwardMostMove);
15608     if (appData.debugMode) {
15609         fprintf(debugFP, "EditPosDone\n");
15610     }
15611     DisplayTitle("");
15612     DisplayMessage("", "");
15613     timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15614     timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15615     gameMode = EditGame;
15616     ModeHighlight();
15617     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15618     ClearHighlights(); /* [AS] */
15619 }
15620
15621 /* Pause for `ms' milliseconds */
15622 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15623 void
15624 TimeDelay (long ms)
15625 {
15626     TimeMark m1, m2;
15627
15628     GetTimeMark(&m1);
15629     do {
15630         GetTimeMark(&m2);
15631     } while (SubtractTimeMarks(&m2, &m1) < ms);
15632 }
15633
15634 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15635 void
15636 SendMultiLineToICS (char *buf)
15637 {
15638     char temp[MSG_SIZ+1], *p;
15639     int len;
15640
15641     len = strlen(buf);
15642     if (len > MSG_SIZ)
15643       len = MSG_SIZ;
15644
15645     strncpy(temp, buf, len);
15646     temp[len] = 0;
15647
15648     p = temp;
15649     while (*p) {
15650         if (*p == '\n' || *p == '\r')
15651           *p = ' ';
15652         ++p;
15653     }
15654
15655     strcat(temp, "\n");
15656     SendToICS(temp);
15657     SendToPlayer(temp, strlen(temp));
15658 }
15659
15660 void
15661 SetWhiteToPlayEvent ()
15662 {
15663     if (gameMode == EditPosition) {
15664         blackPlaysFirst = FALSE;
15665         DisplayBothClocks();    /* works because currentMove is 0 */
15666     } else if (gameMode == IcsExamining) {
15667         SendToICS(ics_prefix);
15668         SendToICS("tomove white\n");
15669     }
15670 }
15671
15672 void
15673 SetBlackToPlayEvent ()
15674 {
15675     if (gameMode == EditPosition) {
15676         blackPlaysFirst = TRUE;
15677         currentMove = 1;        /* kludge */
15678         DisplayBothClocks();
15679         currentMove = 0;
15680     } else if (gameMode == IcsExamining) {
15681         SendToICS(ics_prefix);
15682         SendToICS("tomove black\n");
15683     }
15684 }
15685
15686 void
15687 EditPositionMenuEvent (ChessSquare selection, int x, int y)
15688 {
15689     char buf[MSG_SIZ];
15690     ChessSquare piece = boards[0][y][x];
15691     static Board erasedBoard, currentBoard, menuBoard, nullBoard;
15692     static int lastVariant;
15693     int baseRank = BOARD_HEIGHT-1, hasRights = 0;
15694
15695     if (gameMode != EditPosition && gameMode != IcsExamining) return;
15696
15697     switch (selection) {
15698       case ClearBoard:
15699         fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
15700         MarkTargetSquares(1);
15701         CopyBoard(currentBoard, boards[0]);
15702         CopyBoard(menuBoard, initialPosition);
15703         if (gameMode == IcsExamining && ics_type == ICS_FICS) {
15704             SendToICS(ics_prefix);
15705             SendToICS("bsetup clear\n");
15706         } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
15707             SendToICS(ics_prefix);
15708             SendToICS("clearboard\n");
15709         } else {
15710             int nonEmpty = 0;
15711             for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
15712                 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
15713                 for (y = 0; y < BOARD_HEIGHT; y++) {
15714                     if (gameMode == IcsExamining) {
15715                         if (boards[currentMove][y][x] != EmptySquare) {
15716                           snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
15717                                     AAA + x, ONE + y);
15718                             SendToICS(buf);
15719                         }
15720                     } else if(boards[0][y][x] != DarkSquare) {
15721                         if(boards[0][y][x] != p) nonEmpty++;
15722                         boards[0][y][x] = p;
15723                     }
15724                 }
15725             }
15726             CopyBoard(rightsBoard, nullBoard);
15727             if(gameMode != IcsExamining) { // [HGM] editpos: cycle trough boards
15728                 int r, i;
15729                 for(r = 0; r < BOARD_HEIGHT; r++) {
15730                   for(x = BOARD_LEFT; x < BOARD_RGHT; x++) { // create 'menu board' by removing duplicates 
15731                     ChessSquare p = menuBoard[r][x];
15732                     for(y = x + 1; y < BOARD_RGHT; y++) if(menuBoard[r][y] == p) menuBoard[r][y] = EmptySquare;
15733                   }
15734                 }
15735                 menuBoard[CASTLING][0] = menuBoard[CASTLING][3] = NoRights; // h-side Rook was deleted
15736                 DisplayMessage("Clicking clock again restores position", "");
15737                 if(gameInfo.variant != lastVariant) lastVariant = gameInfo.variant, CopyBoard(erasedBoard, boards[0]);
15738                 if(!nonEmpty) { // asked to clear an empty board
15739                     CopyBoard(boards[0], menuBoard);
15740                 } else
15741                 if(CompareBoards(currentBoard, menuBoard)) { // asked to clear an empty board
15742                     CopyBoard(boards[0], initialPosition);
15743                 } else
15744                 if(CompareBoards(currentBoard, initialPosition) && !CompareBoards(currentBoard, erasedBoard)
15745                                                                  && !CompareBoards(nullBoard, erasedBoard)) {
15746                     CopyBoard(boards[0], erasedBoard);
15747                 } else
15748                     CopyBoard(erasedBoard, currentBoard);
15749
15750                 for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
15751                     rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
15752             }
15753         }
15754         if (gameMode == EditPosition) {
15755             DrawPosition(FALSE, boards[0]);
15756         }
15757         break;
15758
15759       case WhitePlay:
15760         SetWhiteToPlayEvent();
15761         break;
15762
15763       case BlackPlay:
15764         SetBlackToPlayEvent();
15765         break;
15766
15767       case EmptySquare:
15768         if (gameMode == IcsExamining) {
15769             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15770             snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
15771             SendToICS(buf);
15772         } else {
15773             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15774                 if(x == BOARD_LEFT-2) {
15775                     if(y < handSize-1-gameInfo.holdingsSize) break;
15776                     boards[0][y][1] = 0;
15777                 } else
15778                 if(x == BOARD_RGHT+1) {
15779                     if(y >= gameInfo.holdingsSize) break;
15780                     boards[0][y][BOARD_WIDTH-2] = 0;
15781                 } else break;
15782             }
15783             boards[0][y][x] = EmptySquare;
15784             DrawPosition(FALSE, boards[0]);
15785         }
15786         break;
15787
15788       case PromotePiece:
15789         if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
15790            piece >= (int)BlackPawn && piece < (int)BlackMan   ) {
15791             selection = (ChessSquare) (PROMOTED(piece));
15792         } else if(piece == EmptySquare) selection = WhiteSilver;
15793         else selection = (ChessSquare)((int)piece - 1);
15794         goto defaultlabel;
15795
15796       case DemotePiece:
15797         if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
15798            piece > (int)BlackMan && piece <= (int)BlackKing   ) {
15799             selection = (ChessSquare) (DEMOTED(piece));
15800         } else if(piece == EmptySquare) selection = BlackSilver;
15801         else selection = (ChessSquare)((int)piece + 1);
15802         goto defaultlabel;
15803
15804       case WhiteQueen:
15805       case BlackQueen:
15806         if(gameInfo.variant == VariantShatranj ||
15807            gameInfo.variant == VariantXiangqi  ||
15808            gameInfo.variant == VariantCourier  ||
15809            gameInfo.variant == VariantASEAN    ||
15810            gameInfo.variant == VariantMakruk     )
15811             selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
15812         goto defaultlabel;
15813
15814       case WhiteRook:
15815         baseRank = 0;
15816       case BlackRook:
15817         if(y == baseRank && (x == BOARD_LEFT || x == BOARD_RGHT-1 || appData.fischerCastling)) hasRights = 1;
15818         if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
15819         goto defaultlabel;
15820
15821       case WhiteKing:
15822         baseRank = 0;
15823       case BlackKing:
15824         if(gameInfo.variant == VariantXiangqi)
15825             selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
15826         if(gameInfo.variant == VariantKnightmate)
15827             selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
15828         if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
15829       default:
15830         defaultlabel:
15831         if (gameMode == IcsExamining) {
15832             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15833             snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
15834                      PieceToChar(selection), AAA + x, ONE + y);
15835             SendToICS(buf);
15836         } else {
15837             rightsBoard[y][x] = hasRights;
15838             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15839                 int n;
15840                 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
15841                     n = PieceToNumber(selection - BlackPawn);
15842                     if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
15843                     boards[0][handSize-1-n][0] = selection;
15844                     boards[0][handSize-1-n][1]++;
15845                 } else
15846                 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
15847                     n = PieceToNumber(selection);
15848                     if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
15849                     boards[0][n][BOARD_WIDTH-1] = selection;
15850                     boards[0][n][BOARD_WIDTH-2]++;
15851                 }
15852             } else
15853             boards[0][y][x] = selection;
15854             DrawPosition(TRUE, boards[0]);
15855             ClearHighlights();
15856             fromX = fromY = -1;
15857         }
15858         break;
15859     }
15860 }
15861
15862
15863 void
15864 DropMenuEvent (ChessSquare selection, int x, int y)
15865 {
15866     ChessMove moveType;
15867
15868     switch (gameMode) {
15869       case IcsPlayingWhite:
15870       case MachinePlaysBlack:
15871         if (!WhiteOnMove(currentMove)) {
15872             DisplayMoveError(_("It is Black's turn"));
15873             return;
15874         }
15875         moveType = WhiteDrop;
15876         break;
15877       case IcsPlayingBlack:
15878       case MachinePlaysWhite:
15879         if (WhiteOnMove(currentMove)) {
15880             DisplayMoveError(_("It is White's turn"));
15881             return;
15882         }
15883         moveType = BlackDrop;
15884         break;
15885       case EditGame:
15886         moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
15887         break;
15888       default:
15889         return;
15890     }
15891
15892     if (moveType == BlackDrop && selection < BlackPawn) {
15893       selection = (ChessSquare) ((int) selection
15894                                  + (int) BlackPawn - (int) WhitePawn);
15895     }
15896     if (boards[currentMove][y][x] != EmptySquare) {
15897         DisplayMoveError(_("That square is occupied"));
15898         return;
15899     }
15900
15901     FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
15902 }
15903
15904 void
15905 AcceptEvent ()
15906 {
15907     /* Accept a pending offer of any kind from opponent */
15908
15909     if (appData.icsActive) {
15910         SendToICS(ics_prefix);
15911         SendToICS("accept\n");
15912     } else if (cmailMsgLoaded) {
15913         if (currentMove == cmailOldMove &&
15914             commentList[cmailOldMove] != NULL &&
15915             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15916                    "Black offers a draw" : "White offers a draw")) {
15917             TruncateGame();
15918             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15919             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15920         } else {
15921             DisplayError(_("There is no pending offer on this move"), 0);
15922             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15923         }
15924     } else {
15925         /* Not used for offers from chess program */
15926     }
15927 }
15928
15929 void
15930 DeclineEvent ()
15931 {
15932     /* Decline a pending offer of any kind from opponent */
15933
15934     if (appData.icsActive) {
15935         SendToICS(ics_prefix);
15936         SendToICS("decline\n");
15937     } else if (cmailMsgLoaded) {
15938         if (currentMove == cmailOldMove &&
15939             commentList[cmailOldMove] != NULL &&
15940             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15941                    "Black offers a draw" : "White offers a draw")) {
15942 #ifdef NOTDEF
15943             AppendComment(cmailOldMove, "Draw declined", TRUE);
15944             DisplayComment(cmailOldMove - 1, "Draw declined");
15945 #endif /*NOTDEF*/
15946         } else {
15947             DisplayError(_("There is no pending offer on this move"), 0);
15948         }
15949     } else {
15950         /* Not used for offers from chess program */
15951     }
15952 }
15953
15954 void
15955 RematchEvent ()
15956 {
15957     /* Issue ICS rematch command */
15958     if (appData.icsActive) {
15959         SendToICS(ics_prefix);
15960         SendToICS("rematch\n");
15961     }
15962 }
15963
15964 void
15965 CallFlagEvent ()
15966 {
15967     /* Call your opponent's flag (claim a win on time) */
15968     if (appData.icsActive) {
15969         SendToICS(ics_prefix);
15970         SendToICS("flag\n");
15971     } else {
15972         switch (gameMode) {
15973           default:
15974             return;
15975           case MachinePlaysWhite:
15976             if (whiteFlag) {
15977                 if (blackFlag)
15978                   GameEnds(GameIsDrawn, "Both players ran out of time",
15979                            GE_PLAYER);
15980                 else
15981                   GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
15982             } else {
15983                 DisplayError(_("Your opponent is not out of time"), 0);
15984             }
15985             break;
15986           case MachinePlaysBlack:
15987             if (blackFlag) {
15988                 if (whiteFlag)
15989                   GameEnds(GameIsDrawn, "Both players ran out of time",
15990                            GE_PLAYER);
15991                 else
15992                   GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
15993             } else {
15994                 DisplayError(_("Your opponent is not out of time"), 0);
15995             }
15996             break;
15997         }
15998     }
15999 }
16000
16001 void
16002 ClockClick (int which)
16003 {       // [HGM] code moved to back-end from winboard.c
16004         if(which) { // black clock
16005           if (gameMode == EditPosition || gameMode == IcsExamining) {
16006             if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
16007             SetBlackToPlayEvent();
16008           } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
16009                       gameMode == MachinePlaysBlack && PosFlags(0) & F_NULL_MOVE && !blackFlag && !shiftKey) && WhiteOnMove(currentMove)) {
16010           UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
16011           } else if (shiftKey) {
16012             AdjustClock(which, -1);
16013           } else if (gameMode == IcsPlayingWhite ||
16014                      gameMode == MachinePlaysBlack) {
16015             CallFlagEvent();
16016           }
16017         } else { // white clock
16018           if (gameMode == EditPosition || gameMode == IcsExamining) {
16019             if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
16020             SetWhiteToPlayEvent();
16021           } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
16022                       gameMode == MachinePlaysWhite && PosFlags(0) & F_NULL_MOVE && !whiteFlag && !shiftKey) && !WhiteOnMove(currentMove)) {
16023           UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
16024           } else if (shiftKey) {
16025             AdjustClock(which, -1);
16026           } else if (gameMode == IcsPlayingBlack ||
16027                    gameMode == MachinePlaysWhite) {
16028             CallFlagEvent();
16029           }
16030         }
16031 }
16032
16033 void
16034 DrawEvent ()
16035 {
16036     /* Offer draw or accept pending draw offer from opponent */
16037
16038     if (appData.icsActive) {
16039         /* Note: tournament rules require draw offers to be
16040            made after you make your move but before you punch
16041            your clock.  Currently ICS doesn't let you do that;
16042            instead, you immediately punch your clock after making
16043            a move, but you can offer a draw at any time. */
16044
16045         SendToICS(ics_prefix);
16046         SendToICS("draw\n");
16047         userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
16048     } else if (cmailMsgLoaded) {
16049         if (currentMove == cmailOldMove &&
16050             commentList[cmailOldMove] != NULL &&
16051             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
16052                    "Black offers a draw" : "White offers a draw")) {
16053             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
16054             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
16055         } else if (currentMove == cmailOldMove + 1) {
16056             char *offer = WhiteOnMove(cmailOldMove) ?
16057               "White offers a draw" : "Black offers a draw";
16058             AppendComment(currentMove, offer, TRUE);
16059             DisplayComment(currentMove - 1, offer);
16060             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
16061         } else {
16062             DisplayError(_("You must make your move before offering a draw"), 0);
16063             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
16064         }
16065     } else if (first.offeredDraw) {
16066         GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
16067     } else {
16068         if (first.sendDrawOffers) {
16069             SendToProgram("draw\n", &first);
16070             userOfferedDraw = TRUE;
16071         }
16072     }
16073 }
16074
16075 void
16076 AdjournEvent ()
16077 {
16078     /* Offer Adjourn or accept pending Adjourn offer from opponent */
16079
16080     if (appData.icsActive) {
16081         SendToICS(ics_prefix);
16082         SendToICS("adjourn\n");
16083     } else {
16084         /* Currently GNU Chess doesn't offer or accept Adjourns */
16085     }
16086 }
16087
16088
16089 void
16090 AbortEvent ()
16091 {
16092     /* Offer Abort or accept pending Abort offer from opponent */
16093
16094     if (appData.icsActive) {
16095         SendToICS(ics_prefix);
16096         SendToICS("abort\n");
16097     } else {
16098         GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
16099     }
16100 }
16101
16102 void
16103 ResignEvent ()
16104 {
16105     /* Resign.  You can do this even if it's not your turn. */
16106
16107     if (appData.icsActive) {
16108         SendToICS(ics_prefix);
16109         SendToICS("resign\n");
16110     } else {
16111         switch (gameMode) {
16112           case MachinePlaysWhite:
16113             GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
16114             break;
16115           case MachinePlaysBlack:
16116             GameEnds(BlackWins, "White resigns", GE_PLAYER);
16117             break;
16118           case EditGame:
16119             if (cmailMsgLoaded) {
16120                 TruncateGame();
16121                 if (WhiteOnMove(cmailOldMove)) {
16122                     GameEnds(BlackWins, "White resigns", GE_PLAYER);
16123                 } else {
16124                     GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
16125                 }
16126                 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
16127             }
16128             break;
16129           default:
16130             break;
16131         }
16132     }
16133 }
16134
16135
16136 void
16137 StopObservingEvent ()
16138 {
16139     /* Stop observing current games */
16140     SendToICS(ics_prefix);
16141     SendToICS("unobserve\n");
16142 }
16143
16144 void
16145 StopExaminingEvent ()
16146 {
16147     /* Stop observing current game */
16148     SendToICS(ics_prefix);
16149     SendToICS("unexamine\n");
16150 }
16151
16152 void
16153 ForwardInner (int target)
16154 {
16155     int limit; int oldSeekGraphUp = seekGraphUp;
16156
16157     if (appData.debugMode)
16158         fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
16159                 target, currentMove, forwardMostMove);
16160
16161     if (gameMode == EditPosition)
16162       return;
16163
16164     seekGraphUp = FALSE;
16165     MarkTargetSquares(1);
16166     fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
16167
16168     if (gameMode == PlayFromGameFile && !pausing)
16169       PauseEvent();
16170
16171     if (gameMode == IcsExamining && pausing)
16172       limit = pauseExamForwardMostMove;
16173     else
16174       limit = forwardMostMove;
16175
16176     if (target > limit) target = limit;
16177
16178     if (target > 0 && moveList[target - 1][0]) {
16179         int fromX, fromY, toX, toY;
16180         toX = moveList[target - 1][2] - AAA;
16181         toY = moveList[target - 1][3] - ONE;
16182         if (moveList[target - 1][1] == '@') {
16183             if (appData.highlightLastMove) {
16184                 SetHighlights(-1, -1, toX, toY);
16185             }
16186         } else {
16187             fromX = moveList[target - 1][0] - AAA;
16188             fromY = moveList[target - 1][1] - ONE;
16189             if (target == currentMove + 1) {
16190                 if(moveList[target - 1][4] == ';') { // multi-leg
16191                     killX = moveList[target - 1][5] - AAA;
16192                     killY = moveList[target - 1][6] - ONE;
16193                 }
16194                 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
16195                 killX = killY = -1;
16196             }
16197             if (appData.highlightLastMove) {
16198                 SetHighlights(fromX, fromY, toX, toY);
16199             }
16200         }
16201     }
16202     if (gameMode == EditGame || gameMode == AnalyzeMode ||
16203         gameMode == Training || gameMode == PlayFromGameFile ||
16204         gameMode == AnalyzeFile) {
16205         while (currentMove < target) {
16206             if(second.analyzing) SendMoveToProgram(currentMove, &second);
16207             SendMoveToProgram(currentMove++, &first);
16208         }
16209     } else {
16210         currentMove = target;
16211     }
16212
16213     if (gameMode == EditGame || gameMode == EndOfGame) {
16214         whiteTimeRemaining = timeRemaining[0][currentMove];
16215         blackTimeRemaining = timeRemaining[1][currentMove];
16216     }
16217     DisplayBothClocks();
16218     DisplayMove(currentMove - 1);
16219     DrawPosition(oldSeekGraphUp, boards[currentMove]);
16220     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
16221     if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
16222         DisplayComment(currentMove - 1, commentList[currentMove]);
16223     }
16224     ClearMap(); // [HGM] exclude: invalidate map
16225 }
16226
16227
16228 void
16229 ForwardEvent ()
16230 {
16231     if (gameMode == IcsExamining && !pausing) {
16232         SendToICS(ics_prefix);
16233         SendToICS("forward\n");
16234     } else {
16235         ForwardInner(currentMove + 1);
16236     }
16237 }
16238
16239 void
16240 ToEndEvent ()
16241 {
16242     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16243         /* to optimze, we temporarily turn off analysis mode while we feed
16244          * the remaining moves to the engine. Otherwise we get analysis output
16245          * after each move.
16246          */
16247         if (first.analysisSupport) {
16248           SendToProgram("exit\nforce\n", &first);
16249           first.analyzing = FALSE;
16250         }
16251     }
16252
16253     if (gameMode == IcsExamining && !pausing) {
16254         SendToICS(ics_prefix);
16255         SendToICS("forward 999999\n");
16256     } else {
16257         ForwardInner(forwardMostMove);
16258     }
16259
16260     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16261         /* we have fed all the moves, so reactivate analysis mode */
16262         SendToProgram("analyze\n", &first);
16263         first.analyzing = TRUE;
16264         /*first.maybeThinking = TRUE;*/
16265         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
16266     }
16267 }
16268
16269 void
16270 BackwardInner (int target)
16271 {
16272     int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
16273
16274     if (appData.debugMode)
16275         fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
16276                 target, currentMove, forwardMostMove);
16277
16278     if (gameMode == EditPosition) return;
16279     seekGraphUp = FALSE;
16280     MarkTargetSquares(1);
16281     fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
16282     if (currentMove <= backwardMostMove) {
16283         ClearHighlights();
16284         DrawPosition(full_redraw, boards[currentMove]);
16285         return;
16286     }
16287     if (gameMode == PlayFromGameFile && !pausing)
16288       PauseEvent();
16289
16290     if (moveList[target][0]) {
16291         int fromX, fromY, toX, toY;
16292         toX = moveList[target][2] - AAA;
16293         toY = moveList[target][3] - ONE;
16294         if (moveList[target][1] == '@') {
16295             if (appData.highlightLastMove) {
16296                 SetHighlights(-1, -1, toX, toY);
16297             }
16298         } else {
16299             fromX = moveList[target][0] - AAA;
16300             fromY = moveList[target][1] - ONE;
16301             if (target == currentMove - 1) {
16302                 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
16303             }
16304             if (appData.highlightLastMove) {
16305                 SetHighlights(fromX, fromY, toX, toY);
16306             }
16307         }
16308     }
16309     if (gameMode == EditGame || gameMode==AnalyzeMode ||
16310         gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
16311         while (currentMove > target) {
16312             if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
16313                 // null move cannot be undone. Reload program with move history before it.
16314                 int i;
16315                 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
16316                     if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
16317                 }
16318                 SendBoard(&first, i);
16319               if(second.analyzing) SendBoard(&second, i);
16320                 for(currentMove=i; currentMove<target; currentMove++) {
16321                     SendMoveToProgram(currentMove, &first);
16322                     if(second.analyzing) SendMoveToProgram(currentMove, &second);
16323                 }
16324                 break;
16325             }
16326             SendToBoth("undo\n");
16327             currentMove--;
16328         }
16329     } else {
16330         currentMove = target;
16331     }
16332
16333     if (gameMode == EditGame || gameMode == EndOfGame) {
16334         whiteTimeRemaining = timeRemaining[0][currentMove];
16335         blackTimeRemaining = timeRemaining[1][currentMove];
16336     }
16337     DisplayBothClocks();
16338     DisplayMove(currentMove - 1);
16339     DrawPosition(full_redraw, boards[currentMove]);
16340     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
16341     // [HGM] PV info: routine tests if comment empty
16342     DisplayComment(currentMove - 1, commentList[currentMove]);
16343     ClearMap(); // [HGM] exclude: invalidate map
16344 }
16345
16346 void
16347 BackwardEvent ()
16348 {
16349     if (gameMode == IcsExamining && !pausing) {
16350         SendToICS(ics_prefix);
16351         SendToICS("backward\n");
16352     } else {
16353         BackwardInner(currentMove - 1);
16354     }
16355 }
16356
16357 void
16358 ToStartEvent ()
16359 {
16360     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16361         /* to optimize, we temporarily turn off analysis mode while we undo
16362          * all the moves. Otherwise we get analysis output after each undo.
16363          */
16364         if (first.analysisSupport) {
16365           SendToProgram("exit\nforce\n", &first);
16366           first.analyzing = FALSE;
16367         }
16368     }
16369
16370     if (gameMode == IcsExamining && !pausing) {
16371         SendToICS(ics_prefix);
16372         SendToICS("backward 999999\n");
16373     } else {
16374         BackwardInner(backwardMostMove);
16375     }
16376
16377     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16378         /* we have fed all the moves, so reactivate analysis mode */
16379         SendToProgram("analyze\n", &first);
16380         first.analyzing = TRUE;
16381         /*first.maybeThinking = TRUE;*/
16382         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
16383     }
16384 }
16385
16386 void
16387 ToNrEvent (int to)
16388 {
16389   if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
16390   if (to >= forwardMostMove) to = forwardMostMove;
16391   if (to <= backwardMostMove) to = backwardMostMove;
16392   if (to < currentMove) {
16393     BackwardInner(to);
16394   } else {
16395     ForwardInner(to);
16396   }
16397 }
16398
16399 void
16400 RevertEvent (Boolean annotate)
16401 {
16402     if(PopTail(annotate)) { // [HGM] vari: restore old game tail
16403         return;
16404     }
16405     if (gameMode != IcsExamining) {
16406         DisplayError(_("You are not examining a game"), 0);
16407         return;
16408     }
16409     if (pausing) {
16410         DisplayError(_("You can't revert while pausing"), 0);
16411         return;
16412     }
16413     SendToICS(ics_prefix);
16414     SendToICS("revert\n");
16415 }
16416
16417 void
16418 RetractMoveEvent ()
16419 {
16420     switch (gameMode) {
16421       case MachinePlaysWhite:
16422       case MachinePlaysBlack:
16423         if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
16424             DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
16425             return;
16426         }
16427         if (forwardMostMove < 2) return;
16428         currentMove = forwardMostMove = forwardMostMove - 2;
16429         whiteTimeRemaining = timeRemaining[0][currentMove];
16430         blackTimeRemaining = timeRemaining[1][currentMove];
16431         DisplayBothClocks();
16432         DisplayMove(currentMove - 1);
16433         ClearHighlights();/*!! could figure this out*/
16434         DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
16435         SendToProgram("remove\n", &first);
16436         /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
16437         break;
16438
16439       case BeginningOfGame:
16440       default:
16441         break;
16442
16443       case IcsPlayingWhite:
16444       case IcsPlayingBlack:
16445         if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
16446             SendToICS(ics_prefix);
16447             SendToICS("takeback 2\n");
16448         } else {
16449             SendToICS(ics_prefix);
16450             SendToICS("takeback 1\n");
16451         }
16452         break;
16453     }
16454 }
16455
16456 void
16457 MoveNowEvent ()
16458 {
16459     ChessProgramState *cps;
16460
16461     switch (gameMode) {
16462       case MachinePlaysWhite:
16463         if (!WhiteOnMove(forwardMostMove)) {
16464             DisplayError(_("It is your turn"), 0);
16465             return;
16466         }
16467         cps = &first;
16468         break;
16469       case MachinePlaysBlack:
16470         if (WhiteOnMove(forwardMostMove)) {
16471             DisplayError(_("It is your turn"), 0);
16472             return;
16473         }
16474         cps = &first;
16475         break;
16476       case TwoMachinesPlay:
16477         if (WhiteOnMove(forwardMostMove) ==
16478             (first.twoMachinesColor[0] == 'w')) {
16479             cps = &first;
16480         } else {
16481             cps = &second;
16482         }
16483         break;
16484       case BeginningOfGame:
16485       default:
16486         return;
16487     }
16488     SendToProgram("?\n", cps);
16489 }
16490
16491 void
16492 TruncateGameEvent ()
16493 {
16494     EditGameEvent();
16495     if (gameMode != EditGame) return;
16496     TruncateGame();
16497 }
16498
16499 void
16500 TruncateGame ()
16501 {
16502     CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
16503     if (forwardMostMove > currentMove) {
16504         if (gameInfo.resultDetails != NULL) {
16505             free(gameInfo.resultDetails);
16506             gameInfo.resultDetails = NULL;
16507             gameInfo.result = GameUnfinished;
16508         }
16509         forwardMostMove = currentMove;
16510         HistorySet(parseList, backwardMostMove, forwardMostMove,
16511                    currentMove-1);
16512     }
16513 }
16514
16515 void
16516 HintEvent ()
16517 {
16518     if (appData.noChessProgram) return;
16519     switch (gameMode) {
16520       case MachinePlaysWhite:
16521         if (WhiteOnMove(forwardMostMove)) {
16522             DisplayError(_("Wait until your turn."), 0);
16523             return;
16524         }
16525         break;
16526       case BeginningOfGame:
16527       case MachinePlaysBlack:
16528         if (!WhiteOnMove(forwardMostMove)) {
16529             DisplayError(_("Wait until your turn."), 0);
16530             return;
16531         }
16532         break;
16533       default:
16534         DisplayError(_("No hint available"), 0);
16535         return;
16536     }
16537     SendToProgram("hint\n", &first);
16538     hintRequested = TRUE;
16539 }
16540
16541 int
16542 SaveSelected (FILE *g, int dummy, char *dummy2)
16543 {
16544     ListGame * lg = (ListGame *) gameList.head;
16545     int nItem, cnt=0;
16546     FILE *f;
16547
16548     if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
16549         DisplayError(_("Game list not loaded or empty"), 0);
16550         return 0;
16551     }
16552
16553     creatingBook = TRUE; // suppresses stuff during load game
16554
16555     /* Get list size */
16556     for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16557         if(lg->position >= 0) { // selected?
16558             LoadGame(f, nItem, "", TRUE);
16559             SaveGamePGN2(g); // leaves g open
16560             cnt++; DoEvents();
16561         }
16562         lg = (ListGame *) lg->node.succ;
16563     }
16564
16565     fclose(g);
16566     creatingBook = FALSE;
16567
16568     return cnt;
16569 }
16570
16571 void
16572 CreateBookEvent ()
16573 {
16574     ListGame * lg = (ListGame *) gameList.head;
16575     FILE *f, *g;
16576     int nItem;
16577     static int secondTime = FALSE;
16578
16579     if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
16580         DisplayError(_("Game list not loaded or empty"), 0);
16581         return;
16582     }
16583
16584     if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
16585         fclose(g);
16586         secondTime++;
16587         DisplayNote(_("Book file exists! Try again for overwrite."));
16588         return;
16589     }
16590
16591     creatingBook = TRUE;
16592     secondTime = FALSE;
16593
16594     /* Get list size */
16595     for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16596         if(lg->position >= 0) {
16597             LoadGame(f, nItem, "", TRUE);
16598             AddGameToBook(TRUE);
16599             DoEvents();
16600         }
16601         lg = (ListGame *) lg->node.succ;
16602     }
16603
16604     creatingBook = FALSE;
16605     FlushBook();
16606 }
16607
16608 void
16609 BookEvent ()
16610 {
16611     if (appData.noChessProgram) return;
16612     switch (gameMode) {
16613       case MachinePlaysWhite:
16614         if (WhiteOnMove(forwardMostMove)) {
16615             DisplayError(_("Wait until your turn."), 0);
16616             return;
16617         }
16618         break;
16619       case BeginningOfGame:
16620       case MachinePlaysBlack:
16621         if (!WhiteOnMove(forwardMostMove)) {
16622             DisplayError(_("Wait until your turn."), 0);
16623             return;
16624         }
16625         break;
16626       case EditPosition:
16627         EditPositionDone(TRUE);
16628         break;
16629       case TwoMachinesPlay:
16630         return;
16631       default:
16632         break;
16633     }
16634     SendToProgram("bk\n", &first);
16635     bookOutput[0] = NULLCHAR;
16636     bookRequested = TRUE;
16637 }
16638
16639 void
16640 AboutGameEvent ()
16641 {
16642     char *tags = PGNTags(&gameInfo);
16643     TagsPopUp(tags, CmailMsg());
16644     free(tags);
16645 }
16646
16647 /* end button procedures */
16648
16649 void
16650 PrintPosition (FILE *fp, int move)
16651 {
16652     int i, j;
16653
16654     for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16655         for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16656             char c = PieceToChar(boards[move][i][j]);
16657             fputc(c == '?' ? '.' : c, fp);
16658             fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
16659         }
16660     }
16661     if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
16662       fprintf(fp, "white to play\n");
16663     else
16664       fprintf(fp, "black to play\n");
16665 }
16666
16667 void
16668 PrintOpponents (FILE *fp)
16669 {
16670     if (gameInfo.white != NULL) {
16671         fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
16672     } else {
16673         fprintf(fp, "\n");
16674     }
16675 }
16676
16677 /* Find last component of program's own name, using some heuristics */
16678 void
16679 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
16680 {
16681     char *p, *q, c;
16682     int local = (strcmp(host, "localhost") == 0);
16683     while (!local && (p = strchr(prog, ';')) != NULL) {
16684         p++;
16685         while (*p == ' ') p++;
16686         prog = p;
16687     }
16688     if (*prog == '"' || *prog == '\'') {
16689         q = strchr(prog + 1, *prog);
16690     } else {
16691         q = strchr(prog, ' ');
16692     }
16693     if (q == NULL) q = prog + strlen(prog);
16694     p = q;
16695     while (p >= prog && *p != '/' && *p != '\\') p--;
16696     p++;
16697     if(p == prog && *p == '"') p++;
16698     c = *q; *q = 0;
16699     if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
16700     memcpy(buf, p, q - p);
16701     buf[q - p] = NULLCHAR;
16702     if (!local) {
16703         strcat(buf, "@");
16704         strcat(buf, host);
16705     }
16706 }
16707
16708 char *
16709 TimeControlTagValue ()
16710 {
16711     char buf[MSG_SIZ];
16712     if (!appData.clockMode) {
16713       safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
16714     } else if (movesPerSession > 0) {
16715       snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
16716     } else if (timeIncrement == 0) {
16717       snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
16718     } else {
16719       snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
16720     }
16721     return StrSave(buf);
16722 }
16723
16724 void
16725 SetGameInfo ()
16726 {
16727     /* This routine is used only for certain modes */
16728     VariantClass v = gameInfo.variant;
16729     ChessMove r = GameUnfinished;
16730     char *p = NULL;
16731
16732     if(keepInfo) return;
16733
16734     if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
16735         r = gameInfo.result;
16736         p = gameInfo.resultDetails;
16737         gameInfo.resultDetails = NULL;
16738     }
16739     ClearGameInfo(&gameInfo);
16740     gameInfo.variant = v;
16741
16742     switch (gameMode) {
16743       case MachinePlaysWhite:
16744         gameInfo.event = StrSave( appData.pgnEventHeader );
16745         gameInfo.site = StrSave(HostName());
16746         gameInfo.date = PGNDate();
16747         gameInfo.round = StrSave("-");
16748         gameInfo.white = StrSave(first.tidy);
16749         gameInfo.black = StrSave(UserName());
16750         gameInfo.timeControl = TimeControlTagValue();
16751         break;
16752
16753       case MachinePlaysBlack:
16754         gameInfo.event = StrSave( appData.pgnEventHeader );
16755         gameInfo.site = StrSave(HostName());
16756         gameInfo.date = PGNDate();
16757         gameInfo.round = StrSave("-");
16758         gameInfo.white = StrSave(UserName());
16759         gameInfo.black = StrSave(first.tidy);
16760         gameInfo.timeControl = TimeControlTagValue();
16761         break;
16762
16763       case TwoMachinesPlay:
16764         gameInfo.event = StrSave( appData.pgnEventHeader );
16765         gameInfo.site = StrSave(HostName());
16766         gameInfo.date = PGNDate();
16767         if (roundNr > 0) {
16768             char buf[MSG_SIZ];
16769             snprintf(buf, MSG_SIZ, "%d", roundNr);
16770             gameInfo.round = StrSave(buf);
16771         } else {
16772             gameInfo.round = StrSave("-");
16773         }
16774         if (first.twoMachinesColor[0] == 'w') {
16775             gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16776             gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16777         } else {
16778             gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16779             gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16780         }
16781         gameInfo.timeControl = TimeControlTagValue();
16782         break;
16783
16784       case EditGame:
16785         gameInfo.event = StrSave("Edited game");
16786         gameInfo.site = StrSave(HostName());
16787         gameInfo.date = PGNDate();
16788         gameInfo.round = StrSave("-");
16789         gameInfo.white = StrSave("-");
16790         gameInfo.black = StrSave("-");
16791         gameInfo.result = r;
16792         gameInfo.resultDetails = p;
16793         break;
16794
16795       case EditPosition:
16796         gameInfo.event = StrSave("Edited position");
16797         gameInfo.site = StrSave(HostName());
16798         gameInfo.date = PGNDate();
16799         gameInfo.round = StrSave("-");
16800         gameInfo.white = StrSave("-");
16801         gameInfo.black = StrSave("-");
16802         break;
16803
16804       case IcsPlayingWhite:
16805       case IcsPlayingBlack:
16806       case IcsObserving:
16807       case IcsExamining:
16808         break;
16809
16810       case PlayFromGameFile:
16811         gameInfo.event = StrSave("Game from non-PGN file");
16812         gameInfo.site = StrSave(HostName());
16813         gameInfo.date = PGNDate();
16814         gameInfo.round = StrSave("-");
16815         gameInfo.white = StrSave("?");
16816         gameInfo.black = StrSave("?");
16817         break;
16818
16819       default:
16820         break;
16821     }
16822 }
16823
16824 void
16825 ReplaceComment (int index, char *text)
16826 {
16827     int len;
16828     char *p;
16829     float score;
16830
16831     if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
16832        pvInfoList[index-1].depth == len &&
16833        fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
16834        (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
16835     while (*text == '\n') text++;
16836     len = strlen(text);
16837     while (len > 0 && text[len - 1] == '\n') len--;
16838
16839     if (commentList[index] != NULL)
16840       free(commentList[index]);
16841
16842     if (len == 0) {
16843         commentList[index] = NULL;
16844         return;
16845     }
16846   if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
16847       *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
16848       *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
16849     commentList[index] = (char *) malloc(len + 2);
16850     strncpy(commentList[index], text, len);
16851     commentList[index][len] = '\n';
16852     commentList[index][len + 1] = NULLCHAR;
16853   } else {
16854     // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
16855     char *p;
16856     commentList[index] = (char *) malloc(len + 7);
16857     safeStrCpy(commentList[index], "{\n", 3);
16858     safeStrCpy(commentList[index]+2, text, len+1);
16859     commentList[index][len+2] = NULLCHAR;
16860     while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
16861     strcat(commentList[index], "\n}\n");
16862   }
16863 }
16864
16865 void
16866 CrushCRs (char *text)
16867 {
16868   char *p = text;
16869   char *q = text;
16870   char ch;
16871
16872   do {
16873     ch = *p++;
16874     if (ch == '\r') continue;
16875     *q++ = ch;
16876   } while (ch != '\0');
16877 }
16878
16879 void
16880 AppendComment (int index, char *text, Boolean addBraces)
16881 /* addBraces  tells if we should add {} */
16882 {
16883     int oldlen, len;
16884     char *old;
16885
16886 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
16887     if(addBraces == 3) addBraces = 0; else // force appending literally
16888     text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
16889
16890     CrushCRs(text);
16891     while (*text == '\n') text++;
16892     len = strlen(text);
16893     while (len > 0 && text[len - 1] == '\n') len--;
16894     text[len] = NULLCHAR;
16895
16896     if (len == 0) return;
16897
16898     if (commentList[index] != NULL) {
16899       Boolean addClosingBrace = addBraces;
16900         old = commentList[index];
16901         oldlen = strlen(old);
16902         while(commentList[index][oldlen-1] ==  '\n')
16903           commentList[index][--oldlen] = NULLCHAR;
16904         commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
16905         safeStrCpy(commentList[index], old, oldlen + len + 6);
16906         free(old);
16907         // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
16908         if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
16909           if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
16910           while (*text == '\n') { text++; len--; }
16911           commentList[index][--oldlen] = NULLCHAR;
16912       }
16913         if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
16914         else          strcat(commentList[index], "\n");
16915         strcat(commentList[index], text);
16916         if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
16917         else          strcat(commentList[index], "\n");
16918     } else {
16919         commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
16920         if(addBraces)
16921           safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
16922         else commentList[index][0] = NULLCHAR;
16923         strcat(commentList[index], text);
16924         strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
16925         if(addBraces == TRUE) strcat(commentList[index], "}\n");
16926     }
16927 }
16928
16929 static char *
16930 FindStr (char * text, char * sub_text)
16931 {
16932     char * result = strstr( text, sub_text );
16933
16934     if( result != NULL ) {
16935         result += strlen( sub_text );
16936     }
16937
16938     return result;
16939 }
16940
16941 /* [AS] Try to extract PV info from PGN comment */
16942 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
16943 char *
16944 GetInfoFromComment (int index, char * text)
16945 {
16946     char * sep = text, *p;
16947
16948     if( text != NULL && index > 0 ) {
16949         int score = 0;
16950         int depth = 0;
16951         int time = -1, sec = 0, deci;
16952         char * s_eval = FindStr( text, "[%eval " );
16953         char * s_emt = FindStr( text, "[%emt " );
16954 #if 0
16955         if( s_eval != NULL || s_emt != NULL ) {
16956 #else
16957         if(0) { // [HGM] this code is not finished, and could actually be detrimental
16958 #endif
16959             /* New style */
16960             char delim;
16961
16962             if( s_eval != NULL ) {
16963                 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
16964                     return text;
16965                 }
16966
16967                 if( delim != ']' ) {
16968                     return text;
16969                 }
16970             }
16971
16972             if( s_emt != NULL ) {
16973             }
16974                 return text;
16975         }
16976         else {
16977             /* We expect something like: [+|-]nnn.nn/dd */
16978             int score_lo = 0;
16979
16980             if(*text != '{') return text; // [HGM] braces: must be normal comment
16981
16982             sep = strchr( text, '/' );
16983             if( sep == NULL || sep < (text+4) ) {
16984                 return text;
16985             }
16986
16987             p = text;
16988             if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
16989             if(p[1] == '(') { // comment starts with PV
16990                p = strchr(p, ')'); // locate end of PV
16991                if(p == NULL || sep < p+5) return text;
16992                // at this point we have something like "{(.*) +0.23/6 ..."
16993                p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
16994                *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
16995                // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
16996             }
16997             time = -1; sec = -1; deci = -1;
16998             if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
16999                 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
17000                 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
17001                 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3   ) {
17002                 return text;
17003             }
17004
17005             if( score_lo < 0 || score_lo >= 100 ) {
17006                 return text;
17007             }
17008
17009             if(sec >= 0) time = 600*time + 10*sec; else
17010             if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
17011
17012             score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
17013
17014             /* [HGM] PV time: now locate end of PV info */
17015             while( *++sep >= '0' && *sep <= '9'); // strip depth
17016             if(time >= 0)
17017             while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
17018             if(sec >= 0)
17019             while( *++sep >= '0' && *sep <= '9'); // strip seconds
17020             if(deci >= 0)
17021             while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
17022             while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
17023         }
17024
17025         if( depth <= 0 ) {
17026             return text;
17027         }
17028
17029         if( time < 0 ) {
17030             time = -1;
17031         }
17032
17033         pvInfoList[index-1].depth = depth;
17034         pvInfoList[index-1].score = score;
17035         pvInfoList[index-1].time  = 10*time; // centi-sec
17036         if(*sep == '}') *sep = 0; else *--sep = '{';
17037         if(p != text) {
17038             while(*p++ = *sep++)
17039                                 ;
17040             sep = text;
17041         } // squeeze out space between PV and comment, and return both
17042     }
17043     return sep;
17044 }
17045
17046 void
17047 SendToProgram (char *message, ChessProgramState *cps)
17048 {
17049     int count, outCount, error;
17050     char buf[MSG_SIZ];
17051
17052     if (cps->pr == NoProc) return;
17053     Attention(cps);
17054
17055     if (appData.debugMode) {
17056         TimeMark now;
17057         GetTimeMark(&now);
17058         fprintf(debugFP, "%ld >%-6s: %s",
17059                 SubtractTimeMarks(&now, &programStartTime),
17060                 cps->which, message);
17061         if(serverFP)
17062             fprintf(serverFP, "%ld >%-6s: %s",
17063                 SubtractTimeMarks(&now, &programStartTime),
17064                 cps->which, message), fflush(serverFP);
17065     }
17066
17067     count = strlen(message);
17068     outCount = OutputToProcess(cps->pr, message, count, &error);
17069     if (outCount < count && !exiting
17070                          && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
17071       if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
17072       snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
17073         if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
17074             if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
17075                 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
17076                 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
17077                 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
17078             } else {
17079                 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
17080                 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
17081                 gameInfo.result = res;
17082             }
17083             gameInfo.resultDetails = StrSave(buf);
17084         }
17085         if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
17086         if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
17087     }
17088 }
17089
17090 void
17091 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
17092 {
17093     char *end_str;
17094     char buf[MSG_SIZ];
17095     ChessProgramState *cps = (ChessProgramState *)closure;
17096
17097     if (isr != cps->isr) return; /* Killed intentionally */
17098     if (count <= 0) {
17099         if (count == 0) {
17100             RemoveInputSource(cps->isr);
17101             snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
17102                     _(cps->which), cps->program);
17103             if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
17104             if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
17105                 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
17106                     snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
17107                     if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
17108                     gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
17109                 } else {
17110                     ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
17111                     if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
17112                     gameInfo.result = res;
17113                 }
17114                 gameInfo.resultDetails = StrSave(buf);
17115             }
17116             if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
17117             if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
17118         } else {
17119             snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
17120                     _(cps->which), cps->program);
17121             RemoveInputSource(cps->isr);
17122
17123             /* [AS] Program is misbehaving badly... kill it */
17124             if( count == -2 ) {
17125                 DestroyChildProcess( cps->pr, 9 );
17126                 cps->pr = NoProc;
17127             }
17128
17129             if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
17130         }
17131         return;
17132     }
17133
17134     if ((end_str = strchr(message, '\r')) != NULL)
17135       *end_str = NULLCHAR;
17136     if ((end_str = strchr(message, '\n')) != NULL)
17137       *end_str = NULLCHAR;
17138
17139     if (appData.debugMode) {
17140         TimeMark now; int print = 1;
17141         char *quote = ""; char c; int i;
17142
17143         if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
17144                 char start = message[0];
17145                 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
17146                 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
17147                    sscanf(message, "move %c", &c)!=1  && sscanf(message, "offer%c", &c)!=1 &&
17148                    sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
17149                    sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
17150                    sscanf(message, "tell%c", &c)!=1   && sscanf(message, "0-1 %c", &c)!=1 &&
17151                    sscanf(message, "1-0 %c", &c)!=1   && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
17152                    sscanf(message, "setboard %c", &c)!=1   && sscanf(message, "setup %c", &c)!=1 &&
17153                    sscanf(message, "hint: %c", &c)!=1 &&
17154                    sscanf(message, "pong %c", &c)!=1   && start != '#') {
17155                     quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
17156                     print = (appData.engineComments >= 2);
17157                 }
17158                 message[0] = start; // restore original message
17159         }
17160         if(print) {
17161                 GetTimeMark(&now);
17162                 fprintf(debugFP, "%ld <%-6s: %s%s\n",
17163                         SubtractTimeMarks(&now, &programStartTime), cps->which,
17164                         quote,
17165                         message);
17166                 if(serverFP)
17167                     fprintf(serverFP, "%ld <%-6s: %s%s\n",
17168                         SubtractTimeMarks(&now, &programStartTime), cps->which,
17169                         quote,
17170                         message), fflush(serverFP);
17171         }
17172     }
17173
17174     /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
17175     if (appData.icsEngineAnalyze) {
17176         if (strstr(message, "whisper") != NULL ||
17177              strstr(message, "kibitz") != NULL ||
17178             strstr(message, "tellics") != NULL) return;
17179     }
17180
17181     HandleMachineMove(message, cps);
17182 }
17183
17184
17185 void
17186 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
17187 {
17188     char buf[MSG_SIZ];
17189     int seconds;
17190
17191     if( timeControl_2 > 0 ) {
17192         if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
17193             tc = timeControl_2;
17194         }
17195     }
17196     tc  /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
17197     inc /= cps->timeOdds;
17198     st  /= cps->timeOdds;
17199
17200     seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
17201
17202     if (st > 0) {
17203       /* Set exact time per move, normally using st command */
17204       if (cps->stKludge) {
17205         /* GNU Chess 4 has no st command; uses level in a nonstandard way */
17206         seconds = st % 60;
17207         if (seconds == 0) {
17208           snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
17209         } else {
17210           snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
17211         }
17212       } else {
17213         snprintf(buf, MSG_SIZ, "st %d\n", st);
17214       }
17215     } else {
17216       /* Set conventional or incremental time control, using level command */
17217       if (seconds == 0) {
17218         /* Note old gnuchess bug -- minutes:seconds used to not work.
17219            Fixed in later versions, but still avoid :seconds
17220            when seconds is 0. */
17221         snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
17222       } else {
17223         snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
17224                  seconds, inc/1000.);
17225       }
17226     }
17227     SendToProgram(buf, cps);
17228
17229     /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
17230     /* Orthogonally, limit search to given depth */
17231     if (sd > 0) {
17232       if (cps->sdKludge) {
17233         snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
17234       } else {
17235         snprintf(buf, MSG_SIZ, "sd %d\n", sd);
17236       }
17237       SendToProgram(buf, cps);
17238     }
17239
17240     if(cps->nps >= 0) { /* [HGM] nps */
17241         if(cps->supportsNPS == FALSE)
17242           cps->nps = -1; // don't use if engine explicitly says not supported!
17243         else {
17244           snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
17245           SendToProgram(buf, cps);
17246         }
17247     }
17248 }
17249
17250 ChessProgramState *
17251 WhitePlayer ()
17252 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
17253 {
17254     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
17255        gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
17256         return &second;
17257     return &first;
17258 }
17259
17260 void
17261 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
17262 {
17263     char message[MSG_SIZ];
17264     long time, otime;
17265
17266     /* Note: this routine must be called when the clocks are stopped
17267        or when they have *just* been set or switched; otherwise
17268        it will be off by the time since the current tick started.
17269     */
17270     if (machineWhite) {
17271         time = whiteTimeRemaining / 10;
17272         otime = blackTimeRemaining / 10;
17273     } else {
17274         time = blackTimeRemaining / 10;
17275         otime = whiteTimeRemaining / 10;
17276     }
17277     /* [HGM] translate opponent's time by time-odds factor */
17278     otime = (otime * cps->other->timeOdds) / cps->timeOdds;
17279
17280     if (time <= 0) time = 1;
17281     if (otime <= 0) otime = 1;
17282
17283     snprintf(message, MSG_SIZ, "time %ld\n", time);
17284     SendToProgram(message, cps);
17285
17286     snprintf(message, MSG_SIZ, "otim %ld\n", otime);
17287     SendToProgram(message, cps);
17288 }
17289
17290 char *
17291 EngineDefinedVariant (ChessProgramState *cps, int n)
17292 {   // return name of n-th unknown variant that engine supports
17293     static char buf[MSG_SIZ];
17294     char *p, *s = cps->variants;
17295     if(!s) return NULL;
17296     do { // parse string from variants feature
17297       VariantClass v;
17298         p = strchr(s, ',');
17299         if(p) *p = NULLCHAR;
17300       v = StringToVariant(s);
17301       if(v == VariantNormal && strcmp(s, "normal") && !strstr(s, "_normal")) v = VariantUnknown; // garbage is recognized as normal
17302         if(v == VariantUnknown) { // non-standard variant in list of engine-supported variants
17303             if(!strcmp(s, "tenjiku") || !strcmp(s, "dai") || !strcmp(s, "dada") || // ignore Alien-Edition variants
17304                !strcmp(s, "maka") || !strcmp(s, "tai") || !strcmp(s, "kyoku") ||
17305                !strcmp(s, "checkers") || !strcmp(s, "go") || !strcmp(s, "reversi") ||
17306                !strcmp(s, "dark") || !strcmp(s, "alien") || !strcmp(s, "multi") || !strcmp(s, "amazons") ) n++;
17307             if(--n < 0) safeStrCpy(buf, s, MSG_SIZ);
17308         }
17309         if(p) *p++ = ',';
17310         if(n < 0) return buf;
17311     } while(s = p);
17312     return NULL;
17313 }
17314
17315 int
17316 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
17317 {
17318   char buf[MSG_SIZ];
17319   int len = strlen(name);
17320   int val;
17321
17322   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
17323     (*p) += len + 1;
17324     sscanf(*p, "%d", &val);
17325     *loc = (val != 0);
17326     while (**p && **p != ' ')
17327       (*p)++;
17328     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17329     SendToProgram(buf, cps);
17330     return TRUE;
17331   }
17332   return FALSE;
17333 }
17334
17335 int
17336 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
17337 {
17338   char buf[MSG_SIZ];
17339   int len = strlen(name);
17340   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
17341     (*p) += len + 1;
17342     sscanf(*p, "%d", loc);
17343     while (**p && **p != ' ') (*p)++;
17344     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17345     SendToProgram(buf, cps);
17346     return TRUE;
17347   }
17348   return FALSE;
17349 }
17350
17351 int
17352 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
17353 {
17354   char buf[MSG_SIZ];
17355   int len = strlen(name);
17356   if (strncmp((*p), name, len) == 0
17357       && (*p)[len] == '=' && (*p)[len+1] == '\"') {
17358     (*p) += len + 2;
17359     len = strlen(*p) + 1; if(len < MSG_SIZ && !strcmp(name, "option")) len = MSG_SIZ; // make sure string options have enough space to change their value
17360     FREE(*loc); *loc = malloc(len);
17361     strncpy(*loc, *p, len);
17362     sscanf(*p, "%[^\"]", *loc); // should always fit, because we allocated at least strlen(*p)
17363     while (**p && **p != '\"') (*p)++;
17364     if (**p == '\"') (*p)++;
17365     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17366     SendToProgram(buf, cps);
17367     return TRUE;
17368   }
17369   return FALSE;
17370 }
17371
17372 int
17373 ParseOption (Option *opt, ChessProgramState *cps)
17374 // [HGM] options: process the string that defines an engine option, and determine
17375 // name, type, default value, and allowed value range
17376 {
17377         char *p, *q, buf[MSG_SIZ];
17378         int n, min = (-1)<<31, max = 1<<31, def;
17379
17380         opt->target = &opt->value;   // OK for spin/slider and checkbox
17381         if(p = strstr(opt->name, " -spin ")) {
17382             if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
17383             if(max < min) max = min; // enforce consistency
17384             if(def < min) def = min;
17385             if(def > max) def = max;
17386             opt->value = def;
17387             opt->min = min;
17388             opt->max = max;
17389             opt->type = Spin;
17390         } else if((p = strstr(opt->name, " -slider "))) {
17391             // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
17392             if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
17393             if(max < min) max = min; // enforce consistency
17394             if(def < min) def = min;
17395             if(def > max) def = max;
17396             opt->value = def;
17397             opt->min = min;
17398             opt->max = max;
17399             opt->type = Spin; // Slider;
17400         } else if((p = strstr(opt->name, " -string "))) {
17401             opt->textValue = p+9;
17402             opt->type = TextBox;
17403             opt->target = &opt->textValue;
17404         } else if((p = strstr(opt->name, " -file "))) {
17405             // for now -file is a synonym for -string, to already provide compatibility with future polyglots
17406             opt->target = opt->textValue = p+7;
17407             opt->type = FileName; // FileName;
17408             opt->target = &opt->textValue;
17409         } else if((p = strstr(opt->name, " -path "))) {
17410             // for now -file is a synonym for -string, to already provide compatibility with future polyglots
17411             opt->target = opt->textValue = p+7;
17412             opt->type = PathName; // PathName;
17413             opt->target = &opt->textValue;
17414         } else if(p = strstr(opt->name, " -check ")) {
17415             if(sscanf(p, " -check %d", &def) < 1) return FALSE;
17416             opt->value = (def != 0);
17417             opt->type = CheckBox;
17418         } else if(p = strstr(opt->name, " -combo ")) {
17419             opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
17420             cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
17421             if(*q == '*') cps->comboList[cps->comboCnt-1]++;
17422             opt->value = n = 0;
17423             while(q = StrStr(q, " /// ")) {
17424                 n++; *q = 0;    // count choices, and null-terminate each of them
17425                 q += 5;
17426                 if(*q == '*') { // remember default, which is marked with * prefix
17427                     q++;
17428                     opt->value = n;
17429                 }
17430                 cps->comboList[cps->comboCnt++] = q;
17431             }
17432             cps->comboList[cps->comboCnt++] = NULL;
17433             opt->max = n + 1;
17434             opt->type = ComboBox;
17435         } else if(p = strstr(opt->name, " -button")) {
17436             opt->type = Button;
17437         } else if(p = strstr(opt->name, " -save")) {
17438             opt->type = SaveButton;
17439         } else return FALSE;
17440         *p = 0; // terminate option name
17441         *(int*) (opt->name + MSG_SIZ - 104) = opt->value; // hide default values somewhere
17442         if(opt->target == &opt->textValue) strncpy(opt->name + MSG_SIZ - 100, opt->textValue, 99);
17443         // now look if the command-line options define a setting for this engine option.
17444         if(cps->optionSettings && cps->optionSettings[0])
17445             p = strstr(cps->optionSettings, opt->name); else p = NULL;
17446         if(p && (p == cps->optionSettings || p[-1] == ',')) {
17447           snprintf(buf, MSG_SIZ, "option %s", p);
17448                 if(p = strstr(buf, ",")) *p = 0;
17449                 if(q = strchr(buf, '=')) switch(opt->type) {
17450                     case ComboBox:
17451                         for(n=0; n<opt->max; n++)
17452                             if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
17453                         break;
17454                     case TextBox:
17455                     case FileName:
17456                     case PathName:
17457                         safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
17458                         break;
17459                     case Spin:
17460                     case CheckBox:
17461                         opt->value = atoi(q+1);
17462                     default:
17463                         break;
17464                 }
17465                 strcat(buf, "\n");
17466                 SendToProgram(buf, cps);
17467         }
17468         return TRUE;
17469 }
17470
17471 void
17472 FeatureDone (ChessProgramState *cps, int val)
17473 {
17474   DelayedEventCallback cb = GetDelayedEvent();
17475   if ((cb == InitBackEnd3 && cps == &first) ||
17476       (cb == SettingsMenuIfReady && cps == &second) ||
17477       (cb == LoadEngine) || (cb == StartSecond) ||
17478       (cb == TwoMachinesEventIfReady)) {
17479     CancelDelayedEvent();
17480     ScheduleDelayedEvent(cb, val ? 1 : 3600000);
17481   } else if(!val && !cps->reload) ClearOptions(cps); // let 'spurious' done=0 clear engine's option list
17482   cps->initDone = val;
17483   if(val) cps->reload = FALSE,  RefreshSettingsDialog(cps, val);
17484 }
17485
17486 /* Parse feature command from engine */
17487 void
17488 ParseFeatures (char *args, ChessProgramState *cps)
17489 {
17490   char *p = args;
17491   char *q = NULL;
17492   int val;
17493   char buf[MSG_SIZ];
17494
17495   for (;;) {
17496     while (*p == ' ') p++;
17497     if (*p == NULLCHAR) return;
17498
17499     if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
17500     if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
17501     if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
17502     if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
17503     if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
17504     if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
17505     if (BoolFeature(&p, "reuse", &val, cps)) {
17506       /* Engine can disable reuse, but can't enable it if user said no */
17507       if (!val) cps->reuse = FALSE;
17508       continue;
17509     }
17510     if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
17511     if (StringFeature(&p, "myname", &cps->tidy, cps)) {
17512       if (gameMode == TwoMachinesPlay) {
17513         DisplayTwoMachinesTitle();
17514       } else {
17515         DisplayTitle("");
17516       }
17517       continue;
17518     }
17519     if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
17520     if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
17521     if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
17522     if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
17523     if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
17524     if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
17525     if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
17526     if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
17527     if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
17528     if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
17529     if (IntFeature(&p, "done", &val, cps)) {
17530       FeatureDone(cps, val);
17531       continue;
17532     }
17533     /* Added by Tord: */
17534     if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
17535     if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
17536     /* End of additions by Tord */
17537
17538     /* [HGM] added features: */
17539     if (BoolFeature(&p, "highlight", &cps->highlight, cps)) continue;
17540     if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
17541     if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
17542     if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
17543     if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
17544     if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
17545     if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
17546     if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
17547         if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
17548         if(cps->nrOptions == 0) { ASSIGN(cps->option[0].name, _("Make Persistent -save")); ParseOption(&(cps->option[cps->nrOptions++]), cps); }
17549         FREE(cps->option[cps->nrOptions].name);
17550         cps->option[cps->nrOptions].name = q; q = NULL;
17551         if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
17552           snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
17553             SendToProgram(buf, cps);
17554             continue;
17555         }
17556         if(cps->nrOptions >= MAX_OPTIONS) {
17557             cps->nrOptions--;
17558             snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
17559             DisplayError(buf, 0);
17560         }
17561         continue;
17562     }
17563     /* End of additions by HGM */
17564
17565     /* unknown feature: complain and skip */
17566     q = p;
17567     while (*q && *q != '=') q++;
17568     snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
17569     SendToProgram(buf, cps);
17570     p = q;
17571     if (*p == '=') {
17572       p++;
17573       if (*p == '\"') {
17574         p++;
17575         while (*p && *p != '\"') p++;
17576         if (*p == '\"') p++;
17577       } else {
17578         while (*p && *p != ' ') p++;
17579       }
17580     }
17581   }
17582
17583 }
17584
17585 void
17586 PeriodicUpdatesEvent (int newState)
17587 {
17588     if (newState == appData.periodicUpdates)
17589       return;
17590
17591     appData.periodicUpdates=newState;
17592
17593     /* Display type changes, so update it now */
17594 //    DisplayAnalysis();
17595
17596     /* Get the ball rolling again... */
17597     if (newState) {
17598         AnalysisPeriodicEvent(1);
17599         StartAnalysisClock();
17600     }
17601 }
17602
17603 void
17604 PonderNextMoveEvent (int newState)
17605 {
17606     if (newState == appData.ponderNextMove) return;
17607     if (gameMode == EditPosition) EditPositionDone(TRUE);
17608     if (newState) {
17609         SendToProgram("hard\n", &first);
17610         if (gameMode == TwoMachinesPlay) {
17611             SendToProgram("hard\n", &second);
17612         }
17613     } else {
17614         SendToProgram("easy\n", &first);
17615         thinkOutput[0] = NULLCHAR;
17616         if (gameMode == TwoMachinesPlay) {
17617             SendToProgram("easy\n", &second);
17618         }
17619     }
17620     appData.ponderNextMove = newState;
17621 }
17622
17623 void
17624 NewSettingEvent (int option, int *feature, char *command, int value)
17625 {
17626     char buf[MSG_SIZ];
17627
17628     if (gameMode == EditPosition) EditPositionDone(TRUE);
17629     snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
17630     if(feature == NULL || *feature) SendToProgram(buf, &first);
17631     if (gameMode == TwoMachinesPlay) {
17632         if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
17633     }
17634 }
17635
17636 void
17637 ShowThinkingEvent ()
17638 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
17639 {
17640     static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
17641     int newState = appData.showThinking
17642         // [HGM] thinking: other features now need thinking output as well
17643         || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
17644
17645     if (oldState == newState) return;
17646     oldState = newState;
17647     if (gameMode == EditPosition) EditPositionDone(TRUE);
17648     if (oldState) {
17649         SendToProgram("post\n", &first);
17650         if (gameMode == TwoMachinesPlay) {
17651             SendToProgram("post\n", &second);
17652         }
17653     } else {
17654         SendToProgram("nopost\n", &first);
17655         thinkOutput[0] = NULLCHAR;
17656         if (gameMode == TwoMachinesPlay) {
17657             SendToProgram("nopost\n", &second);
17658         }
17659     }
17660 //    appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
17661 }
17662
17663 void
17664 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
17665 {
17666   ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
17667   if (pr == NoProc) return;
17668   AskQuestion(title, question, replyPrefix, pr);
17669 }
17670
17671 void
17672 TypeInEvent (char firstChar)
17673 {
17674     if ((gameMode == BeginningOfGame && !appData.icsActive) ||
17675         gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
17676         gameMode == AnalyzeMode || gameMode == EditGame ||
17677         gameMode == EditPosition || gameMode == IcsExamining ||
17678         gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
17679         isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
17680                 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
17681                   gameMode == IcsObserving || gameMode == TwoMachinesPlay    ) ||
17682         gameMode == Training) PopUpMoveDialog(firstChar);
17683 }
17684
17685 void
17686 TypeInDoneEvent (char *move)
17687 {
17688         Board board;
17689         int n, fromX, fromY, toX, toY;
17690         char promoChar;
17691         ChessMove moveType;
17692
17693         // [HGM] FENedit
17694         if(gameMode == EditPosition && ParseFEN(board, &n, move, TRUE) ) {
17695                 EditPositionPasteFEN(move);
17696                 return;
17697         }
17698         // [HGM] movenum: allow move number to be typed in any mode
17699         if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
17700           ToNrEvent(2*n-1);
17701           return;
17702         }
17703         // undocumented kludge: allow command-line option to be typed in!
17704         // (potentially fatal, and does not implement the effect of the option.)
17705         // should only be used for options that are values on which future decisions will be made,
17706         // and definitely not on options that would be used during initialization.
17707         if(strstr(move, "!!! -") == move) {
17708             ParseArgsFromString(move+4);
17709             return;
17710         }
17711
17712       if (gameMode != EditGame && currentMove != forwardMostMove &&
17713         gameMode != Training) {
17714         DisplayMoveError(_("Displayed move is not current"));
17715       } else {
17716         int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17717           &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
17718         if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
17719         if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17720           &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
17721           UserMoveEvent(fromX, fromY, toX, toY, promoChar);
17722         } else {
17723           DisplayMoveError(_("Could not parse move"));
17724         }
17725       }
17726 }
17727
17728 void
17729 DisplayMove (int moveNumber)
17730 {
17731     char message[MSG_SIZ];
17732     char res[MSG_SIZ];
17733     char cpThinkOutput[MSG_SIZ];
17734
17735     if(appData.noGUI) return; // [HGM] fast: suppress display of moves
17736
17737     if (moveNumber == forwardMostMove - 1 ||
17738         gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
17739
17740         safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
17741
17742         if (strchr(cpThinkOutput, '\n')) {
17743             *strchr(cpThinkOutput, '\n') = NULLCHAR;
17744         }
17745     } else {
17746         *cpThinkOutput = NULLCHAR;
17747     }
17748
17749     /* [AS] Hide thinking from human user */
17750     if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
17751         *cpThinkOutput = NULLCHAR;
17752         if( thinkOutput[0] != NULLCHAR ) {
17753             int i;
17754
17755             for( i=0; i<=hiddenThinkOutputState; i++ ) {
17756                 cpThinkOutput[i] = '.';
17757             }
17758             cpThinkOutput[i] = NULLCHAR;
17759             hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
17760         }
17761     }
17762
17763     if (moveNumber == forwardMostMove - 1 &&
17764         gameInfo.resultDetails != NULL) {
17765         if (gameInfo.resultDetails[0] == NULLCHAR) {
17766           snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
17767         } else {
17768           snprintf(res, MSG_SIZ, " {%s} %s",
17769                     T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
17770         }
17771     } else {
17772         res[0] = NULLCHAR;
17773     }
17774
17775     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17776         DisplayMessage(res, cpThinkOutput);
17777     } else {
17778       snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
17779                 WhiteOnMove(moveNumber) ? " " : ".. ",
17780                 parseList[moveNumber], res);
17781         DisplayMessage(message, cpThinkOutput);
17782     }
17783 }
17784
17785 void
17786 DisplayComment (int moveNumber, char *text)
17787 {
17788     char title[MSG_SIZ];
17789
17790     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17791       safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
17792     } else {
17793       snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
17794               WhiteOnMove(moveNumber) ? " " : ".. ",
17795               parseList[moveNumber]);
17796     }
17797     if (text != NULL && (appData.autoDisplayComment || commentUp))
17798         CommentPopUp(title, text);
17799 }
17800
17801 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
17802  * might be busy thinking or pondering.  It can be omitted if your
17803  * gnuchess is configured to stop thinking immediately on any user
17804  * input.  However, that gnuchess feature depends on the FIONREAD
17805  * ioctl, which does not work properly on some flavors of Unix.
17806  */
17807 void
17808 Attention (ChessProgramState *cps)
17809 {
17810 #if ATTENTION
17811     if (!cps->useSigint) return;
17812     if (appData.noChessProgram || (cps->pr == NoProc)) return;
17813     switch (gameMode) {
17814       case MachinePlaysWhite:
17815       case MachinePlaysBlack:
17816       case TwoMachinesPlay:
17817       case IcsPlayingWhite:
17818       case IcsPlayingBlack:
17819       case AnalyzeMode:
17820       case AnalyzeFile:
17821         /* Skip if we know it isn't thinking */
17822         if (!cps->maybeThinking) return;
17823         if (appData.debugMode)
17824           fprintf(debugFP, "Interrupting %s\n", cps->which);
17825         InterruptChildProcess(cps->pr);
17826         cps->maybeThinking = FALSE;
17827         break;
17828       default:
17829         break;
17830     }
17831 #endif /*ATTENTION*/
17832 }
17833
17834 int
17835 CheckFlags ()
17836 {
17837     if (whiteTimeRemaining <= 0) {
17838         if (!whiteFlag) {
17839             whiteFlag = TRUE;
17840             if (appData.icsActive) {
17841                 if (appData.autoCallFlag &&
17842                     gameMode == IcsPlayingBlack && !blackFlag) {
17843                   SendToICS(ics_prefix);
17844                   SendToICS("flag\n");
17845                 }
17846             } else {
17847                 if (blackFlag) {
17848                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17849                 } else {
17850                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
17851                     if (appData.autoCallFlag) {
17852                         GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
17853                         return TRUE;
17854                     }
17855                 }
17856             }
17857         }
17858     }
17859     if (blackTimeRemaining <= 0) {
17860         if (!blackFlag) {
17861             blackFlag = TRUE;
17862             if (appData.icsActive) {
17863                 if (appData.autoCallFlag &&
17864                     gameMode == IcsPlayingWhite && !whiteFlag) {
17865                   SendToICS(ics_prefix);
17866                   SendToICS("flag\n");
17867                 }
17868             } else {
17869                 if (whiteFlag) {
17870                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17871                 } else {
17872                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
17873                     if (appData.autoCallFlag) {
17874                         GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
17875                         return TRUE;
17876                     }
17877                 }
17878             }
17879         }
17880     }
17881     return FALSE;
17882 }
17883
17884 void
17885 CheckTimeControl ()
17886 {
17887     if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
17888         gameMode == PlayFromGameFile || forwardMostMove == 0) return;
17889
17890     /*
17891      * add time to clocks when time control is achieved ([HGM] now also used for increment)
17892      */
17893     if ( !WhiteOnMove(forwardMostMove) ) {
17894         /* White made time control */
17895         lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
17896         whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
17897         /* [HGM] time odds: correct new time quota for time odds! */
17898                                             / WhitePlayer()->timeOdds;
17899         lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
17900     } else {
17901         lastBlack -= blackTimeRemaining;
17902         /* Black made time control */
17903         blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
17904                                             / WhitePlayer()->other->timeOdds;
17905         lastWhite = whiteTimeRemaining;
17906     }
17907 }
17908
17909 void
17910 DisplayBothClocks ()
17911 {
17912     int wom = gameMode == EditPosition ?
17913       !blackPlaysFirst : WhiteOnMove(currentMove);
17914     DisplayWhiteClock(whiteTimeRemaining, wom);
17915     DisplayBlackClock(blackTimeRemaining, !wom);
17916 }
17917
17918
17919 /* Timekeeping seems to be a portability nightmare.  I think everyone
17920    has ftime(), but I'm really not sure, so I'm including some ifdefs
17921    to use other calls if you don't.  Clocks will be less accurate if
17922    you have neither ftime nor gettimeofday.
17923 */
17924
17925 /* VS 2008 requires the #include outside of the function */
17926 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
17927 #include <sys/timeb.h>
17928 #endif
17929
17930 /* Get the current time as a TimeMark */
17931 void
17932 GetTimeMark (TimeMark *tm)
17933 {
17934 #if HAVE_GETTIMEOFDAY
17935
17936     struct timeval timeVal;
17937     struct timezone timeZone;
17938
17939     gettimeofday(&timeVal, &timeZone);
17940     tm->sec = (long) timeVal.tv_sec;
17941     tm->ms = (int) (timeVal.tv_usec / 1000L);
17942
17943 #else /*!HAVE_GETTIMEOFDAY*/
17944 #if HAVE_FTIME
17945
17946 // include <sys/timeb.h> / moved to just above start of function
17947     struct timeb timeB;
17948
17949     ftime(&timeB);
17950     tm->sec = (long) timeB.time;
17951     tm->ms = (int) timeB.millitm;
17952
17953 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
17954     tm->sec = (long) time(NULL);
17955     tm->ms = 0;
17956 #endif
17957 #endif
17958 }
17959
17960 /* Return the difference in milliseconds between two
17961    time marks.  We assume the difference will fit in a long!
17962 */
17963 long
17964 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
17965 {
17966     return 1000L*(tm2->sec - tm1->sec) +
17967            (long) (tm2->ms - tm1->ms);
17968 }
17969
17970
17971 /*
17972  * Code to manage the game clocks.
17973  *
17974  * In tournament play, black starts the clock and then white makes a move.
17975  * We give the human user a slight advantage if he is playing white---the
17976  * clocks don't run until he makes his first move, so it takes zero time.
17977  * Also, we don't account for network lag, so we could get out of sync
17978  * with GNU Chess's clock -- but then, referees are always right.
17979  */
17980
17981 static TimeMark tickStartTM;
17982 static long intendedTickLength;
17983
17984 long
17985 NextTickLength (long timeRemaining)
17986 {
17987     long nominalTickLength, nextTickLength;
17988
17989     if (timeRemaining > 0L && timeRemaining <= 10000L)
17990       nominalTickLength = 100L;
17991     else
17992       nominalTickLength = 1000L;
17993     nextTickLength = timeRemaining % nominalTickLength;
17994     if (nextTickLength <= 0) nextTickLength += nominalTickLength;
17995
17996     return nextTickLength;
17997 }
17998
17999 /* Adjust clock one minute up or down */
18000 void
18001 AdjustClock (Boolean which, int dir)
18002 {
18003     if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
18004     if(which) blackTimeRemaining += 60000*dir;
18005     else      whiteTimeRemaining += 60000*dir;
18006     DisplayBothClocks();
18007     adjustedClock = TRUE;
18008 }
18009
18010 /* Stop clocks and reset to a fresh time control */
18011 void
18012 ResetClocks ()
18013 {
18014     (void) StopClockTimer();
18015     if (appData.icsActive) {
18016         whiteTimeRemaining = blackTimeRemaining = 0;
18017     } else if (searchTime) {
18018         whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
18019         blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
18020     } else { /* [HGM] correct new time quote for time odds */
18021         whiteTC = blackTC = fullTimeControlString;
18022         whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
18023         blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
18024     }
18025     if (whiteFlag || blackFlag) {
18026         DisplayTitle("");
18027         whiteFlag = blackFlag = FALSE;
18028     }
18029     lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
18030     DisplayBothClocks();
18031     adjustedClock = FALSE;
18032 }
18033
18034 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
18035
18036 static int timeSuffix; // [HGM] This should realy be a passed parameter, but it has to pass through too many levels for my laziness...
18037
18038 /* Decrement running clock by amount of time that has passed */
18039 void
18040 DecrementClocks ()
18041 {
18042     long tRemaining;
18043     long lastTickLength, fudge;
18044     TimeMark now;
18045
18046     if (!appData.clockMode) return;
18047     if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
18048
18049     GetTimeMark(&now);
18050
18051     lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18052
18053     /* Fudge if we woke up a little too soon */
18054     fudge = intendedTickLength - lastTickLength;
18055     if (fudge < 0 || fudge > FUDGE) fudge = 0;
18056
18057     if (WhiteOnMove(forwardMostMove)) {
18058         if(whiteNPS >= 0) lastTickLength = 0;
18059          tRemaining = whiteTimeRemaining -= lastTickLength;
18060         if( tRemaining < 0 && !appData.icsActive) {
18061             GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
18062             if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
18063                 whiteStartMove = forwardMostMove; whiteTC = nextSession;
18064                 lastWhite=  tRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
18065             }
18066         }
18067         if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[0][forwardMostMove-1] - tRemaining;
18068         DisplayWhiteClock(whiteTimeRemaining - fudge,
18069                           WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
18070         timeSuffix = 0;
18071     } else {
18072         if(blackNPS >= 0) lastTickLength = 0;
18073          tRemaining = blackTimeRemaining -= lastTickLength;
18074         if( tRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
18075             GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
18076             if(suddenDeath) {
18077                 blackStartMove = forwardMostMove;
18078                 lastBlack =  tRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
18079             }
18080         }
18081         if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[1][forwardMostMove-1] - tRemaining;
18082         DisplayBlackClock(blackTimeRemaining - fudge,
18083                           !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
18084         timeSuffix = 0;
18085     }
18086     if (CheckFlags()) return;
18087
18088     if(twoBoards) { // count down secondary board's clocks as well
18089         activePartnerTime -= lastTickLength;
18090         partnerUp = 1;
18091         if(activePartner == 'W')
18092             DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
18093         else
18094             DisplayBlackClock(activePartnerTime, TRUE);
18095         partnerUp = 0;
18096     }
18097
18098     tickStartTM = now;
18099     intendedTickLength = NextTickLength( tRemaining - fudge) + fudge;
18100     StartClockTimer(intendedTickLength);
18101
18102     /* if the time remaining has fallen below the alarm threshold, sound the
18103      * alarm. if the alarm has sounded and (due to a takeback or time control
18104      * with increment) the time remaining has increased to a level above the
18105      * threshold, reset the alarm so it can sound again.
18106      */
18107
18108     if (appData.icsActive && appData.icsAlarm) {
18109
18110         /* make sure we are dealing with the user's clock */
18111         if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
18112                ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
18113            )) return;
18114
18115         if (alarmSounded && ( tRemaining > appData.icsAlarmTime)) {
18116             alarmSounded = FALSE;
18117         } else if (!alarmSounded && ( tRemaining <= appData.icsAlarmTime)) {
18118             PlayAlarmSound();
18119             alarmSounded = TRUE;
18120         }
18121     }
18122 }
18123
18124
18125 /* A player has just moved, so stop the previously running
18126    clock and (if in clock mode) start the other one.
18127    We redisplay both clocks in case we're in ICS mode, because
18128    ICS gives us an update to both clocks after every move.
18129    Note that this routine is called *after* forwardMostMove
18130    is updated, so the last fractional tick must be subtracted
18131    from the color that is *not* on move now.
18132 */
18133 void
18134 SwitchClocks (int newMoveNr)
18135 {
18136     long lastTickLength;
18137     TimeMark now;
18138     int flagged = FALSE;
18139
18140     GetTimeMark(&now);
18141
18142     if (StopClockTimer() && appData.clockMode) {
18143         lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18144         if (!WhiteOnMove(forwardMostMove)) {
18145             if(blackNPS >= 0) lastTickLength = 0;
18146             blackTimeRemaining -= lastTickLength;
18147            /* [HGM] PGNtime: save time for PGN file if engine did not give it */
18148 //         if(pvInfoList[forwardMostMove].time == -1)
18149                  pvInfoList[forwardMostMove].time =               // use GUI time
18150                       (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
18151         } else {
18152            if(whiteNPS >= 0) lastTickLength = 0;
18153            whiteTimeRemaining -= lastTickLength;
18154            /* [HGM] PGNtime: save time for PGN file if engine did not give it */
18155 //         if(pvInfoList[forwardMostMove].time == -1)
18156                  pvInfoList[forwardMostMove].time =
18157                       (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
18158         }
18159         flagged = CheckFlags();
18160     }
18161     forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
18162     CheckTimeControl();
18163
18164     if (flagged || !appData.clockMode) return;
18165
18166     switch (gameMode) {
18167       case MachinePlaysBlack:
18168       case MachinePlaysWhite:
18169       case BeginningOfGame:
18170         if (pausing) return;
18171         break;
18172
18173       case EditGame:
18174       case PlayFromGameFile:
18175       case IcsExamining:
18176         return;
18177
18178       default:
18179         break;
18180     }
18181
18182     if (searchTime) { // [HGM] st: set clock of player that has to move to max time
18183         if(WhiteOnMove(forwardMostMove))
18184              whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
18185         else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
18186     }
18187
18188     tickStartTM = now;
18189     intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
18190       whiteTimeRemaining : blackTimeRemaining);
18191     StartClockTimer(intendedTickLength);
18192 }
18193
18194
18195 /* Stop both clocks */
18196 void
18197 StopClocks ()
18198 {
18199     long lastTickLength;
18200     TimeMark now;
18201
18202     if (!StopClockTimer()) return;
18203     if (!appData.clockMode) return;
18204
18205     GetTimeMark(&now);
18206
18207     lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18208     if (WhiteOnMove(forwardMostMove)) {
18209         if(whiteNPS >= 0) lastTickLength = 0;
18210         whiteTimeRemaining -= lastTickLength;
18211         DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
18212     } else {
18213         if(blackNPS >= 0) lastTickLength = 0;
18214         blackTimeRemaining -= lastTickLength;
18215         DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
18216     }
18217     CheckFlags();
18218 }
18219
18220 /* Start clock of player on move.  Time may have been reset, so
18221    if clock is already running, stop and restart it. */
18222 void
18223 StartClocks ()
18224 {
18225     (void) StopClockTimer(); /* in case it was running already */
18226     DisplayBothClocks();
18227     if (CheckFlags()) return;
18228
18229     if (!appData.clockMode) return;
18230     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
18231
18232     GetTimeMark(&tickStartTM);
18233     intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
18234       whiteTimeRemaining : blackTimeRemaining);
18235
18236    /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
18237     whiteNPS = blackNPS = -1;
18238     if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
18239        || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
18240         whiteNPS = first.nps;
18241     if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
18242        || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
18243         blackNPS = first.nps;
18244     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
18245         whiteNPS = second.nps;
18246     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
18247         blackNPS = second.nps;
18248     if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
18249
18250     StartClockTimer(intendedTickLength);
18251 }
18252
18253 char *
18254 TimeString (long ms)
18255 {
18256     long second, minute, hour, day;
18257     char *sign = "";
18258     static char buf[40], moveTime[8];
18259
18260     if (ms > 0 && ms <= 9900) {
18261       /* convert milliseconds to tenths, rounding up */
18262       double tenths = floor( ((double)(ms + 99L)) / 100.00 );
18263
18264       snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
18265       return buf;
18266     }
18267
18268     /* convert milliseconds to seconds, rounding up */
18269     /* use floating point to avoid strangeness of integer division
18270        with negative dividends on many machines */
18271     second = (long) floor(((double) (ms + 999L)) / 1000.0);
18272
18273     if (second < 0) {
18274         sign = "-";
18275         second = -second;
18276     }
18277
18278     day = second / (60 * 60 * 24);
18279     second = second % (60 * 60 * 24);
18280     hour = second / (60 * 60);
18281     second = second % (60 * 60);
18282     minute = second / 60;
18283     second = second % 60;
18284
18285     if(timeSuffix) snprintf(moveTime, 8, " (%d)", timeSuffix/1000); // [HGM] kludge alert; fraction contains move time
18286     else *moveTime = NULLCHAR;
18287
18288     if (day > 0)
18289       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld%s ",
18290               sign, day, hour, minute, second, moveTime);
18291     else if (hour > 0)
18292       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld%s ", sign, hour, minute, second, moveTime);
18293     else
18294       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld%s ", sign, minute, second, moveTime);
18295
18296     return buf;
18297 }
18298
18299
18300 /*
18301  * This is necessary because some C libraries aren't ANSI C compliant yet.
18302  */
18303 char *
18304 StrStr (char *string, char *match)
18305 {
18306     int i, length;
18307
18308     length = strlen(match);
18309
18310     for (i = strlen(string) - length; i >= 0; i--, string++)
18311       if (!strncmp(match, string, length))
18312         return string;
18313
18314     return NULL;
18315 }
18316
18317 char *
18318 StrCaseStr (char *string, char *match)
18319 {
18320     int i, j, length;
18321
18322     length = strlen(match);
18323
18324     for (i = strlen(string) - length; i >= 0; i--, string++) {
18325         for (j = 0; j < length; j++) {
18326             if (ToLower(match[j]) != ToLower(string[j]))
18327               break;
18328         }
18329         if (j == length) return string;
18330     }
18331
18332     return NULL;
18333 }
18334
18335 #ifndef _amigados
18336 int
18337 StrCaseCmp (char *s1, char *s2)
18338 {
18339     char c1, c2;
18340
18341     for (;;) {
18342         c1 = ToLower(*s1++);
18343         c2 = ToLower(*s2++);
18344         if (c1 > c2) return 1;
18345         if (c1 < c2) return -1;
18346         if (c1 == NULLCHAR) return 0;
18347     }
18348 }
18349
18350
18351 int
18352 ToLower (int c)
18353 {
18354     return isupper(c) ? tolower(c) : c;
18355 }
18356
18357
18358 int
18359 ToUpper (int c)
18360 {
18361     return islower(c) ? toupper(c) : c;
18362 }
18363 #endif /* !_amigados    */
18364
18365 char *
18366 StrSave (char *s)
18367 {
18368   char *ret;
18369
18370   if ((ret = (char *) malloc(strlen(s) + 1)))
18371     {
18372       safeStrCpy(ret, s, strlen(s)+1);
18373     }
18374   return ret;
18375 }
18376
18377 char *
18378 StrSavePtr (char *s, char **savePtr)
18379 {
18380     if (*savePtr) {
18381         free(*savePtr);
18382     }
18383     if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
18384       safeStrCpy(*savePtr, s, strlen(s)+1);
18385     }
18386     return(*savePtr);
18387 }
18388
18389 char *
18390 PGNDate ()
18391 {
18392     time_t clock;
18393     struct tm *tm;
18394     char buf[MSG_SIZ];
18395
18396     clock = time((time_t *)NULL);
18397     tm = localtime(&clock);
18398     snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
18399             tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
18400     return StrSave(buf);
18401 }
18402
18403
18404 char *
18405 PositionToFEN (int move, char *overrideCastling, int moveCounts)
18406 {
18407     int i, j, fromX, fromY, toX, toY;
18408     int whiteToPlay, haveRights = nrCastlingRights;
18409     char buf[MSG_SIZ];
18410     char *p, *q;
18411     int emptycount;
18412     ChessSquare piece;
18413
18414     whiteToPlay = (gameMode == EditPosition) ?
18415       !blackPlaysFirst : (move % 2 == 0);
18416     p = buf;
18417
18418     /* Piece placement data */
18419     for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
18420         if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
18421         emptycount = 0;
18422         for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
18423             if (boards[move][i][j] == EmptySquare) {
18424                 emptycount++;
18425             } else { ChessSquare piece = boards[move][i][j];
18426                 if (emptycount > 0) {
18427                     if(emptycount<10) /* [HGM] can be >= 10 */
18428                         *p++ = '0' + emptycount;
18429                     else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
18430                     emptycount = 0;
18431                 }
18432                 if(PieceToChar(piece) == '+') {
18433                     /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
18434                     *p++ = '+';
18435                     piece = (ChessSquare)(CHUDEMOTED(piece));
18436                 }
18437                 *p++ = (piece == DarkSquare ? '*' : PieceToChar(piece));
18438                 if(*p = PieceSuffix(piece)) p++;
18439                 if(p[-1] == '~') {
18440                     /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
18441                     p[-1] = PieceToChar((ChessSquare)(CHUDEMOTED(piece)));
18442                     *p++ = '~';
18443                 }
18444             }
18445         }
18446         if (emptycount > 0) {
18447             if(emptycount<10) /* [HGM] can be >= 10 */
18448                 *p++ = '0' + emptycount;
18449             else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
18450             emptycount = 0;
18451         }
18452         *p++ = '/';
18453     }
18454     *(p - 1) = ' ';
18455
18456     /* [HGM] print Crazyhouse or Shogi holdings */
18457     if( gameInfo.holdingsWidth ) {
18458         *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
18459         q = p;
18460         for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
18461             piece = boards[move][i][BOARD_WIDTH-1];
18462             if( piece != EmptySquare )
18463               for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
18464                   *p++ = PieceToChar(piece);
18465         }
18466         for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
18467             piece = boards[move][handSize-i-1][0];
18468             if( piece != EmptySquare )
18469               for(j=0; j<(int) boards[move][handSize-i-1][1]; j++)
18470                   *p++ = PieceToChar(piece);
18471         }
18472
18473         if( q == p ) *p++ = '-';
18474         *p++ = ']';
18475         *p++ = ' ';
18476     }
18477
18478     /* Active color */
18479     *p++ = whiteToPlay ? 'w' : 'b';
18480     *p++ = ' ';
18481
18482   if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
18483     haveRights = 0; q = p;
18484     for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
18485       piece = boards[move][0][i];
18486       if(piece >= WhitePawn && piece <= WhiteKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
18487         if(!(boards[move][TOUCHED_W] & 1<<i)) *p++ = 'A' + i; // print file ID if it has not moved
18488       }
18489     }
18490     for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
18491       piece = boards[move][BOARD_HEIGHT-1][i];
18492       if(piece >= BlackPawn && piece <= BlackKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
18493         if(!(boards[move][TOUCHED_B] & 1<<i)) *p++ = 'a' + i; // print file ID if it has not moved
18494       }
18495     }
18496     if(p == q) *p++ = '-';
18497     *p++ = ' ';
18498   }
18499
18500   if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
18501     while(*p++ = *q++)
18502                       ;
18503     if(q != overrideCastling+1) p[-1] = ' '; else --p;
18504   } else {
18505   if(haveRights) {
18506      int handW=0, handB=0;
18507      if(gameInfo.variant == VariantSChess) { // for S-Chess, all virgin backrank pieces must be listed
18508         for(i=0; i<BOARD_HEIGHT; i++) handW += boards[move][i][BOARD_RGHT]; // count white held pieces
18509         for(i=0; i<BOARD_HEIGHT; i++) handB += boards[move][i][BOARD_LEFT-1]; // count black held pieces
18510      }
18511      q = p;
18512      if(appData.fischerCastling) {
18513         if(handW) { // in shuffle S-Chess simply dump all virgin pieces
18514            for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
18515                if(boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
18516         } else {
18517        /* [HGM] write directly from rights */
18518            if(boards[move][CASTLING][2] != NoRights &&
18519               boards[move][CASTLING][0] != NoRights   )
18520                 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
18521            if(boards[move][CASTLING][2] != NoRights &&
18522               boards[move][CASTLING][1] != NoRights   )
18523                 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
18524         }
18525         if(handB) {
18526            for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
18527                if(boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
18528         } else {
18529            if(boards[move][CASTLING][5] != NoRights &&
18530               boards[move][CASTLING][3] != NoRights   )
18531                 *p++ = boards[move][CASTLING][3] + AAA;
18532            if(boards[move][CASTLING][5] != NoRights &&
18533               boards[move][CASTLING][4] != NoRights   )
18534                 *p++ = boards[move][CASTLING][4] + AAA;
18535         }
18536      } else {
18537
18538         /* [HGM] write true castling rights */
18539         if( nrCastlingRights == 6 ) {
18540             int q, k=0;
18541             if(boards[move][CASTLING][0] != NoRights &&
18542                boards[move][CASTLING][2] != NoRights  ) k = 1, *p++ = 'K';
18543             q = (boards[move][CASTLING][1] != NoRights &&
18544                  boards[move][CASTLING][2] != NoRights  );
18545             if(handW) { // for S-Chess with pieces in hand, list virgin pieces between K and Q
18546                 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
18547                     if((boards[move][0][i] != WhiteKing || k+q == 0) &&
18548                         boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
18549             }
18550             if(q) *p++ = 'Q';
18551             k = 0;
18552             if(boards[move][CASTLING][3] != NoRights &&
18553                boards[move][CASTLING][5] != NoRights  ) k = 1, *p++ = 'k';
18554             q = (boards[move][CASTLING][4] != NoRights &&
18555                  boards[move][CASTLING][5] != NoRights  );
18556             if(handB) {
18557                 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
18558                     if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
18559                         boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
18560             }
18561             if(q) *p++ = 'q';
18562         }
18563      }
18564      if (q == p) *p++ = '-'; /* No castling rights */
18565      *p++ = ' ';
18566   }
18567
18568   if(gameInfo.variant != VariantShogi    && gameInfo.variant != VariantXiangqi &&
18569      gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18570      gameInfo.variant != VariantMakruk   && gameInfo.variant != VariantASEAN ) {
18571     /* En passant target square */
18572     if (move > backwardMostMove) {
18573         fromX = moveList[move - 1][0] - AAA;
18574         fromY = moveList[move - 1][1] - ONE;
18575         toX = moveList[move - 1][2] - AAA;
18576         toY = moveList[move - 1][3] - ONE;
18577         if ((whiteToPlay ? toY < fromY - 1 : toY > fromY + 1) &&
18578             boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) ) {
18579             /* 2-square pawn move just happened */
18580             *p++ = (3*toX + 5*fromX + 4)/8 + AAA;
18581             *p++ = (3*toY + 5*fromY + 4)/8 + ONE;
18582             if(gameInfo.variant == VariantBerolina) {
18583                 *p++ = toX + AAA;
18584                 *p++ = toY + ONE;
18585             }
18586         } else {
18587             *p++ = '-';
18588         }
18589     } else if(move == backwardMostMove) {
18590         // [HGM] perhaps we should always do it like this, and forget the above?
18591         if((signed char)boards[move][EP_STATUS] >= 0) {
18592             *p++ = boards[move][EP_STATUS] + AAA;
18593             *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
18594         } else {
18595             *p++ = '-';
18596         }
18597     } else {
18598         *p++ = '-';
18599     }
18600     *p++ = ' ';
18601   }
18602   }
18603
18604     i = boards[move][CHECK_COUNT];
18605     if(i) {
18606         sprintf(p, "%d+%d ", i&255, i>>8);
18607         while(*p) p++;
18608     }
18609
18610     if(moveCounts)
18611     {   int i = 0, j=move;
18612
18613         /* [HGM] find reversible plies */
18614         if (appData.debugMode) { int k;
18615             fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
18616             for(k=backwardMostMove; k<=forwardMostMove; k++)
18617                 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
18618
18619         }
18620
18621         while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
18622         if( j == backwardMostMove ) i += initialRulePlies;
18623         sprintf(p, "%d ", i);
18624         p += i>=100 ? 4 : i >= 10 ? 3 : 2;
18625
18626         /* Fullmove number */
18627         sprintf(p, "%d", (move / 2) + 1);
18628     } else *--p = NULLCHAR;
18629
18630     return StrSave(buf);
18631 }
18632
18633 Boolean
18634 ParseFEN (Board board, int *blackPlaysFirst, char *fen, Boolean autoSize)
18635 {
18636     int i, j, k, w=0, subst=0, shuffle=0, wKingRank = -1, bKingRank = -1;
18637     char *p, c;
18638     int emptycount, virgin[BOARD_FILES];
18639     ChessSquare piece, king = (gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing);
18640
18641     p = fen;
18642
18643     for(i=1; i<=deadRanks; i++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) board[BOARD_HEIGHT-i][j] = DarkSquare;
18644
18645     /* Piece placement data */
18646     for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
18647         j = 0;
18648         for (;;) {
18649             if (*p == '/' || *p == ' ' || *p == '[' ) {
18650                 if(j > w) w = j;
18651                 emptycount = gameInfo.boardWidth - j;
18652                 while (emptycount--)
18653                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18654                 if (*p == '/') p++;
18655                 else if(autoSize && i != BOARD_HEIGHT-1) { // we stumbled unexpectedly into end of board
18656                     for(k=i; k<BOARD_HEIGHT; k++) { // too few ranks; shift towards bottom
18657                         for(j=0; j<BOARD_WIDTH; j++) board[k-i][j] = board[k][j];
18658                     }
18659                     appData.NrRanks = gameInfo.boardHeight - i; i=0;
18660                 }
18661                 break;
18662 #if(BOARD_FILES >= 10)*0
18663             } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
18664                 p++; emptycount=10;
18665                 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18666                 while (emptycount--)
18667                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18668 #endif
18669             } else if (*p == '*') {
18670                 board[i][(j++)+gameInfo.holdingsWidth] = DarkSquare; p++;
18671             } else if (isdigit(*p)) {
18672                 emptycount = *p++ - '0';
18673                 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
18674                 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18675                 while (emptycount--)
18676                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18677             } else if (*p == '<') {
18678                 if(i == BOARD_HEIGHT-1) shuffle = 1;
18679                 else if (i != 0 || !shuffle) return FALSE;
18680                 p++;
18681             } else if (shuffle && *p == '>') {
18682                 p++; // for now ignore closing shuffle range, and assume rank-end
18683             } else if (*p == '?') {
18684                 if (j >= gameInfo.boardWidth) return FALSE;
18685                 if (i != 0  && i != BOARD_HEIGHT-1) return FALSE; // only on back-rank
18686                 board[i][(j++)+gameInfo.holdingsWidth] = ClearBoard; p++; subst++; // placeHolder
18687             } else if (*p == '+' || isalpha(*p)) {
18688                 char *q, *s = SUFFIXES;
18689                 if (j >= gameInfo.boardWidth) return FALSE;
18690                 if(*p=='+') {
18691                     char c = *++p;
18692                     if(q = strchr(s, p[1])) p++;
18693                     piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
18694                     if(piece == EmptySquare) return FALSE; /* unknown piece */
18695                     piece = (ChessSquare) (CHUPROMOTED(piece)); p++;
18696                     if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
18697                 } else {
18698                     char c = *p++;
18699                     if(q = strchr(s, *p)) p++;
18700                     piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
18701                 }
18702
18703                 if(piece==EmptySquare) return FALSE; /* unknown piece */
18704                 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
18705                     piece = (ChessSquare) (PROMOTED(piece));
18706                     if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
18707                     p++;
18708                 }
18709                 board[i][(j++)+gameInfo.holdingsWidth] = piece;
18710                 if(piece == king) wKingRank = i;
18711                 if(piece == WHITE_TO_BLACK king) bKingRank = i;
18712             } else {
18713                 return FALSE;
18714             }
18715         }
18716     }
18717     while (*p == '/' || *p == ' ') p++;
18718
18719     if(autoSize && w != 0) appData.NrFiles = w, InitPosition(TRUE);
18720
18721     /* [HGM] by default clear Crazyhouse holdings, if present */
18722     if(gameInfo.holdingsWidth) {
18723        for(i=0; i<handSize; i++) {
18724            board[i][0]             = EmptySquare; /* black holdings */
18725            board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
18726            board[i][1]             = (ChessSquare) 0; /* black counts */
18727            board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
18728        }
18729     }
18730
18731     /* [HGM] look for Crazyhouse holdings here */
18732     while(*p==' ') p++;
18733     if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
18734         int swap=0, wcnt=0, bcnt=0;
18735         if(*p == '[') p++;
18736         if(*p == '<') swap++, p++;
18737         if(*p == '-' ) p++; /* empty holdings */ else {
18738             if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
18739             /* if we would allow FEN reading to set board size, we would   */
18740             /* have to add holdings and shift the board read so far here   */
18741             while( (piece = CharToPiece(*p) ) != EmptySquare ) {
18742                 p++;
18743                 if((int) piece >= (int) BlackPawn ) {
18744                     i = (int)piece - (int)BlackPawn;
18745                     i = PieceToNumber((ChessSquare)i);
18746                     if( i >= gameInfo.holdingsSize ) return FALSE;
18747                     board[handSize-1-i][0] = piece; /* black holdings */
18748                     board[handSize-1-i][1]++;       /* black counts   */
18749                     bcnt++;
18750                 } else {
18751                     i = (int)piece - (int)WhitePawn;
18752                     i = PieceToNumber((ChessSquare)i);
18753                     if( i >= gameInfo.holdingsSize ) return FALSE;
18754                     board[i][BOARD_WIDTH-1] = piece;    /* white holdings */
18755                     board[i][BOARD_WIDTH-2]++;          /* black holdings */
18756                     wcnt++;
18757                 }
18758             }
18759             if(subst) { // substitute back-rank question marks by holdings pieces
18760                 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
18761                     int k, m, n = bcnt + 1;
18762                     if(board[0][j] == ClearBoard) {
18763                         if(!wcnt) return FALSE;
18764                         n = rand() % wcnt;
18765                         for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((m -= board[k][BOARD_WIDTH-2]) < 0) {
18766                             board[0][j] = board[k][BOARD_WIDTH-1]; wcnt--;
18767                             if(--board[k][BOARD_WIDTH-2] == 0) board[k][BOARD_WIDTH-1] = EmptySquare;
18768                             break;
18769                         }
18770                     }
18771                     if(board[BOARD_HEIGHT-1][j] == ClearBoard) {
18772                         if(!bcnt) return FALSE;
18773                         if(n >= bcnt) n = rand() % bcnt; // use same randomization for black and white if possible
18774                         for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((n -= board[handSize-1-k][1]) < 0) {
18775                             board[BOARD_HEIGHT-1][j] = board[handSize-1-k][0]; bcnt--;
18776                             if(--board[handSize-1-k][1] == 0) board[handSize-1-k][0] = EmptySquare;
18777                             break;
18778                         }
18779                     }
18780                 }
18781                 subst = 0;
18782             }
18783         }
18784         if(*p == ']') p++;
18785     }
18786
18787     if(subst) return FALSE; // substitution requested, but no holdings
18788
18789     while(*p == ' ') p++;
18790
18791     /* Active color */
18792     c = *p++;
18793     if(appData.colorNickNames) {
18794       if( c == appData.colorNickNames[0] ) c = 'w'; else
18795       if( c == appData.colorNickNames[1] ) c = 'b';
18796     }
18797     switch (c) {
18798       case 'w':
18799         *blackPlaysFirst = FALSE;
18800         break;
18801       case 'b':
18802         *blackPlaysFirst = TRUE;
18803         break;
18804       default:
18805         return FALSE;
18806     }
18807
18808     /* [HGM] We NO LONGER ignore the rest of the FEN notation */
18809     /* return the extra info in global variiables             */
18810
18811     while(*p==' ') p++;
18812
18813     if(!isdigit(*p) && *p != '-') { // we seem to have castling rights. Make sure they are on the rank the King actually is.
18814         if(wKingRank >= 0) for(i=0; i<3; i++) castlingRank[i] = wKingRank;
18815         if(bKingRank >= 0) for(i=3; i<6; i++) castlingRank[i] = bKingRank;
18816     }
18817
18818     /* set defaults in case FEN is incomplete */
18819     board[EP_STATUS] = EP_UNKNOWN;
18820     board[TOUCHED_W] = board[TOUCHED_B] = 0;
18821     for(i=0; i<nrCastlingRights; i++ ) {
18822         board[CASTLING][i] =
18823             appData.fischerCastling ? NoRights : initialRights[i];
18824     }   /* assume possible unless obviously impossible */
18825     if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
18826     if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
18827     if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
18828                                   && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
18829     if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
18830     if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
18831     if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
18832                                   && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
18833     FENrulePlies = 0;
18834
18835     if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
18836       char *q = p;
18837       int w=0, b=0;
18838       while(isalpha(*p)) {
18839         if(isupper(*p)) w |= 1 << (*p++ - 'A');
18840         if(islower(*p)) b |= 1 << (*p++ - 'a');
18841       }
18842       if(*p == '-') p++;
18843       if(p != q) {
18844         board[TOUCHED_W] = ~w;
18845         board[TOUCHED_B] = ~b;
18846         while(*p == ' ') p++;
18847       }
18848     } else
18849
18850     if(nrCastlingRights) {
18851       int fischer = 0;
18852       if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
18853       if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
18854           /* castling indicator present, so default becomes no castlings */
18855           for(i=0; i<nrCastlingRights; i++ ) {
18856                  board[CASTLING][i] = NoRights;
18857           }
18858       }
18859       while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
18860              (appData.fischerCastling || gameInfo.variant == VariantSChess) &&
18861              ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
18862              ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth)   ) {
18863         int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
18864
18865         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
18866             if(board[castlingRank[5]][i] == BlackKing) blackKingFile = i;
18867             if(board[castlingRank[2]][i] == WhiteKing) whiteKingFile = i;
18868         }
18869         if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
18870             whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
18871         if(whiteKingFile == NoRights || board[castlingRank[2]][whiteKingFile] != WhiteUnicorn
18872                                      && board[castlingRank[2]][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
18873         if(blackKingFile == NoRights || board[castlingRank[5]][blackKingFile] != BlackUnicorn
18874                                      && board[castlingRank[5]][blackKingFile] != BlackKing) blackKingFile = NoRights;
18875         switch(c) {
18876           case'K':
18877               for(i=BOARD_RGHT-1; board[castlingRank[2]][i]!=WhiteRook && i>whiteKingFile; i--);
18878               board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
18879               board[CASTLING][2] = whiteKingFile;
18880               if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
18881               if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18882               if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18883               break;
18884           case'Q':
18885               for(i=BOARD_LEFT;  i<BOARD_RGHT && board[castlingRank[2]][i]!=WhiteRook && i<whiteKingFile; i++);
18886               board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
18887               board[CASTLING][2] = whiteKingFile;
18888               if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
18889               if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18890               if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18891               break;
18892           case'k':
18893               for(i=BOARD_RGHT-1; board[castlingRank[5]][i]!=BlackRook && i>blackKingFile; i--);
18894               board[CASTLING][3] = i != blackKingFile ? i : NoRights;
18895               board[CASTLING][5] = blackKingFile;
18896               if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
18897               if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18898               if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18899               break;
18900           case'q':
18901               for(i=BOARD_LEFT; i<BOARD_RGHT && board[castlingRank[5]][i]!=BlackRook && i<blackKingFile; i++);
18902               board[CASTLING][4] = i != blackKingFile ? i : NoRights;
18903               board[CASTLING][5] = blackKingFile;
18904               if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
18905               if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18906               if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18907           case '-':
18908               break;
18909           default: /* FRC castlings */
18910               if(c >= 'a') { /* black rights */
18911                   if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
18912                   for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18913                     if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
18914                   if(i == BOARD_RGHT) break;
18915                   board[CASTLING][5] = i;
18916                   c -= AAA;
18917                   if(board[BOARD_HEIGHT-1][c] <  BlackPawn ||
18918                      board[BOARD_HEIGHT-1][c] >= BlackKing   ) break;
18919                   if(c > i)
18920                       board[CASTLING][3] = c;
18921                   else
18922                       board[CASTLING][4] = c;
18923               } else { /* white rights */
18924                   if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
18925                   for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18926                     if(board[0][i] == WhiteKing) break;
18927                   if(i == BOARD_RGHT) break;
18928                   board[CASTLING][2] = i;
18929                   c -= AAA - 'a' + 'A';
18930                   if(board[0][c] >= WhiteKing) break;
18931                   if(c > i)
18932                       board[CASTLING][0] = c;
18933                   else
18934                       board[CASTLING][1] = c;
18935               }
18936         }
18937       }
18938       for(i=0; i<nrCastlingRights; i++)
18939         if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
18940       if(gameInfo.variant == VariantSChess)
18941         for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = shuffle ? VIRGIN_W | VIRGIN_B : virgin[i]; // when shuffling assume all virgin
18942       if(fischer && shuffle) appData.fischerCastling = TRUE;
18943     if (appData.debugMode) {
18944         fprintf(debugFP, "FEN castling rights:");
18945         for(i=0; i<nrCastlingRights; i++)
18946         fprintf(debugFP, " %d", board[CASTLING][i]);
18947         fprintf(debugFP, "\n");
18948     }
18949
18950       while(*p==' ') p++;
18951     }
18952
18953     if(shuffle) SetUpShuffle(board, appData.defaultFrcPosition);
18954
18955     /* read e.p. field in games that know e.p. capture */
18956     if(gameInfo.variant != VariantShogi    && gameInfo.variant != VariantXiangqi &&
18957        gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18958        gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
18959       if(*p=='-') {
18960         p++; board[EP_STATUS] = EP_NONE;
18961       } else {
18962          int d, r, c = *p - AAA;
18963
18964          if(c >= BOARD_LEFT && c < BOARD_RGHT) {
18965              p++;
18966              board[EP_STATUS] = board[EP_FILE] = c; r = 0;
18967              if(*p >= '0' && *p <='9') r = board[EP_RANK] = *p++ - ONE;
18968              d = (r < BOARD_HEIGHT << 1 ? 1 : -1); // assume double-push (P next to e.p. square nearer center)
18969              if(board[r+d][c] == EmptySquare) d *= 2; // but if no Pawn there, triple push
18970              board[LAST_TO] = 256*(r + d) + c;
18971              c = *p++ - AAA;
18972              if(c >= BOARD_LEFT && c < BOARD_RGHT) { // mover explicitly mentioned
18973                  if(*p >= '0' && *p <='9') r = board[EP_RANK] = *p++ - ONE;
18974                  board[LAST_TO] = 256*r + c;
18975                  if(!(board[EP_RANK]-r & 1)) board[EP_RANK] |= 128;
18976              }
18977          }
18978       }
18979     }
18980
18981     while(*p == ' ') p++;
18982
18983     board[CHECK_COUNT] = 0; // [HGM] 3check: check-count field
18984     if(sscanf(p, "%d+%d", &i, &j) == 2) {
18985         board[CHECK_COUNT] = i + 256*j;
18986         while(*p && *p != ' ') p++;
18987     }
18988
18989     c = sscanf(p, "%d%*d +%d+%d", &i, &j, &k);
18990     if(c > 0) {
18991         FENrulePlies = i; /* 50-move ply counter */
18992         /* (The move number is still ignored)    */
18993         if(c == 3 && !board[CHECK_COUNT]) board[CHECK_COUNT] = (3 - j) + 256*(3 - k); // SCIDB-style check count
18994     }
18995
18996     return TRUE;
18997 }
18998
18999 void
19000 EditPositionPasteFEN (char *fen)
19001 {
19002   if (fen != NULL) {
19003     Board initial_position;
19004
19005     if (!ParseFEN(initial_position, &blackPlaysFirst, fen, TRUE)) {
19006       DisplayError(_("Bad FEN position in clipboard"), 0);
19007       return ;
19008     } else {
19009       int savedBlackPlaysFirst = blackPlaysFirst;
19010       EditPositionEvent();
19011       blackPlaysFirst = savedBlackPlaysFirst;
19012       CopyBoard(boards[0], initial_position);
19013       initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
19014       EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
19015       DisplayBothClocks();
19016       DrawPosition(FALSE, boards[currentMove]);
19017     }
19018   }
19019 }
19020
19021 static char cseq[12] = "\\   ";
19022
19023 Boolean
19024 set_cont_sequence (char *new_seq)
19025 {
19026     int len;
19027     Boolean ret;
19028
19029     // handle bad attempts to set the sequence
19030         if (!new_seq)
19031                 return 0; // acceptable error - no debug
19032
19033     len = strlen(new_seq);
19034     ret = (len > 0) && (len < sizeof(cseq));
19035     if (ret)
19036       safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
19037     else if (appData.debugMode)
19038       fprintf(debugFP, "Invalid continuation sequence \"%s\"  (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
19039     return ret;
19040 }
19041
19042 /*
19043     reformat a source message so words don't cross the width boundary.  internal
19044     newlines are not removed.  returns the wrapped size (no null character unless
19045     included in source message).  If dest is NULL, only calculate the size required
19046     for the dest buffer.  lp argument indicats line position upon entry, and it's
19047     passed back upon exit.
19048 */
19049 int
19050 wrap (char *dest, char *src, int count, int width, int *lp)
19051 {
19052     int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
19053
19054     cseq_len = strlen(cseq);
19055     old_line = line = *lp;
19056     ansi = len = clen = 0;
19057
19058     for (i=0; i < count; i++)
19059     {
19060         if (src[i] == '\033')
19061             ansi = 1;
19062
19063         // if we hit the width, back up
19064         if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
19065         {
19066             // store i & len in case the word is too long
19067             old_i = i, old_len = len;
19068
19069             // find the end of the last word
19070             while (i && src[i] != ' ' && src[i] != '\n')
19071             {
19072                 i--;
19073                 len--;
19074             }
19075
19076             // word too long?  restore i & len before splitting it
19077             if ((old_i-i+clen) >= width)
19078             {
19079                 i = old_i;
19080                 len = old_len;
19081             }
19082
19083             // extra space?
19084             if (i && src[i-1] == ' ')
19085                 len--;
19086
19087             if (src[i] != ' ' && src[i] != '\n')
19088             {
19089                 i--;
19090                 if (len)
19091                     len--;
19092             }
19093
19094             // now append the newline and continuation sequence
19095             if (dest)
19096                 dest[len] = '\n';
19097             len++;
19098             if (dest)
19099                 strncpy(dest+len, cseq, cseq_len);
19100             len += cseq_len;
19101             line = cseq_len;
19102             clen = cseq_len;
19103             continue;
19104         }
19105
19106         if (dest)
19107             dest[len] = src[i];
19108         len++;
19109         if (!ansi)
19110             line++;
19111         if (src[i] == '\n')
19112             line = 0;
19113         if (src[i] == 'm')
19114             ansi = 0;
19115     }
19116     if (dest && appData.debugMode)
19117     {
19118         fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
19119             count, width, line, len, *lp);
19120         show_bytes(debugFP, src, count);
19121         fprintf(debugFP, "\ndest: ");
19122         show_bytes(debugFP, dest, len);
19123         fprintf(debugFP, "\n");
19124     }
19125     *lp = dest ? line : old_line;
19126
19127     return len;
19128 }
19129
19130 // [HGM] vari: routines for shelving variations
19131 Boolean modeRestore = FALSE;
19132
19133 void
19134 PushInner (int firstMove, int lastMove)
19135 {
19136         int i, j, nrMoves = lastMove - firstMove;
19137
19138         // push current tail of game on stack
19139         savedResult[storedGames] = gameInfo.result;
19140         savedDetails[storedGames] = gameInfo.resultDetails;
19141         gameInfo.resultDetails = NULL;
19142         savedFirst[storedGames] = firstMove;
19143         savedLast [storedGames] = lastMove;
19144         savedFramePtr[storedGames] = framePtr;
19145         framePtr -= nrMoves; // reserve space for the boards
19146         for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
19147             CopyBoard(boards[framePtr+i], boards[firstMove+i]);
19148             for(j=0; j<MOVE_LEN; j++)
19149                 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
19150             for(j=0; j<2*MOVE_LEN; j++)
19151                 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
19152             timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
19153             timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
19154             pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
19155             pvInfoList[firstMove+i-1].depth = 0;
19156             commentList[framePtr+i] = commentList[firstMove+i];
19157             commentList[firstMove+i] = NULL;
19158         }
19159
19160         storedGames++;
19161         forwardMostMove = firstMove; // truncate game so we can start variation
19162 }
19163
19164 void
19165 PushTail (int firstMove, int lastMove)
19166 {
19167         if(appData.icsActive) { // only in local mode
19168                 forwardMostMove = currentMove; // mimic old ICS behavior
19169                 return;
19170         }
19171         if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
19172
19173         PushInner(firstMove, lastMove);
19174         if(storedGames == 1) GreyRevert(FALSE);
19175         if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
19176 }
19177
19178 void
19179 PopInner (Boolean annotate)
19180 {
19181         int i, j, nrMoves;
19182         char buf[8000], moveBuf[20];
19183
19184         ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
19185         storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
19186         nrMoves = savedLast[storedGames] - currentMove;
19187         if(annotate) {
19188                 int cnt = 10;
19189                 if(!WhiteOnMove(currentMove))
19190                   snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
19191                 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
19192                 for(i=currentMove; i<forwardMostMove; i++) {
19193                         if(WhiteOnMove(i))
19194                           snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
19195                         else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
19196                         strcat(buf, moveBuf);
19197                         if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
19198                         if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
19199                 }
19200                 strcat(buf, ")");
19201         }
19202         for(i=1; i<=nrMoves; i++) { // copy last variation back
19203             CopyBoard(boards[currentMove+i], boards[framePtr+i]);
19204             for(j=0; j<MOVE_LEN; j++)
19205                 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
19206             for(j=0; j<2*MOVE_LEN; j++)
19207                 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
19208             timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
19209             timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
19210             pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
19211             if(commentList[currentMove+i]) free(commentList[currentMove+i]);
19212             commentList[currentMove+i] = commentList[framePtr+i];
19213             commentList[framePtr+i] = NULL;
19214         }
19215         if(annotate) AppendComment(currentMove+1, buf, FALSE);
19216         framePtr = savedFramePtr[storedGames];
19217         gameInfo.result = savedResult[storedGames];
19218         if(gameInfo.resultDetails != NULL) {
19219             free(gameInfo.resultDetails);
19220       }
19221         gameInfo.resultDetails = savedDetails[storedGames];
19222         forwardMostMove = currentMove + nrMoves;
19223 }
19224
19225 Boolean
19226 PopTail (Boolean annotate)
19227 {
19228         if(appData.icsActive) return FALSE; // only in local mode
19229         if(!storedGames) return FALSE; // sanity
19230         CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
19231
19232         PopInner(annotate);
19233         if(currentMove < forwardMostMove) ForwardEvent(); else
19234         HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
19235
19236         if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
19237         return TRUE;
19238 }
19239
19240 void
19241 CleanupTail ()
19242 {       // remove all shelved variations
19243         int i;
19244         for(i=0; i<storedGames; i++) {
19245             if(savedDetails[i])
19246                 free(savedDetails[i]);
19247             savedDetails[i] = NULL;
19248         }
19249         for(i=framePtr; i<MAX_MOVES; i++) {
19250                 if(commentList[i]) free(commentList[i]);
19251                 commentList[i] = NULL;
19252         }
19253         framePtr = MAX_MOVES-1;
19254         storedGames = 0;
19255 }
19256
19257 void
19258 LoadVariation (int index, char *text)
19259 {       // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
19260         char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
19261         int level = 0, move;
19262
19263         if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
19264         // first find outermost bracketing variation
19265         while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
19266             if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
19267                 if(*p == '{') wait = '}'; else
19268                 if(*p == '[') wait = ']'; else
19269                 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
19270                 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
19271             }
19272             if(*p == wait) wait = NULLCHAR; // closing ]} found
19273             p++;
19274         }
19275         if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
19276         if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
19277         end[1] = NULLCHAR; // clip off comment beyond variation
19278         ToNrEvent(currentMove-1);
19279         PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
19280         // kludge: use ParsePV() to append variation to game
19281         move = currentMove;
19282         ParsePV(start, TRUE, TRUE);
19283         forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
19284         ClearPremoveHighlights();
19285         CommentPopDown();
19286         ToNrEvent(currentMove+1);
19287 }
19288
19289 int transparency[2];
19290
19291 void
19292 LoadTheme ()
19293 {
19294 #define BUF_SIZ (2*MSG_SIZ)
19295     char *p, *q, buf[BUF_SIZ];
19296     if(engineLine && engineLine[0]) { // a theme was selected from the listbox
19297         snprintf(buf, BUF_SIZ, "-theme %s", engineLine);
19298         ParseArgsFromString(buf);
19299         ActivateTheme(TRUE); // also redo colors
19300         return;
19301     }
19302     p = nickName;
19303     if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
19304     {
19305         int len;
19306         q = appData.themeNames;
19307         snprintf(buf, BUF_SIZ, "\"%s\"", nickName);
19308       if(appData.useBitmaps) {
19309         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt true -lbtf \"%s\"",
19310                 Shorten(appData.liteBackTextureFile));
19311         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dbtf \"%s\" -lbtm %d -dbtm %d",
19312                 Shorten(appData.darkBackTextureFile),
19313                 appData.liteBackTextureMode,
19314                 appData.darkBackTextureMode );
19315       } else {
19316         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt false");
19317       }
19318       if(!appData.useBitmaps || transparency[0]) {
19319         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -lsc %s", Col2Text(2) ); // lightSquareColor
19320       }
19321       if(!appData.useBitmaps || transparency[1]) {
19322         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dsc %s", Col2Text(3) ); // darkSquareColor
19323       }
19324       if(appData.useBorder) {
19325         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub true -border \"%s\"",
19326                 appData.border);
19327       } else {
19328         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub false");
19329       }
19330       if(appData.useFont) {
19331         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
19332                 appData.renderPiecesWithFont,
19333                 appData.fontToPieceTable,
19334                 Col2Text(9),    // appData.fontBackColorWhite
19335                 Col2Text(10) ); // appData.fontForeColorBlack
19336       } else {
19337         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf false");
19338         if(appData.pieceDirectory[0]) {
19339           snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -pid \"%s\"", Shorten(appData.pieceDirectory));
19340           if(appData.trueColors != 2) // 2 is a kludge to suppress this in WinBoard
19341             snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -trueColors %s", appData.trueColors ? "true" : "false");
19342         }
19343         if(!appData.pieceDirectory[0] || !appData.trueColors)
19344           snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -wpc %s -bpc %s",
19345                 Col2Text(0),   // whitePieceColor
19346                 Col2Text(1) ); // blackPieceColor
19347       }
19348       snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -hsc %s -phc %s\n",
19349                 Col2Text(4),   // highlightSquareColor
19350                 Col2Text(5) ); // premoveHighlightColor
19351         appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
19352         if(insert != q) insert[-1] = NULLCHAR;
19353         snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
19354         if(q)   free(q);
19355     }
19356     ActivateTheme(FALSE);
19357 }