Locate engine list in separate file
[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     p = strstr(firstChessProgramNames, currentEngine[n]);
11405     if(!p) { DisplayMessage("saving failed: engine not found in list", ""); return; } // sanity check; engine could be deleted from list after loading
11406     optionSettings = ResendOptions(n ? &second : &first, FALSE);
11407     len = strlen(currentEngine[n]);
11408     q = p + len; *p = 0; // cut list into head and tail piece
11409     s = strstr(currentEngine[n], "firstOptions");
11410     if(s && (s[-1] == '-' || s[-1] == '/') && (s[12] == ' ' || s[12] == '=') && (s[13] == '"' || s[13] == '\'')) {
11411         char *r = s + 14;
11412         while(*r && *r != s[13]) r++;
11413         s[14] = 0; // cut currentEngine into head and tail part, removing old settings
11414         snprintf(buf, MSG_SIZ, "%s%s%s", currentEngine[n], optionSettings, *r ? r : "\""); // synthesize new engine line
11415     } else if(*optionSettings) {
11416         snprintf(buf, MSG_SIZ, "%s -firstOptions \"%s\"", currentEngine[n], optionSettings);
11417     }
11418     ASSIGN(currentEngine[n], buf); // updated engine line
11419     len = p - firstChessProgramNames + strlen(q) + strlen(currentEngine[n]) + 1;
11420     s = malloc(len);
11421     snprintf(s, len, "%s%s%s", firstChessProgramNames, currentEngine[n], q);
11422     FREE(firstChessProgramNames); firstChessProgramNames = s; // new list
11423 }
11424
11425 // following implemented as macro to avoid type limitations
11426 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
11427
11428 void
11429 SwapEngines (int n)
11430 {   // swap settings for first engine and other engine (so far only some selected options)
11431     int h;
11432     char *p;
11433     if(n == 0) return;
11434     SWAP(directory, p)
11435     SWAP(chessProgram, p)
11436     SWAP(isUCI, h)
11437     SWAP(hasOwnBookUCI, h)
11438     SWAP(protocolVersion, h)
11439     SWAP(reuse, h)
11440     SWAP(scoreIsAbsolute, h)
11441     SWAP(timeOdds, h)
11442     SWAP(logo, p)
11443     SWAP(pgnName, p)
11444     SWAP(pvSAN, h)
11445     SWAP(engOptions, p)
11446     SWAP(engInitString, p)
11447     SWAP(computerString, p)
11448     SWAP(features, p)
11449     SWAP(fenOverride, p)
11450     SWAP(NPS, h)
11451     SWAP(accumulateTC, h)
11452     SWAP(drawDepth, h)
11453     SWAP(host, p)
11454     SWAP(pseudo, h)
11455 }
11456
11457 int
11458 GetEngineLine (char *s, int n)
11459 {
11460     int i;
11461     char buf[MSG_SIZ];
11462     extern char *icsNames;
11463     if(!s || !*s) return 0;
11464     NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
11465     for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
11466     if(!mnemonic[i]) return 0;
11467     if(n == 11) return 1; // just testing if there was a match
11468     snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
11469     if(n == 1) SwapEngines(n);
11470     ParseArgsFromString(buf);
11471     if(n == 1) SwapEngines(n);
11472     if(n < 2) { ASSIGN(currentEngine[n], command[i]); }
11473     if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
11474         SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
11475         ParseArgsFromString(buf);
11476     }
11477     return 1;
11478 }
11479
11480 int
11481 SetPlayer (int player, char *p)
11482 {   // [HGM] find the engine line of the partcipant given by number, and parse its options.
11483     int i;
11484     char buf[MSG_SIZ], *engineName;
11485     for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
11486     engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
11487     for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
11488     if(mnemonic[i]) {
11489         snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
11490         ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
11491         appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
11492         ParseArgsFromString(buf);
11493     } else { // no engine with this nickname is installed!
11494         snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
11495         ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
11496         matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
11497         ModeHighlight();
11498         DisplayError(buf, 0);
11499         return 0;
11500     }
11501     free(engineName);
11502     return i;
11503 }
11504
11505 char *recentEngines;
11506
11507 void
11508 RecentEngineEvent (int nr)
11509 {
11510     int n;
11511 //    SwapEngines(1); // bump first to second
11512 //    ReplaceEngine(&second, 1); // and load it there
11513     NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11514     n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
11515     if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
11516         ReplaceEngine(&first, 0);
11517         FloatToFront(&appData.recentEngineList, command[n]);
11518         ASSIGN(currentEngine[0], command[n]);
11519     }
11520 }
11521
11522 int
11523 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
11524 {   // determine players from game number
11525     int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
11526
11527     if(appData.tourneyType == 0) {
11528         roundsPerCycle = (nPlayers - 1) | 1;
11529         pairingsPerRound = nPlayers / 2;
11530     } else if(appData.tourneyType > 0) {
11531         roundsPerCycle = nPlayers - appData.tourneyType;
11532         pairingsPerRound = appData.tourneyType;
11533     }
11534     gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
11535     gamesPerCycle = gamesPerRound * roundsPerCycle;
11536     appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
11537     curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
11538     curRound = nr / gamesPerRound; nr %= gamesPerRound;
11539     curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
11540     matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
11541     roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
11542
11543     if(appData.cycleSync) *syncInterval = gamesPerCycle;
11544     if(appData.roundSync) *syncInterval = gamesPerRound;
11545
11546     if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
11547
11548     if(appData.tourneyType == 0) {
11549         if(curPairing == (nPlayers-1)/2 ) {
11550             *whitePlayer = curRound;
11551             *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
11552         } else {
11553             *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
11554             if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
11555             *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
11556             if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
11557         }
11558     } else if(appData.tourneyType > 1) {
11559         *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
11560         *whitePlayer = curRound + appData.tourneyType;
11561     } else if(appData.tourneyType > 0) {
11562         *whitePlayer = curPairing;
11563         *blackPlayer = curRound + appData.tourneyType;
11564     }
11565
11566     // take care of white/black alternation per round.
11567     // For cycles and games this is already taken care of by default, derived from matchGame!
11568     return curRound & 1;
11569 }
11570
11571 int
11572 NextTourneyGame (int nr, int *swapColors)
11573 {   // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
11574     char *p, *q;
11575     int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
11576     FILE *tf;
11577     if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
11578     tf = fopen(appData.tourneyFile, "r");
11579     if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
11580     ParseArgsFromFile(tf); fclose(tf);
11581     InitTimeControls(); // TC might be altered from tourney file
11582
11583     nPlayers = CountPlayers(appData.participants); // count participants
11584     if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
11585     *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
11586
11587     if(syncInterval) {
11588         p = q = appData.results;
11589         while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
11590         if(firstBusy/syncInterval < (nextGame/syncInterval)) {
11591             DisplayMessage(_("Waiting for other game(s)"),"");
11592             waitingForGame = TRUE;
11593             ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
11594             return 0;
11595         }
11596         waitingForGame = FALSE;
11597     }
11598
11599     if(appData.tourneyType < 0) {
11600         if(nr>=0 && !pairingReceived) {
11601             char buf[1<<16];
11602             if(pairing.pr == NoProc) {
11603                 if(!appData.pairingEngine[0]) {
11604                     DisplayFatalError(_("No pairing engine specified"), 0, 1);
11605                     return 0;
11606                 }
11607                 StartChessProgram(&pairing); // starts the pairing engine
11608             }
11609             snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
11610             SendToProgram(buf, &pairing);
11611             snprintf(buf, 1<<16, "pairing %d\n", nr+1);
11612             SendToProgram(buf, &pairing);
11613             return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
11614         }
11615         pairingReceived = 0;                              // ... so we continue here
11616         *swapColors = 0;
11617         appData.matchGames = appData.tourneyCycles * syncInterval - 1;
11618         whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
11619         matchGame = 1; roundNr = nr / syncInterval + 1;
11620     }
11621
11622     if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
11623
11624     // redefine engines, engine dir, etc.
11625     NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11626     if(first.pr == NoProc) {
11627       if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
11628       InitEngine(&first, 0);  // initialize ChessProgramStates based on new settings.
11629     }
11630     if(second.pr == NoProc) {
11631       SwapEngines(1);
11632       if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
11633       SwapEngines(1);         // and make that valid for second engine by swapping
11634       InitEngine(&second, 1);
11635     }
11636     CommonEngineInit();     // after this TwoMachinesEvent will create correct engine processes
11637     UpdateLogos(FALSE);     // leave display to ModeHiglight()
11638     return OK;
11639 }
11640
11641 void
11642 NextMatchGame ()
11643 {   // performs game initialization that does not invoke engines, and then tries to start the game
11644     int res, firstWhite, swapColors = 0;
11645     if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
11646     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
11647         char buf[MSG_SIZ];
11648         snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
11649         if(strcmp(buf, currentDebugFile)) { // name has changed
11650             FILE *f = fopen(buf, "w");
11651             if(f) { // if opening the new file failed, just keep using the old one
11652                 ASSIGN(currentDebugFile, buf);
11653                 fclose(debugFP);
11654                 debugFP = f;
11655             }
11656             if(appData.serverFileName) {
11657                 if(serverFP) fclose(serverFP);
11658                 serverFP = fopen(appData.serverFileName, "w");
11659                 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
11660                 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
11661             }
11662         }
11663     }
11664     firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
11665     firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
11666     first.twoMachinesColor =  firstWhite ? "white\n" : "black\n";   // perform actual color assignement
11667     second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11668     appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
11669     if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
11670     Reset(FALSE, first.pr != NoProc);
11671     res = LoadGameOrPosition(matchGame); // setup game
11672     appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
11673     if(!res) return; // abort when bad game/pos file
11674     if(appData.epd) {// in EPD mode we make sure first engine is to move
11675         firstWhite = !(forwardMostMove & 1);
11676         first.twoMachinesColor =  firstWhite ? "white\n" : "black\n";   // perform actual color assignement
11677         second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11678     }
11679     TwoMachinesEvent();
11680 }
11681
11682 void
11683 UserAdjudicationEvent (int result)
11684 {
11685     ChessMove gameResult = GameIsDrawn;
11686
11687     if( result > 0 ) {
11688         gameResult = WhiteWins;
11689     }
11690     else if( result < 0 ) {
11691         gameResult = BlackWins;
11692     }
11693
11694     if( gameMode == TwoMachinesPlay ) {
11695         GameEnds( gameResult, "User adjudication", GE_XBOARD );
11696     }
11697 }
11698
11699
11700 // [HGM] save: calculate checksum of game to make games easily identifiable
11701 int
11702 StringCheckSum (char *s)
11703 {
11704         int i = 0;
11705         if(s==NULL) return 0;
11706         while(*s) i = i*259 + *s++;
11707         return i;
11708 }
11709
11710 int
11711 GameCheckSum ()
11712 {
11713         int i, sum=0;
11714         for(i=backwardMostMove; i<forwardMostMove; i++) {
11715                 sum += pvInfoList[i].depth;
11716                 sum += StringCheckSum(parseList[i]);
11717                 sum += StringCheckSum(commentList[i]);
11718                 sum *= 261;
11719         }
11720         if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
11721         return sum + StringCheckSum(commentList[i]);
11722 } // end of save patch
11723
11724 void
11725 GameEnds (ChessMove result, char *resultDetails, int whosays)
11726 {
11727     GameMode nextGameMode;
11728     int isIcsGame;
11729     char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
11730
11731     if(endingGame) return; /* [HGM] crash: forbid recursion */
11732     endingGame = 1;
11733     if(twoBoards) { // [HGM] dual: switch back to one board
11734         twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
11735         DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
11736     }
11737     if (appData.debugMode) {
11738       fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
11739               result, resultDetails ? resultDetails : "(null)", whosays);
11740     }
11741
11742     fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move the user is entering. // [HGM] lion
11743
11744     if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
11745
11746     if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
11747         /* If we are playing on ICS, the server decides when the
11748            game is over, but the engine can offer to draw, claim
11749            a draw, or resign.
11750          */
11751 #if ZIPPY
11752         if (appData.zippyPlay && first.initDone) {
11753             if (result == GameIsDrawn) {
11754                 /* In case draw still needs to be claimed */
11755                 SendToICS(ics_prefix);
11756                 SendToICS("draw\n");
11757             } else if (StrCaseStr(resultDetails, "resign")) {
11758                 SendToICS(ics_prefix);
11759                 SendToICS("resign\n");
11760             }
11761         }
11762 #endif
11763         endingGame = 0; /* [HGM] crash */
11764         return;
11765     }
11766
11767     /* If we're loading the game from a file, stop */
11768     if (whosays == GE_FILE) {
11769       (void) StopLoadGameTimer();
11770       gameFileFP = NULL;
11771     }
11772
11773     /* Cancel draw offers */
11774     first.offeredDraw = second.offeredDraw = 0;
11775
11776     /* If this is an ICS game, only ICS can really say it's done;
11777        if not, anyone can. */
11778     isIcsGame = (gameMode == IcsPlayingWhite ||
11779                  gameMode == IcsPlayingBlack ||
11780                  gameMode == IcsObserving    ||
11781                  gameMode == IcsExamining);
11782
11783     if (!isIcsGame || whosays == GE_ICS) {
11784         /* OK -- not an ICS game, or ICS said it was done */
11785         StopClocks();
11786         if (!isIcsGame && !appData.noChessProgram)
11787           SetUserThinkingEnables();
11788
11789         /* [HGM] if a machine claims the game end we verify this claim */
11790         if(gameMode == TwoMachinesPlay && appData.testClaims) {
11791             if(appData.testLegality && whosays >= GE_ENGINE1 ) {
11792                 char claimer;
11793                 ChessMove trueResult = (ChessMove) -1;
11794
11795                 claimer = whosays == GE_ENGINE1 ?      /* color of claimer */
11796                                             first.twoMachinesColor[0] :
11797                                             second.twoMachinesColor[0] ;
11798
11799                 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
11800                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
11801                     /* [HGM] verify: engine mate claims accepted if they were flagged */
11802                     trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
11803                 } else
11804                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
11805                     /* [HGM] verify: engine mate claims accepted if they were flagged */
11806                     trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
11807                 } else
11808                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
11809                     trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
11810                 }
11811
11812                 // now verify win claims, but not in drop games, as we don't understand those yet
11813                 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11814                                                  || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
11815                     (result == WhiteWins && claimer == 'w' ||
11816                      result == BlackWins && claimer == 'b'   ) ) { // case to verify: engine claims own win
11817                       if (appData.debugMode) {
11818                         fprintf(debugFP, "result=%d sp=%d move=%d\n",
11819                                 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
11820                       }
11821                       if(result != trueResult) {
11822                         snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
11823                               result = claimer == 'w' ? BlackWins : WhiteWins;
11824                               resultDetails = buf;
11825                       }
11826                 } else
11827                 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
11828                     && (forwardMostMove <= backwardMostMove ||
11829                         (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
11830                         (claimer=='b')==(forwardMostMove&1))
11831                                                                                   ) {
11832                       /* [HGM] verify: draws that were not flagged are false claims */
11833                   snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
11834                       result = claimer == 'w' ? BlackWins : WhiteWins;
11835                       resultDetails = buf;
11836                 }
11837                 /* (Claiming a loss is accepted no questions asked!) */
11838             } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
11839                 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
11840                 result = GameUnfinished;
11841                 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
11842             }
11843             /* [HGM] bare: don't allow bare King to win */
11844             if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11845                                             || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
11846                && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
11847                && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
11848                && result != GameIsDrawn)
11849             {   int i, j, k=0, oppoKings = 0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
11850                 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
11851                         int p = (int)boards[forwardMostMove][i][j] - color;
11852                         if(p >= 0 && p <= (int)WhiteKing) k++;
11853                         oppoKings += (p + color == WhiteKing + BlackPawn - color);
11854                 }
11855                 if (appData.debugMode) {
11856                      fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
11857                         result, resultDetails ? resultDetails : "(null)", whosays, k, color);
11858                 }
11859                 if(k <= 1 && oppoKings > 0) { // the latter needed in Atomic, where bare K wins if opponent King already destroyed
11860                         result = GameIsDrawn;
11861                         snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
11862                         resultDetails = buf;
11863                 }
11864             }
11865         }
11866
11867
11868         if(serverMoves != NULL && !loadFlag) { char c = '=';
11869             if(result==WhiteWins) c = '+';
11870             if(result==BlackWins) c = '-';
11871             if(resultDetails != NULL)
11872                 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
11873         }
11874         if (resultDetails != NULL) {
11875             gameInfo.result = result;
11876             gameInfo.resultDetails = StrSave(resultDetails);
11877
11878             /* display last move only if game was not loaded from file */
11879             if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
11880                 DisplayMove(currentMove - 1);
11881
11882             if (forwardMostMove != 0) {
11883                 if (gameMode != PlayFromGameFile && gameMode != EditGame
11884                     && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
11885                                                                 ) {
11886                     if (*appData.saveGameFile != NULLCHAR) {
11887                         if(result == GameUnfinished && matchMode && *appData.tourneyFile)
11888                             AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
11889                         else
11890                         SaveGameToFile(appData.saveGameFile, TRUE);
11891                     } else if (appData.autoSaveGames) {
11892                         if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
11893                     }
11894                     if (*appData.savePositionFile != NULLCHAR) {
11895                         SavePositionToFile(appData.savePositionFile);
11896                     }
11897                     AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
11898                 }
11899             }
11900
11901             /* Tell program how game ended in case it is learning */
11902             /* [HGM] Moved this to after saving the PGN, just in case */
11903             /* engine died and we got here through time loss. In that */
11904             /* case we will get a fatal error writing the pipe, which */
11905             /* would otherwise lose us the PGN.                       */
11906             /* [HGM] crash: not needed anymore, but doesn't hurt;     */
11907             /* output during GameEnds should never be fatal anymore   */
11908             if (gameMode == MachinePlaysWhite ||
11909                 gameMode == MachinePlaysBlack ||
11910                 gameMode == TwoMachinesPlay ||
11911                 gameMode == IcsPlayingWhite ||
11912                 gameMode == IcsPlayingBlack ||
11913                 gameMode == BeginningOfGame) {
11914                 char buf[MSG_SIZ];
11915                 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
11916                         resultDetails);
11917                 if (first.pr != NoProc) {
11918                     SendToProgram(buf, &first);
11919                 }
11920                 if (second.pr != NoProc &&
11921                     gameMode == TwoMachinesPlay) {
11922                     SendToProgram(buf, &second);
11923                 }
11924             }
11925         }
11926
11927         if (appData.icsActive) {
11928             if (appData.quietPlay &&
11929                 (gameMode == IcsPlayingWhite ||
11930                  gameMode == IcsPlayingBlack)) {
11931                 SendToICS(ics_prefix);
11932                 SendToICS("set shout 1\n");
11933             }
11934             nextGameMode = IcsIdle;
11935             ics_user_moved = FALSE;
11936             /* clean up premove.  It's ugly when the game has ended and the
11937              * premove highlights are still on the board.
11938              */
11939             if (gotPremove) {
11940               gotPremove = FALSE;
11941               ClearPremoveHighlights();
11942               DrawPosition(FALSE, boards[currentMove]);
11943             }
11944             if (whosays == GE_ICS) {
11945                 switch (result) {
11946                 case WhiteWins:
11947                     if (gameMode == IcsPlayingWhite)
11948                         PlayIcsWinSound();
11949                     else if(gameMode == IcsPlayingBlack)
11950                         PlayIcsLossSound();
11951                     break;
11952                 case BlackWins:
11953                     if (gameMode == IcsPlayingBlack)
11954                         PlayIcsWinSound();
11955                     else if(gameMode == IcsPlayingWhite)
11956                         PlayIcsLossSound();
11957                     break;
11958                 case GameIsDrawn:
11959                     PlayIcsDrawSound();
11960                     break;
11961                 default:
11962                     PlayIcsUnfinishedSound();
11963                 }
11964             }
11965             if(appData.quitNext) { ExitEvent(0); return; }
11966         } else if (gameMode == EditGame ||
11967                    gameMode == PlayFromGameFile ||
11968                    gameMode == AnalyzeMode ||
11969                    gameMode == AnalyzeFile) {
11970             nextGameMode = gameMode;
11971         } else {
11972             nextGameMode = EndOfGame;
11973         }
11974         pausing = FALSE;
11975         ModeHighlight();
11976     } else {
11977         nextGameMode = gameMode;
11978     }
11979
11980     if (appData.noChessProgram) {
11981         gameMode = nextGameMode;
11982         ModeHighlight();
11983         endingGame = 0; /* [HGM] crash */
11984         return;
11985     }
11986
11987     if (first.reuse) {
11988         /* Put first chess program into idle state */
11989         if (first.pr != NoProc &&
11990             (gameMode == MachinePlaysWhite ||
11991              gameMode == MachinePlaysBlack ||
11992              gameMode == TwoMachinesPlay ||
11993              gameMode == IcsPlayingWhite ||
11994              gameMode == IcsPlayingBlack ||
11995              gameMode == BeginningOfGame)) {
11996             SendToProgram("force\n", &first);
11997             if (first.usePing) {
11998               char buf[MSG_SIZ];
11999               snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
12000               SendToProgram(buf, &first);
12001             }
12002         }
12003     } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
12004         /* Kill off first chess program */
12005         if (first.isr != NULL)
12006           RemoveInputSource(first.isr);
12007         first.isr = NULL;
12008
12009         if (first.pr != NoProc) {
12010             ExitAnalyzeMode();
12011             DoSleep( appData.delayBeforeQuit );
12012             SendToProgram("quit\n", &first);
12013             DestroyChildProcess(first.pr, 4 + first.useSigterm);
12014             first.reload = TRUE;
12015         }
12016         first.pr = NoProc;
12017     }
12018     if (second.reuse) {
12019         /* Put second chess program into idle state */
12020         if (second.pr != NoProc &&
12021             gameMode == TwoMachinesPlay) {
12022             SendToProgram("force\n", &second);
12023             if (second.usePing) {
12024               char buf[MSG_SIZ];
12025               snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
12026               SendToProgram(buf, &second);
12027             }
12028         }
12029     } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
12030         /* Kill off second chess program */
12031         if (second.isr != NULL)
12032           RemoveInputSource(second.isr);
12033         second.isr = NULL;
12034
12035         if (second.pr != NoProc) {
12036             DoSleep( appData.delayBeforeQuit );
12037             SendToProgram("quit\n", &second);
12038             DestroyChildProcess(second.pr, 4 + second.useSigterm);
12039             second.reload = TRUE;
12040         }
12041         second.pr = NoProc;
12042     }
12043
12044     if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
12045         char resChar = '=';
12046         switch (result) {
12047         case WhiteWins:
12048           resChar = '+';
12049           if (first.twoMachinesColor[0] == 'w') {
12050             first.matchWins++;
12051           } else {
12052             second.matchWins++;
12053           }
12054           break;
12055         case BlackWins:
12056           resChar = '-';
12057           if (first.twoMachinesColor[0] == 'b') {
12058             first.matchWins++;
12059           } else {
12060             second.matchWins++;
12061           }
12062           break;
12063         case GameUnfinished:
12064           resChar = ' ';
12065         default:
12066           break;
12067         }
12068
12069         if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
12070         if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
12071             if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
12072             ReserveGame(nextGame, resChar); // sets nextGame
12073             if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
12074             else ranking = strdup("busy"); //suppress popup when aborted but not finished
12075         } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
12076
12077         if (nextGame <= appData.matchGames && !abortMatch) {
12078             gameMode = nextGameMode;
12079             matchGame = nextGame; // this will be overruled in tourney mode!
12080             GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
12081             ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
12082             endingGame = 0; /* [HGM] crash */
12083             return;
12084         } else {
12085             gameMode = nextGameMode;
12086             if(appData.epd) {
12087                 snprintf(buf, MSG_SIZ, "-------------------------------------- ");
12088                 OutputKibitz(2, buf);
12089                 snprintf(buf, MSG_SIZ, _("Average solving time %4.2f sec (total time %4.2f sec) "), totalTime/(100.*first.matchWins), totalTime/100.);
12090                 OutputKibitz(2, buf);
12091                 snprintf(buf, MSG_SIZ, _("%d avoid-moves played "), second.matchWins);
12092                 if(second.matchWins) OutputKibitz(2, buf);
12093                 snprintf(buf, MSG_SIZ, _("Solved %d out of %d (%3.1f%%) "), first.matchWins, nextGame-1, first.matchWins*100./(nextGame-1));
12094                 OutputKibitz(2, buf);
12095             }
12096             snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
12097                      first.tidy, second.tidy,
12098                      first.matchWins, second.matchWins,
12099                      appData.matchGames - (first.matchWins + second.matchWins));
12100             if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
12101             if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
12102             popupRequested++; // [HGM] crash: postpone to after resetting endingGame
12103             if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
12104                 first.twoMachinesColor = "black\n";
12105                 second.twoMachinesColor = "white\n";
12106             } else {
12107                 first.twoMachinesColor = "white\n";
12108                 second.twoMachinesColor = "black\n";
12109             }
12110         }
12111     }
12112     if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
12113         !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
12114       ExitAnalyzeMode();
12115     gameMode = nextGameMode;
12116     ModeHighlight();
12117     endingGame = 0;  /* [HGM] crash */
12118     if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
12119         if(matchMode == TRUE) { // match through command line: exit with or without popup
12120             if(ranking) {
12121                 ToNrEvent(forwardMostMove);
12122                 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
12123                 else ExitEvent(0);
12124             } else DisplayFatalError(buf, 0, 0);
12125         } else { // match through menu; just stop, with or without popup
12126             matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
12127             ModeHighlight();
12128             if(ranking){
12129                 if(strcmp(ranking, "busy")) DisplayNote(ranking);
12130             } else DisplayNote(buf);
12131       }
12132       if(ranking) free(ranking);
12133     }
12134 }
12135
12136 /* Assumes program was just initialized (initString sent).
12137    Leaves program in force mode. */
12138 void
12139 FeedMovesToProgram (ChessProgramState *cps, int upto)
12140 {
12141     int i;
12142
12143     if (appData.debugMode)
12144       fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
12145               startedFromSetupPosition ? "position and " : "",
12146               backwardMostMove, upto, cps->which);
12147     if(currentlyInitializedVariant != gameInfo.variant) {
12148       char buf[MSG_SIZ];
12149         // [HGM] variantswitch: make engine aware of new variant
12150         if(!SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
12151                              gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, ""))
12152                 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
12153         snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
12154         SendToProgram(buf, cps);
12155         currentlyInitializedVariant = gameInfo.variant;
12156     }
12157     SendToProgram("force\n", cps);
12158     if (startedFromSetupPosition) {
12159         SendBoard(cps, backwardMostMove);
12160     if (appData.debugMode) {
12161         fprintf(debugFP, "feedMoves\n");
12162     }
12163     }
12164     for (i = backwardMostMove; i < upto; i++) {
12165         SendMoveToProgram(i, cps);
12166     }
12167 }
12168
12169
12170 int
12171 ResurrectChessProgram ()
12172 {
12173      /* The chess program may have exited.
12174         If so, restart it and feed it all the moves made so far. */
12175     static int doInit = 0;
12176
12177     if (appData.noChessProgram) return 1;
12178
12179     if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
12180         if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
12181         if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
12182         doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
12183     } else {
12184         if (first.pr != NoProc) return 1;
12185         StartChessProgram(&first);
12186     }
12187     InitChessProgram(&first, FALSE);
12188     FeedMovesToProgram(&first, currentMove);
12189
12190     if (!first.sendTime) {
12191         /* can't tell gnuchess what its clock should read,
12192            so we bow to its notion. */
12193         ResetClocks();
12194         timeRemaining[0][currentMove] = whiteTimeRemaining;
12195         timeRemaining[1][currentMove] = blackTimeRemaining;
12196     }
12197
12198     if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
12199                 appData.icsEngineAnalyze) && first.analysisSupport) {
12200       SendToProgram("analyze\n", &first);
12201       first.analyzing = TRUE;
12202     }
12203     return 1;
12204 }
12205
12206 /*
12207  * Button procedures
12208  */
12209 void
12210 Reset (int redraw, int init)
12211 {
12212     int i;
12213
12214     if (appData.debugMode) {
12215         fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
12216                 redraw, init, gameMode);
12217     }
12218     pieceDefs = FALSE; // [HGM] gen: reset engine-defined piece moves
12219     deadRanks = 0; // assume entire board is used
12220     handSize = 0;
12221     for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; }
12222     CleanupTail(); // [HGM] vari: delete any stored variations
12223     CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
12224     pausing = pauseExamInvalid = FALSE;
12225     startedFromSetupPosition = blackPlaysFirst = FALSE;
12226     firstMove = TRUE;
12227     whiteFlag = blackFlag = FALSE;
12228     userOfferedDraw = FALSE;
12229     hintRequested = bookRequested = FALSE;
12230     first.maybeThinking = FALSE;
12231     second.maybeThinking = FALSE;
12232     first.bookSuspend = FALSE; // [HGM] book
12233     second.bookSuspend = FALSE;
12234     thinkOutput[0] = NULLCHAR;
12235     lastHint[0] = NULLCHAR;
12236     ClearGameInfo(&gameInfo);
12237     gameInfo.variant = StringToVariant(appData.variant);
12238     if(gameInfo.variant == VariantNormal && strcmp(appData.variant, "normal")) {
12239         gameInfo.variant = VariantUnknown;
12240         strncpy(engineVariant, appData.variant, MSG_SIZ);
12241     }
12242     ics_user_moved = ics_clock_paused = FALSE;
12243     ics_getting_history = H_FALSE;
12244     ics_gamenum = -1;
12245     white_holding[0] = black_holding[0] = NULLCHAR;
12246     ClearProgramStats();
12247     opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
12248
12249     ResetFrontEnd();
12250     ClearHighlights();
12251     flipView = appData.flipView;
12252     ClearPremoveHighlights();
12253     gotPremove = FALSE;
12254     alarmSounded = FALSE;
12255     killX = killY = kill2X = kill2Y = -1; // [HGM] lion
12256
12257     GameEnds(EndOfFile, NULL, GE_PLAYER);
12258     if(appData.serverMovesName != NULL) {
12259         /* [HGM] prepare to make moves file for broadcasting */
12260         clock_t t = clock();
12261         if(serverMoves != NULL) fclose(serverMoves);
12262         serverMoves = fopen(appData.serverMovesName, "r");
12263         if(serverMoves != NULL) {
12264             fclose(serverMoves);
12265             /* delay 15 sec before overwriting, so all clients can see end */
12266             while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
12267         }
12268         serverMoves = fopen(appData.serverMovesName, "w");
12269     }
12270
12271     ExitAnalyzeMode();
12272     gameMode = BeginningOfGame;
12273     ModeHighlight();
12274     if(appData.icsActive) gameInfo.variant = VariantNormal;
12275     currentMove = forwardMostMove = backwardMostMove = 0;
12276     MarkTargetSquares(1);
12277     InitPosition(redraw);
12278     for (i = 0; i < MAX_MOVES; i++) {
12279         if (commentList[i] != NULL) {
12280             free(commentList[i]);
12281             commentList[i] = NULL;
12282         }
12283     }
12284     ResetClocks();
12285     timeRemaining[0][0] = whiteTimeRemaining;
12286     timeRemaining[1][0] = blackTimeRemaining;
12287
12288     if (first.pr == NoProc) {
12289         StartChessProgram(&first);
12290     }
12291     if (init) {
12292             InitChessProgram(&first, startedFromSetupPosition);
12293     }
12294     DisplayTitle("");
12295     DisplayMessage("", "");
12296     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12297     lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
12298     ClearMap();        // [HGM] exclude: invalidate map
12299 }
12300
12301 void
12302 AutoPlayGameLoop ()
12303 {
12304     for (;;) {
12305         if (!AutoPlayOneMove())
12306           return;
12307         if (matchMode || appData.timeDelay == 0)
12308           continue;
12309         if (appData.timeDelay < 0)
12310           return;
12311         StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
12312         break;
12313     }
12314 }
12315
12316 void
12317 AnalyzeNextGame()
12318 {
12319     ReloadGame(1); // next game
12320 }
12321
12322 int
12323 AutoPlayOneMove ()
12324 {
12325     int fromX, fromY, toX, toY;
12326
12327     if (appData.debugMode) {
12328       fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
12329     }
12330
12331     if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
12332       return FALSE;
12333
12334     if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
12335       pvInfoList[currentMove].depth = programStats.depth;
12336       pvInfoList[currentMove].score = programStats.score;
12337       pvInfoList[currentMove].time  = 0;
12338       if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
12339       else { // append analysis of final position as comment
12340         char buf[MSG_SIZ];
12341         snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
12342         AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
12343       }
12344       programStats.depth = 0;
12345     }
12346
12347     if (currentMove >= forwardMostMove) {
12348       if(gameMode == AnalyzeFile) {
12349           if(appData.loadGameIndex == -1) {
12350             GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
12351           ScheduleDelayedEvent(AnalyzeNextGame, 10);
12352           } else {
12353           ExitAnalyzeMode(); SendToProgram("force\n", &first);
12354         }
12355       }
12356 //      gameMode = EndOfGame;
12357 //      ModeHighlight();
12358
12359       /* [AS] Clear current move marker at the end of a game */
12360       /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
12361
12362       return FALSE;
12363     }
12364
12365     toX = moveList[currentMove][2] - AAA;
12366     toY = moveList[currentMove][3] - ONE;
12367
12368     if (moveList[currentMove][1] == '@') {
12369         if (appData.highlightLastMove) {
12370             SetHighlights(-1, -1, toX, toY);
12371         }
12372     } else {
12373         fromX = moveList[currentMove][0] - AAA;
12374         fromY = moveList[currentMove][1] - ONE;
12375
12376         HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
12377
12378         if(moveList[currentMove][4] == ';') { // multi-leg
12379             killX = moveList[currentMove][5] - AAA;
12380             killY = moveList[currentMove][6] - ONE;
12381         }
12382         AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12383         killX = killY = -1;
12384
12385         if (appData.highlightLastMove) {
12386             SetHighlights(fromX, fromY, toX, toY);
12387         }
12388     }
12389     DisplayMove(currentMove);
12390     SendMoveToProgram(currentMove++, &first);
12391     DisplayBothClocks();
12392     DrawPosition(FALSE, boards[currentMove]);
12393     // [HGM] PV info: always display, routine tests if empty
12394     DisplayComment(currentMove - 1, commentList[currentMove]);
12395     return TRUE;
12396 }
12397
12398
12399 int
12400 LoadGameOneMove (ChessMove readAhead)
12401 {
12402     int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
12403     char promoChar = NULLCHAR;
12404     ChessMove moveType;
12405     char move[MSG_SIZ];
12406     char *p, *q;
12407
12408     if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
12409         gameMode != AnalyzeMode && gameMode != Training) {
12410         gameFileFP = NULL;
12411         return FALSE;
12412     }
12413
12414     yyboardindex = forwardMostMove;
12415     if (readAhead != EndOfFile) {
12416       moveType = readAhead;
12417     } else {
12418       if (gameFileFP == NULL)
12419           return FALSE;
12420       moveType = (ChessMove) Myylex();
12421     }
12422
12423     done = FALSE;
12424     switch (moveType) {
12425       case Comment:
12426         if (appData.debugMode)
12427           fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12428         p = yy_text;
12429
12430         /* append the comment but don't display it */
12431         AppendComment(currentMove, p, FALSE);
12432         return TRUE;
12433
12434       case WhiteCapturesEnPassant:
12435       case BlackCapturesEnPassant:
12436       case WhitePromotion:
12437       case BlackPromotion:
12438       case WhiteNonPromotion:
12439       case BlackNonPromotion:
12440       case NormalMove:
12441       case FirstLeg:
12442       case WhiteKingSideCastle:
12443       case WhiteQueenSideCastle:
12444       case BlackKingSideCastle:
12445       case BlackQueenSideCastle:
12446       case WhiteKingSideCastleWild:
12447       case WhiteQueenSideCastleWild:
12448       case BlackKingSideCastleWild:
12449       case BlackQueenSideCastleWild:
12450       /* PUSH Fabien */
12451       case WhiteHSideCastleFR:
12452       case WhiteASideCastleFR:
12453       case BlackHSideCastleFR:
12454       case BlackASideCastleFR:
12455       /* POP Fabien */
12456         if (appData.debugMode)
12457           fprintf(debugFP, "Parsed %s into %s virgin=%x,%x\n", yy_text, currentMoveString, boards[forwardMostMove][TOUCHED_W], boards[forwardMostMove][TOUCHED_B]);
12458         fromX = currentMoveString[0] - AAA;
12459         fromY = currentMoveString[1] - ONE;
12460         toX = currentMoveString[2] - AAA;
12461         toY = currentMoveString[3] - ONE;
12462         promoChar = currentMoveString[4];
12463         if(promoChar == ';') promoChar = currentMoveString[7];
12464         break;
12465
12466       case WhiteDrop:
12467       case BlackDrop:
12468         if (appData.debugMode)
12469           fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
12470         fromX = moveType == WhiteDrop ?
12471           (int) CharToPiece(ToUpper(currentMoveString[0])) :
12472         (int) CharToPiece(ToLower(currentMoveString[0]));
12473         fromY = DROP_RANK;
12474         toX = currentMoveString[2] - AAA;
12475         toY = currentMoveString[3] - ONE;
12476         break;
12477
12478       case WhiteWins:
12479       case BlackWins:
12480       case GameIsDrawn:
12481       case GameUnfinished:
12482         if (appData.debugMode)
12483           fprintf(debugFP, "Parsed game end: %s\n", yy_text);
12484         p = strchr(yy_text, '{');
12485         if (p == NULL) p = strchr(yy_text, '(');
12486         if (p == NULL) {
12487             p = yy_text;
12488             if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
12489         } else {
12490             q = strchr(p, *p == '{' ? '}' : ')');
12491             if (q != NULL) *q = NULLCHAR;
12492             p++;
12493         }
12494         while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
12495         GameEnds(moveType, p, GE_FILE);
12496         done = TRUE;
12497         if (cmailMsgLoaded) {
12498             ClearHighlights();
12499             flipView = WhiteOnMove(currentMove);
12500             if (moveType == GameUnfinished) flipView = !flipView;
12501             if (appData.debugMode)
12502               fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
12503         }
12504         break;
12505
12506       case EndOfFile:
12507         if (appData.debugMode)
12508           fprintf(debugFP, "Parser hit end of file\n");
12509         switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12510           case MT_NONE:
12511           case MT_CHECK:
12512             break;
12513           case MT_CHECKMATE:
12514           case MT_STAINMATE:
12515             if (WhiteOnMove(currentMove)) {
12516                 GameEnds(BlackWins, "Black mates", GE_FILE);
12517             } else {
12518                 GameEnds(WhiteWins, "White mates", GE_FILE);
12519             }
12520             break;
12521           case MT_STALEMATE:
12522             GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12523             break;
12524         }
12525         done = TRUE;
12526         break;
12527
12528       case MoveNumberOne:
12529         if (lastLoadGameStart == GNUChessGame) {
12530             /* GNUChessGames have numbers, but they aren't move numbers */
12531             if (appData.debugMode)
12532               fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12533                       yy_text, (int) moveType);
12534             return LoadGameOneMove(EndOfFile); /* tail recursion */
12535         }
12536         /* else fall thru */
12537
12538       case XBoardGame:
12539       case GNUChessGame:
12540       case PGNTag:
12541         /* Reached start of next game in file */
12542         if (appData.debugMode)
12543           fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
12544         switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12545           case MT_NONE:
12546           case MT_CHECK:
12547             break;
12548           case MT_CHECKMATE:
12549           case MT_STAINMATE:
12550             if (WhiteOnMove(currentMove)) {
12551                 GameEnds(BlackWins, "Black mates", GE_FILE);
12552             } else {
12553                 GameEnds(WhiteWins, "White mates", GE_FILE);
12554             }
12555             break;
12556           case MT_STALEMATE:
12557             GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12558             break;
12559         }
12560         done = TRUE;
12561         break;
12562
12563       case PositionDiagram:     /* should not happen; ignore */
12564       case ElapsedTime:         /* ignore */
12565       case NAG:                 /* ignore */
12566         if (appData.debugMode)
12567           fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12568                   yy_text, (int) moveType);
12569         return LoadGameOneMove(EndOfFile); /* tail recursion */
12570
12571       case IllegalMove:
12572         if (appData.testLegality) {
12573             if (appData.debugMode)
12574               fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
12575             snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12576                     (forwardMostMove / 2) + 1,
12577                     WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12578             DisplayError(move, 0);
12579             done = TRUE;
12580         } else {
12581             if (appData.debugMode)
12582               fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
12583                       yy_text, currentMoveString);
12584             if(currentMoveString[1] == '@') {
12585                 fromX = CharToPiece(WhiteOnMove(currentMove) ? ToUpper(currentMoveString[0]) : ToLower(currentMoveString[0]));
12586                 fromY = DROP_RANK;
12587             } else {
12588                 fromX = currentMoveString[0] - AAA;
12589                 fromY = currentMoveString[1] - ONE;
12590             }
12591             toX = currentMoveString[2] - AAA;
12592             toY = currentMoveString[3] - ONE;
12593             promoChar = currentMoveString[4];
12594         }
12595         break;
12596
12597       case AmbiguousMove:
12598         if (appData.debugMode)
12599           fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
12600         snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
12601                 (forwardMostMove / 2) + 1,
12602                 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12603         DisplayError(move, 0);
12604         done = TRUE;
12605         break;
12606
12607       default:
12608       case ImpossibleMove:
12609         if (appData.debugMode)
12610           fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
12611         snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12612                 (forwardMostMove / 2) + 1,
12613                 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12614         DisplayError(move, 0);
12615         done = TRUE;
12616         break;
12617     }
12618
12619     if (done) {
12620         if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
12621             DrawPosition(FALSE, boards[currentMove]);
12622             DisplayBothClocks();
12623             if (!appData.matchMode) // [HGM] PV info: routine tests if empty
12624               DisplayComment(currentMove - 1, commentList[currentMove]);
12625         }
12626         (void) StopLoadGameTimer();
12627         gameFileFP = NULL;
12628         cmailOldMove = forwardMostMove;
12629         return FALSE;
12630     } else {
12631         /* currentMoveString is set as a side-effect of yylex */
12632
12633         thinkOutput[0] = NULLCHAR;
12634         MakeMove(fromX, fromY, toX, toY, promoChar);
12635         killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
12636         currentMove = forwardMostMove;
12637         return TRUE;
12638     }
12639 }
12640
12641 /* Load the nth game from the given file */
12642 int
12643 LoadGameFromFile (char *filename, int n, char *title, int useList)
12644 {
12645     FILE *f;
12646     char buf[MSG_SIZ];
12647
12648     if (strcmp(filename, "-") == 0) {
12649         f = stdin;
12650         title = "stdin";
12651     } else {
12652         f = fopen(filename, "rb");
12653         if (f == NULL) {
12654           snprintf(buf, sizeof(buf),  _("Can't open \"%s\""), filename);
12655             DisplayError(buf, errno);
12656             return FALSE;
12657         }
12658     }
12659     if (fseek(f, 0, 0) == -1) {
12660         /* f is not seekable; probably a pipe */
12661         useList = FALSE;
12662     }
12663     if (useList && n == 0) {
12664         int error = GameListBuild(f);
12665         if (error) {
12666             DisplayError(_("Cannot build game list"), error);
12667         } else if (!ListEmpty(&gameList) &&
12668                    ((ListGame *) gameList.tailPred)->number > 1) {
12669             GameListPopUp(f, title);
12670             return TRUE;
12671         }
12672         GameListDestroy();
12673         n = 1;
12674     }
12675     if (n == 0) n = 1;
12676     return LoadGame(f, n, title, FALSE);
12677 }
12678
12679
12680 void
12681 MakeRegisteredMove ()
12682 {
12683     int fromX, fromY, toX, toY;
12684     char promoChar;
12685     if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12686         switch (cmailMoveType[lastLoadGameNumber - 1]) {
12687           case CMAIL_MOVE:
12688           case CMAIL_DRAW:
12689             if (appData.debugMode)
12690               fprintf(debugFP, "Restoring %s for game %d\n",
12691                       cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12692
12693             thinkOutput[0] = NULLCHAR;
12694             safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
12695             fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
12696             fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
12697             toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
12698             toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
12699             promoChar = cmailMove[lastLoadGameNumber - 1][4];
12700             MakeMove(fromX, fromY, toX, toY, promoChar);
12701             ShowMove(fromX, fromY, toX, toY);
12702
12703             switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12704               case MT_NONE:
12705               case MT_CHECK:
12706                 break;
12707
12708               case MT_CHECKMATE:
12709               case MT_STAINMATE:
12710                 if (WhiteOnMove(currentMove)) {
12711                     GameEnds(BlackWins, "Black mates", GE_PLAYER);
12712                 } else {
12713                     GameEnds(WhiteWins, "White mates", GE_PLAYER);
12714                 }
12715                 break;
12716
12717               case MT_STALEMATE:
12718                 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
12719                 break;
12720             }
12721
12722             break;
12723
12724           case CMAIL_RESIGN:
12725             if (WhiteOnMove(currentMove)) {
12726                 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12727             } else {
12728                 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12729             }
12730             break;
12731
12732           case CMAIL_ACCEPT:
12733             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12734             break;
12735
12736           default:
12737             break;
12738         }
12739     }
12740
12741     return;
12742 }
12743
12744 /* Wrapper around LoadGame for use when a Cmail message is loaded */
12745 int
12746 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
12747 {
12748     int retVal;
12749
12750     if (gameNumber > nCmailGames) {
12751         DisplayError(_("No more games in this message"), 0);
12752         return FALSE;
12753     }
12754     if (f == lastLoadGameFP) {
12755         int offset = gameNumber - lastLoadGameNumber;
12756         if (offset == 0) {
12757             cmailMsg[0] = NULLCHAR;
12758             if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12759                 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12760                 nCmailMovesRegistered--;
12761             }
12762             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12763             if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
12764                 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
12765             }
12766         } else {
12767             if (! RegisterMove()) return FALSE;
12768         }
12769     }
12770
12771     retVal = LoadGame(f, gameNumber, title, useList);
12772
12773     /* Make move registered during previous look at this game, if any */
12774     MakeRegisteredMove();
12775
12776     if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
12777         commentList[currentMove]
12778           = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
12779         DisplayComment(currentMove - 1, commentList[currentMove]);
12780     }
12781
12782     return retVal;
12783 }
12784
12785 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
12786 int
12787 ReloadGame (int offset)
12788 {
12789     int gameNumber = lastLoadGameNumber + offset;
12790     if (lastLoadGameFP == NULL) {
12791         DisplayError(_("No game has been loaded yet"), 0);
12792         return FALSE;
12793     }
12794     if (gameNumber <= 0) {
12795         DisplayError(_("Can't back up any further"), 0);
12796         return FALSE;
12797     }
12798     if (cmailMsgLoaded) {
12799         return CmailLoadGame(lastLoadGameFP, gameNumber,
12800                              lastLoadGameTitle, lastLoadGameUseList);
12801     } else {
12802         return LoadGame(lastLoadGameFP, gameNumber,
12803                         lastLoadGameTitle, lastLoadGameUseList);
12804     }
12805 }
12806
12807 int keys[EmptySquare+1];
12808
12809 int
12810 PositionMatches (Board b1, Board b2)
12811 {
12812     int r, f, sum=0;
12813     switch(appData.searchMode) {
12814         case 1: return CompareWithRights(b1, b2);
12815         case 2:
12816             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12817                 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
12818             }
12819             return TRUE;
12820         case 3:
12821             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12822               if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
12823                 sum += keys[b1[r][f]] - keys[b2[r][f]];
12824             }
12825             return sum==0;
12826         case 4:
12827             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12828                 sum += keys[b1[r][f]] - keys[b2[r][f]];
12829             }
12830             return sum==0;
12831     }
12832     return TRUE;
12833 }
12834
12835 #define Q_PROMO  4
12836 #define Q_EP     3
12837 #define Q_BCASTL 2
12838 #define Q_WCASTL 1
12839
12840 int pieceList[256], quickBoard[256];
12841 ChessSquare pieceType[256] = { EmptySquare };
12842 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
12843 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
12844 int soughtTotal, turn;
12845 Boolean epOK, flipSearch;
12846
12847 typedef struct {
12848     unsigned char piece, to;
12849 } Move;
12850
12851 #define DSIZE (250000)
12852
12853 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
12854 Move *moveDatabase = initialSpace;
12855 unsigned int movePtr, dataSize = DSIZE;
12856
12857 int
12858 MakePieceList (Board board, int *counts)
12859 {
12860     int r, f, n=Q_PROMO, total=0;
12861     for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
12862     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12863         int sq = f + (r<<4);
12864         if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
12865             quickBoard[sq] = ++n;
12866             pieceList[n] = sq;
12867             pieceType[n] = board[r][f];
12868             counts[board[r][f]]++;
12869             if(board[r][f] == WhiteKing) pieceList[1] = n; else
12870             if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
12871             total++;
12872         }
12873     }
12874     epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
12875     return total;
12876 }
12877
12878 void
12879 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
12880 {
12881     int sq = fromX + (fromY<<4);
12882     int piece = quickBoard[sq], rook;
12883     quickBoard[sq] = 0;
12884     moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
12885     if(piece == pieceList[1] && fromY == toY) {
12886       if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12887         int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
12888         moveDatabase[movePtr++].piece = Q_WCASTL;
12889         quickBoard[sq] = piece;
12890         piece = quickBoard[from]; quickBoard[from] = 0;
12891         moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12892       } else if((rook = quickBoard[sq]) && pieceType[rook] == WhiteRook) { // FRC castling
12893         quickBoard[sq] = 0; // remove Rook
12894         moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2); // King to-square
12895         moveDatabase[movePtr++].piece = Q_WCASTL;
12896         quickBoard[sq] = pieceList[1]; // put King
12897         piece = rook;
12898         moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12899       }
12900     } else
12901     if(piece == pieceList[2] && fromY == toY) {
12902       if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12903         int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
12904         moveDatabase[movePtr++].piece = Q_BCASTL;
12905         quickBoard[sq] = piece;
12906         piece = quickBoard[from]; quickBoard[from] = 0;
12907         moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12908       } else if((rook = quickBoard[sq]) && pieceType[rook] == BlackRook) { // FRC castling
12909         quickBoard[sq] = 0; // remove Rook
12910         moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2);
12911         moveDatabase[movePtr++].piece = Q_BCASTL;
12912         quickBoard[sq] = pieceList[2]; // put King
12913         piece = rook;
12914         moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12915       }
12916     } else
12917     if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
12918         quickBoard[(fromY<<4)+toX] = 0;
12919         moveDatabase[movePtr].piece = Q_EP;
12920         moveDatabase[movePtr++].to = (fromY<<4)+toX;
12921         moveDatabase[movePtr].to = sq;
12922     } else
12923     if(promoPiece != pieceType[piece]) {
12924         moveDatabase[movePtr++].piece = Q_PROMO;
12925         moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
12926     }
12927     moveDatabase[movePtr].piece = piece;
12928     quickBoard[sq] = piece;
12929     movePtr++;
12930 }
12931
12932 int
12933 PackGame (Board board)
12934 {
12935     Move *newSpace = NULL;
12936     moveDatabase[movePtr].piece = 0; // terminate previous game
12937     if(movePtr > dataSize) {
12938         if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
12939         dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
12940         if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
12941         if(newSpace) {
12942             int i;
12943             Move *p = moveDatabase, *q = newSpace;
12944             for(i=0; i<movePtr; i++) *q++ = *p++;    // copy to newly allocated space
12945             if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
12946             moveDatabase = newSpace;
12947         } else { // calloc failed, we must be out of memory. Too bad...
12948             dataSize = 0; // prevent calloc events for all subsequent games
12949             return 0;     // and signal this one isn't cached
12950         }
12951     }
12952     movePtr++;
12953     MakePieceList(board, counts);
12954     return movePtr;
12955 }
12956
12957 int
12958 QuickCompare (Board board, int *minCounts, int *maxCounts)
12959 {   // compare according to search mode
12960     int r, f;
12961     switch(appData.searchMode)
12962     {
12963       case 1: // exact position match
12964         if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
12965         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12966             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12967         }
12968         break;
12969       case 2: // can have extra material on empty squares
12970         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12971             if(board[r][f] == EmptySquare) continue;
12972             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12973         }
12974         break;
12975       case 3: // material with exact Pawn structure
12976         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12977             if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
12978             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12979         } // fall through to material comparison
12980       case 4: // exact material
12981         for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
12982         break;
12983       case 6: // material range with given imbalance
12984         for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
12985         // fall through to range comparison
12986       case 5: // material range
12987         for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
12988     }
12989     return TRUE;
12990 }
12991
12992 int
12993 QuickScan (Board board, Move *move)
12994 {   // reconstruct game,and compare all positions in it
12995     int cnt=0, stretch=0, found = -1, total = MakePieceList(board, counts);
12996     do {
12997         int piece = move->piece;
12998         int to = move->to, from = pieceList[piece];
12999         if(found < 0) { // if already found just scan to game end for final piece count
13000           if(QuickCompare(soughtBoard, minSought, maxSought) ||
13001            appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
13002            flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
13003                                 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
13004             ) {
13005             static int lastCounts[EmptySquare+1];
13006             int i;
13007             if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
13008             if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
13009           } else stretch = 0;
13010           if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) found = cnt + 1 - stretch;
13011           if(found >= 0 && !appData.minPieces) return found;
13012         }
13013         if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
13014           if(!piece) return (appData.minPieces && (total < appData.minPieces || total > appData.maxPieces) ? -1 : found);
13015           if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
13016             piece = (++move)->piece;
13017             from = pieceList[piece];
13018             counts[pieceType[piece]]--;
13019             pieceType[piece] = (ChessSquare) move->to;
13020             counts[move->to]++;
13021           } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
13022             counts[pieceType[quickBoard[to]]]--;
13023             quickBoard[to] = 0; total--;
13024             move++;
13025             continue;
13026           } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
13027             piece = pieceList[piece]; // first two elements of pieceList contain King numbers
13028             from  = pieceList[piece]; // so this must be King
13029             quickBoard[from] = 0;
13030             pieceList[piece] = to;
13031             from = pieceList[(++move)->piece]; // for FRC this has to be done here
13032             quickBoard[from] = 0; // rook
13033             quickBoard[to] = piece;
13034             to = move->to; piece = move->piece;
13035             goto aftercastle;
13036           }
13037         }
13038         if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
13039         if((total -= (quickBoard[to] != 0)) < soughtTotal && found < 0) return -1; // piece count dropped below what we search for
13040         quickBoard[from] = 0;
13041       aftercastle:
13042         quickBoard[to] = piece;
13043         pieceList[piece] = to;
13044         cnt++; turn ^= 3;
13045         move++;
13046     } while(1);
13047 }
13048
13049 void
13050 InitSearch ()
13051 {
13052     int r, f;
13053     flipSearch = FALSE;
13054     CopyBoard(soughtBoard, boards[currentMove]);
13055     soughtTotal = MakePieceList(soughtBoard, maxSought);
13056     soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
13057     if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
13058     CopyBoard(reverseBoard, boards[currentMove]);
13059     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
13060         int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
13061         if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
13062         reverseBoard[r][f] = piece;
13063     }
13064     reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
13065     for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
13066     if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
13067                  || (boards[currentMove][CASTLING][2] == NoRights ||
13068                      boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
13069                  && (boards[currentMove][CASTLING][5] == NoRights ||
13070                      boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
13071       ) {
13072         flipSearch = TRUE;
13073         CopyBoard(flipBoard, soughtBoard);
13074         CopyBoard(rotateBoard, reverseBoard);
13075         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
13076             flipBoard[r][f]    = soughtBoard[r][BOARD_WIDTH-1-f];
13077             rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
13078         }
13079     }
13080     for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
13081     if(appData.searchMode >= 5) {
13082         for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
13083         MakePieceList(soughtBoard, minSought);
13084         for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
13085     }
13086     if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
13087         soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
13088 }
13089
13090 GameInfo dummyInfo;
13091 static int creatingBook;
13092
13093 int
13094 GameContainsPosition (FILE *f, ListGame *lg)
13095 {
13096     int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
13097     int fromX, fromY, toX, toY;
13098     char promoChar;
13099     static int initDone=FALSE;
13100
13101     // weed out games based on numerical tag comparison
13102     if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
13103     if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
13104     if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
13105     if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
13106     if(!initDone) {
13107         for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
13108         initDone = TRUE;
13109     }
13110     if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen, FALSE);
13111     else CopyBoard(boards[scratch], initialPosition); // default start position
13112     if(lg->moves) {
13113         turn = btm + 1;
13114         if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
13115         if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
13116     }
13117     if(btm) plyNr++;
13118     if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
13119     fseek(f, lg->offset, 0);
13120     yynewfile(f);
13121     while(1) {
13122         yyboardindex = scratch;
13123         quickFlag = plyNr+1;
13124         next = Myylex();
13125         quickFlag = 0;
13126         switch(next) {
13127             case PGNTag:
13128                 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
13129             default:
13130                 continue;
13131
13132             case XBoardGame:
13133             case GNUChessGame:
13134                 if(plyNr) return -1; // after we have seen moves, this is for new game
13135               continue;
13136
13137             case AmbiguousMove: // we cannot reconstruct the game beyond these two
13138             case ImpossibleMove:
13139             case WhiteWins: // game ends here with these four
13140             case BlackWins:
13141             case GameIsDrawn:
13142             case GameUnfinished:
13143                 return -1;
13144
13145             case IllegalMove:
13146                 if(appData.testLegality) return -1;
13147             case WhiteCapturesEnPassant:
13148             case BlackCapturesEnPassant:
13149             case WhitePromotion:
13150             case BlackPromotion:
13151             case WhiteNonPromotion:
13152             case BlackNonPromotion:
13153             case NormalMove:
13154             case FirstLeg:
13155             case WhiteKingSideCastle:
13156             case WhiteQueenSideCastle:
13157             case BlackKingSideCastle:
13158             case BlackQueenSideCastle:
13159             case WhiteKingSideCastleWild:
13160             case WhiteQueenSideCastleWild:
13161             case BlackKingSideCastleWild:
13162             case BlackQueenSideCastleWild:
13163             case WhiteHSideCastleFR:
13164             case WhiteASideCastleFR:
13165             case BlackHSideCastleFR:
13166             case BlackASideCastleFR:
13167                 fromX = currentMoveString[0] - AAA;
13168                 fromY = currentMoveString[1] - ONE;
13169                 toX = currentMoveString[2] - AAA;
13170                 toY = currentMoveString[3] - ONE;
13171                 promoChar = currentMoveString[4];
13172                 break;
13173             case WhiteDrop:
13174             case BlackDrop:
13175                 fromX = next == WhiteDrop ?
13176                   (int) CharToPiece(ToUpper(currentMoveString[0])) :
13177                   (int) CharToPiece(ToLower(currentMoveString[0]));
13178                 fromY = DROP_RANK;
13179                 toX = currentMoveString[2] - AAA;
13180                 toY = currentMoveString[3] - ONE;
13181                 promoChar = 0;
13182                 break;
13183         }
13184         // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
13185         plyNr++;
13186         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
13187         if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
13188         if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
13189         if(appData.findMirror) {
13190             if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
13191             if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
13192         }
13193     }
13194 }
13195
13196 /* Load the nth game from open file f */
13197 int
13198 LoadGame (FILE *f, int gameNumber, char *title, int useList)
13199 {
13200     ChessMove cm;
13201     char buf[MSG_SIZ];
13202     int gn = gameNumber;
13203     ListGame *lg = NULL;
13204     int numPGNTags = 0, i;
13205     int err, pos = -1;
13206     GameMode oldGameMode;
13207     VariantClass v, oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
13208     char oldName[MSG_SIZ];
13209
13210     safeStrCpy(oldName, engineVariant, MSG_SIZ); v = oldVariant;
13211
13212     if (appData.debugMode)
13213         fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
13214
13215     if (gameMode == Training )
13216         SetTrainingModeOff();
13217
13218     oldGameMode = gameMode;
13219     if (gameMode != BeginningOfGame) {
13220       Reset(FALSE, TRUE);
13221     }
13222     killX = killY = kill2X = kill2Y = -1; // [HGM] lion: in case we did not Reset
13223
13224     gameFileFP = f;
13225     if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
13226         fclose(lastLoadGameFP);
13227     }
13228
13229     if (useList) {
13230         lg = (ListGame *) ListElem(&gameList, gameNumber-1);
13231
13232         if (lg) {
13233             fseek(f, lg->offset, 0);
13234             GameListHighlight(gameNumber);
13235             pos = lg->position;
13236             gn = 1;
13237         }
13238         else {
13239             if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
13240               appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
13241             else
13242             DisplayError(_("Game number out of range"), 0);
13243             return FALSE;
13244         }
13245     } else {
13246         GameListDestroy();
13247         if (fseek(f, 0, 0) == -1) {
13248             if (f == lastLoadGameFP ?
13249                 gameNumber == lastLoadGameNumber + 1 :
13250                 gameNumber == 1) {
13251                 gn = 1;
13252             } else {
13253                 DisplayError(_("Can't seek on game file"), 0);
13254                 return FALSE;
13255             }
13256         }
13257     }
13258     lastLoadGameFP = f;
13259     lastLoadGameNumber = gameNumber;
13260     safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
13261     lastLoadGameUseList = useList;
13262
13263     yynewfile(f);
13264
13265     if (lg && lg->gameInfo.white && lg->gameInfo.black) {
13266       snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
13267                 lg->gameInfo.black);
13268             DisplayTitle(buf);
13269     } else if (*title != NULLCHAR) {
13270         if (gameNumber > 1) {
13271           snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
13272             DisplayTitle(buf);
13273         } else {
13274             DisplayTitle(title);
13275         }
13276     }
13277
13278     if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
13279         gameMode = PlayFromGameFile;
13280         ModeHighlight();
13281     }
13282
13283     currentMove = forwardMostMove = backwardMostMove = 0;
13284     CopyBoard(boards[0], initialPosition);
13285     StopClocks();
13286
13287     /*
13288      * Skip the first gn-1 games in the file.
13289      * Also skip over anything that precedes an identifiable
13290      * start of game marker, to avoid being confused by
13291      * garbage at the start of the file.  Currently
13292      * recognized start of game markers are the move number "1",
13293      * the pattern "gnuchess .* game", the pattern
13294      * "^[#;%] [^ ]* game file", and a PGN tag block.
13295      * A game that starts with one of the latter two patterns
13296      * will also have a move number 1, possibly
13297      * following a position diagram.
13298      * 5-4-02: Let's try being more lenient and allowing a game to
13299      * start with an unnumbered move.  Does that break anything?
13300      */
13301     cm = lastLoadGameStart = EndOfFile;
13302     while (gn > 0) {
13303         yyboardindex = forwardMostMove;
13304         cm = (ChessMove) Myylex();
13305         switch (cm) {
13306           case EndOfFile:
13307             if (cmailMsgLoaded) {
13308                 nCmailGames = CMAIL_MAX_GAMES - gn;
13309             } else {
13310                 Reset(TRUE, TRUE);
13311                 DisplayError(_("Game not found in file"), 0);
13312             }
13313             return FALSE;
13314
13315           case GNUChessGame:
13316           case XBoardGame:
13317             gn--;
13318             lastLoadGameStart = cm;
13319             break;
13320
13321           case MoveNumberOne:
13322             switch (lastLoadGameStart) {
13323               case GNUChessGame:
13324               case XBoardGame:
13325               case PGNTag:
13326                 break;
13327               case MoveNumberOne:
13328               case EndOfFile:
13329                 gn--;           /* count this game */
13330                 lastLoadGameStart = cm;
13331                 break;
13332               default:
13333                 /* impossible */
13334                 break;
13335             }
13336             break;
13337
13338           case PGNTag:
13339             switch (lastLoadGameStart) {
13340               case GNUChessGame:
13341               case PGNTag:
13342               case MoveNumberOne:
13343               case EndOfFile:
13344                 gn--;           /* count this game */
13345                 lastLoadGameStart = cm;
13346                 break;
13347               case XBoardGame:
13348                 lastLoadGameStart = cm; /* game counted already */
13349                 break;
13350               default:
13351                 /* impossible */
13352                 break;
13353             }
13354             if (gn > 0) {
13355                 do {
13356                     yyboardindex = forwardMostMove;
13357                     cm = (ChessMove) Myylex();
13358                 } while (cm == PGNTag || cm == Comment);
13359             }
13360             break;
13361
13362           case WhiteWins:
13363           case BlackWins:
13364           case GameIsDrawn:
13365             if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
13366                 if (   cmailResult[CMAIL_MAX_GAMES - gn - 1]
13367                     != CMAIL_OLD_RESULT) {
13368                     nCmailResults ++ ;
13369                     cmailResult[  CMAIL_MAX_GAMES
13370                                 - gn - 1] = CMAIL_OLD_RESULT;
13371                 }
13372             }
13373             break;
13374
13375           case NormalMove:
13376           case FirstLeg:
13377             /* Only a NormalMove can be at the start of a game
13378              * without a position diagram. */
13379             if (lastLoadGameStart == EndOfFile ) {
13380               gn--;
13381               lastLoadGameStart = MoveNumberOne;
13382             }
13383             break;
13384
13385           default:
13386             break;
13387         }
13388     }
13389
13390     if (appData.debugMode)
13391       fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
13392
13393     for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; } // reset VariantMen
13394
13395     if (cm == XBoardGame) {
13396         /* Skip any header junk before position diagram and/or move 1 */
13397         for (;;) {
13398             yyboardindex = forwardMostMove;
13399             cm = (ChessMove) Myylex();
13400
13401             if (cm == EndOfFile ||
13402                 cm == GNUChessGame || cm == XBoardGame) {
13403                 /* Empty game; pretend end-of-file and handle later */
13404                 cm = EndOfFile;
13405                 break;
13406             }
13407
13408             if (cm == MoveNumberOne || cm == PositionDiagram ||
13409                 cm == PGNTag || cm == Comment)
13410               break;
13411         }
13412     } else if (cm == GNUChessGame) {
13413         if (gameInfo.event != NULL) {
13414             free(gameInfo.event);
13415         }
13416         gameInfo.event = StrSave(yy_text);
13417     }
13418
13419     startedFromSetupPosition = startedFromPositionFile; // [HGM]
13420     while (cm == PGNTag) {
13421         if (appData.debugMode)
13422           fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
13423         err = ParsePGNTag(yy_text, &gameInfo);
13424         if (!err) numPGNTags++;
13425
13426         /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
13427         if(gameInfo.variant != oldVariant && (gameInfo.variant != VariantNormal || gameInfo.variantName == NULL || *gameInfo.variantName == NULLCHAR)) {
13428             startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
13429             ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
13430             InitPosition(TRUE);
13431             oldVariant = gameInfo.variant;
13432             if (appData.debugMode)
13433               fprintf(debugFP, "New variant %d\n", (int) oldVariant);
13434         }
13435
13436
13437         if (gameInfo.fen != NULL) {
13438           Board initial_position;
13439           startedFromSetupPosition = TRUE;
13440           if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen, TRUE)) {
13441             Reset(TRUE, TRUE);
13442             DisplayError(_("Bad FEN position in file"), 0);
13443             return FALSE;
13444           }
13445           CopyBoard(boards[0], initial_position);
13446           if(*engineVariant || gameInfo.variant == VariantFairy) // [HGM] for now, assume FEN in engine-defined variant game is default initial position
13447             CopyBoard(initialPosition, initial_position);
13448           if (blackPlaysFirst) {
13449             currentMove = forwardMostMove = backwardMostMove = 1;
13450             CopyBoard(boards[1], initial_position);
13451             safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13452             safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13453             timeRemaining[0][1] = whiteTimeRemaining;
13454             timeRemaining[1][1] = blackTimeRemaining;
13455             if (commentList[0] != NULL) {
13456               commentList[1] = commentList[0];
13457               commentList[0] = NULL;
13458             }
13459           } else {
13460             currentMove = forwardMostMove = backwardMostMove = 0;
13461           }
13462           /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
13463           {   int i;
13464               initialRulePlies = FENrulePlies;
13465               for( i=0; i< nrCastlingRights; i++ )
13466                   initialRights[i] = initial_position[CASTLING][i];
13467           }
13468           yyboardindex = forwardMostMove;
13469           free(gameInfo.fen);
13470           gameInfo.fen = NULL;
13471         }
13472
13473         yyboardindex = forwardMostMove;
13474         cm = (ChessMove) Myylex();
13475
13476         /* Handle comments interspersed among the tags */
13477         while (cm == Comment) {
13478             char *p;
13479             if (appData.debugMode)
13480               fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13481             p = yy_text;
13482             AppendComment(currentMove, p, FALSE);
13483             yyboardindex = forwardMostMove;
13484             cm = (ChessMove) Myylex();
13485         }
13486     }
13487
13488     /* don't rely on existence of Event tag since if game was
13489      * pasted from clipboard the Event tag may not exist
13490      */
13491     if (numPGNTags > 0){
13492         char *tags;
13493         if (gameInfo.variant == VariantNormal) {
13494           VariantClass v = StringToVariant(gameInfo.event);
13495           // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
13496           if(v < VariantShogi) gameInfo.variant = v;
13497         }
13498         if (!matchMode) {
13499           if( appData.autoDisplayTags ) {
13500             tags = PGNTags(&gameInfo);
13501             TagsPopUp(tags, CmailMsg());
13502             free(tags);
13503           }
13504         }
13505     } else {
13506         /* Make something up, but don't display it now */
13507         SetGameInfo();
13508         TagsPopDown();
13509     }
13510
13511     if (cm == PositionDiagram) {
13512         int i, j;
13513         char *p;
13514         Board initial_position;
13515
13516         if (appData.debugMode)
13517           fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
13518
13519         if (!startedFromSetupPosition) {
13520             p = yy_text;
13521             for (i = BOARD_HEIGHT - 1; i >= 0; i--)
13522               for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
13523                 switch (*p) {
13524                   case '{':
13525                   case '[':
13526                   case '-':
13527                   case ' ':
13528                   case '\t':
13529                   case '\n':
13530                   case '\r':
13531                     break;
13532                   default:
13533                     initial_position[i][j++] = CharToPiece(*p);
13534                     break;
13535                 }
13536             while (*p == ' ' || *p == '\t' ||
13537                    *p == '\n' || *p == '\r') p++;
13538
13539             if (strncmp(p, "black", strlen("black"))==0)
13540               blackPlaysFirst = TRUE;
13541             else
13542               blackPlaysFirst = FALSE;
13543             startedFromSetupPosition = TRUE;
13544
13545             CopyBoard(boards[0], initial_position);
13546             if (blackPlaysFirst) {
13547                 currentMove = forwardMostMove = backwardMostMove = 1;
13548                 CopyBoard(boards[1], initial_position);
13549                 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13550                 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13551                 timeRemaining[0][1] = whiteTimeRemaining;
13552                 timeRemaining[1][1] = blackTimeRemaining;
13553                 if (commentList[0] != NULL) {
13554                     commentList[1] = commentList[0];
13555                     commentList[0] = NULL;
13556                 }
13557             } else {
13558                 currentMove = forwardMostMove = backwardMostMove = 0;
13559             }
13560         }
13561         yyboardindex = forwardMostMove;
13562         cm = (ChessMove) Myylex();
13563     }
13564
13565   if(!creatingBook) {
13566     if (first.pr == NoProc) {
13567         StartChessProgram(&first);
13568     }
13569     InitChessProgram(&first, FALSE);
13570     if(gameInfo.variant == VariantUnknown && *oldName) {
13571         safeStrCpy(engineVariant, oldName, MSG_SIZ);
13572         gameInfo.variant = v;
13573     }
13574     SendToProgram("force\n", &first);
13575     if (startedFromSetupPosition) {
13576         SendBoard(&first, forwardMostMove);
13577     if (appData.debugMode) {
13578         fprintf(debugFP, "Load Game\n");
13579     }
13580         DisplayBothClocks();
13581     }
13582   }
13583
13584     /* [HGM] server: flag to write setup moves in broadcast file as one */
13585     loadFlag = appData.suppressLoadMoves;
13586
13587     while (cm == Comment) {
13588         char *p;
13589         if (appData.debugMode)
13590           fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13591         p = yy_text;
13592         AppendComment(currentMove, p, FALSE);
13593         yyboardindex = forwardMostMove;
13594         cm = (ChessMove) Myylex();
13595     }
13596
13597     if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
13598         cm == WhiteWins || cm == BlackWins ||
13599         cm == GameIsDrawn || cm == GameUnfinished) {
13600         DisplayMessage("", _("No moves in game"));
13601         if (cmailMsgLoaded) {
13602             if (appData.debugMode)
13603               fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
13604             ClearHighlights();
13605             flipView = FALSE;
13606         }
13607         DrawPosition(FALSE, boards[currentMove]);
13608         DisplayBothClocks();
13609         gameMode = EditGame;
13610         ModeHighlight();
13611         gameFileFP = NULL;
13612         cmailOldMove = 0;
13613         return TRUE;
13614     }
13615
13616     // [HGM] PV info: routine tests if comment empty
13617     if (!matchMode && (pausing || appData.timeDelay != 0)) {
13618         DisplayComment(currentMove - 1, commentList[currentMove]);
13619     }
13620     if (!matchMode && appData.timeDelay != 0)
13621       DrawPosition(FALSE, boards[currentMove]);
13622
13623     if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
13624       programStats.ok_to_send = 1;
13625     }
13626
13627     /* if the first token after the PGN tags is a move
13628      * and not move number 1, retrieve it from the parser
13629      */
13630     if (cm != MoveNumberOne)
13631         LoadGameOneMove(cm);
13632
13633     /* load the remaining moves from the file */
13634     while (LoadGameOneMove(EndOfFile)) {
13635       timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13636       timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13637     }
13638
13639     /* rewind to the start of the game */
13640     currentMove = backwardMostMove;
13641
13642     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13643
13644     if (oldGameMode == AnalyzeFile) {
13645       appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
13646       AnalyzeFileEvent();
13647     } else
13648     if (oldGameMode == AnalyzeMode) {
13649       AnalyzeFileEvent();
13650     }
13651
13652     if(gameInfo.result == GameUnfinished && gameInfo.resultDetails && appData.clockMode) {
13653         long int w, b; // [HGM] adjourn: restore saved clock times
13654         char *p = strstr(gameInfo.resultDetails, "(Clocks:");
13655         if(p && sscanf(p+8, "%ld,%ld", &w, &b) == 2) {
13656             timeRemaining[0][forwardMostMove] = whiteTimeRemaining = 1000*w + 500;
13657             timeRemaining[1][forwardMostMove] = blackTimeRemaining = 1000*b + 500;
13658         }
13659     }
13660
13661     if(creatingBook) return TRUE;
13662     if (!matchMode && pos > 0) {
13663         ToNrEvent(pos); // [HGM] no autoplay if selected on position
13664     } else
13665     if (matchMode || appData.timeDelay == 0) {
13666       ToEndEvent();
13667     } else if (appData.timeDelay > 0) {
13668       AutoPlayGameLoop();
13669     }
13670
13671     if (appData.debugMode)
13672         fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
13673
13674     loadFlag = 0; /* [HGM] true game starts */
13675     return TRUE;
13676 }
13677
13678 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
13679 int
13680 ReloadPosition (int offset)
13681 {
13682     int positionNumber = lastLoadPositionNumber + offset;
13683     if (lastLoadPositionFP == NULL) {
13684         DisplayError(_("No position has been loaded yet"), 0);
13685         return FALSE;
13686     }
13687     if (positionNumber <= 0) {
13688         DisplayError(_("Can't back up any further"), 0);
13689         return FALSE;
13690     }
13691     return LoadPosition(lastLoadPositionFP, positionNumber,
13692                         lastLoadPositionTitle);
13693 }
13694
13695 /* Load the nth position from the given file */
13696 int
13697 LoadPositionFromFile (char *filename, int n, char *title)
13698 {
13699     FILE *f;
13700     char buf[MSG_SIZ];
13701
13702     if (strcmp(filename, "-") == 0) {
13703         return LoadPosition(stdin, n, "stdin");
13704     } else {
13705         f = fopen(filename, "rb");
13706         if (f == NULL) {
13707             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13708             DisplayError(buf, errno);
13709             return FALSE;
13710         } else {
13711             return LoadPosition(f, n, title);
13712         }
13713     }
13714 }
13715
13716 /* Load the nth position from the given open file, and close it */
13717 int
13718 LoadPosition (FILE *f, int positionNumber, char *title)
13719 {
13720     char *p, line[MSG_SIZ];
13721     Board initial_position;
13722     int i, j, fenMode, pn;
13723
13724     if (gameMode == Training )
13725         SetTrainingModeOff();
13726
13727     if (gameMode != BeginningOfGame) {
13728         Reset(FALSE, TRUE);
13729     }
13730     if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
13731         fclose(lastLoadPositionFP);
13732     }
13733     if (positionNumber == 0) positionNumber = 1;
13734     lastLoadPositionFP = f;
13735     lastLoadPositionNumber = positionNumber;
13736     safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
13737     if (first.pr == NoProc && !appData.noChessProgram) {
13738       StartChessProgram(&first);
13739       InitChessProgram(&first, FALSE);
13740     }
13741     pn = positionNumber;
13742     if (positionNumber < 0) {
13743         /* Negative position number means to seek to that byte offset */
13744         if (fseek(f, -positionNumber, 0) == -1) {
13745             DisplayError(_("Can't seek on position file"), 0);
13746             return FALSE;
13747         };
13748         pn = 1;
13749     } else {
13750         if (fseek(f, 0, 0) == -1) {
13751             if (f == lastLoadPositionFP ?
13752                 positionNumber == lastLoadPositionNumber + 1 :
13753                 positionNumber == 1) {
13754                 pn = 1;
13755             } else {
13756                 DisplayError(_("Can't seek on position file"), 0);
13757                 return FALSE;
13758             }
13759         }
13760     }
13761     /* See if this file is FEN or old-style xboard */
13762     if (fgets(line, MSG_SIZ, f) == NULL) {
13763         DisplayError(_("Position not found in file"), 0);
13764         return FALSE;
13765     }
13766     // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces (or * for blackout)
13767     fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || line[0] == '*' || CharToPiece(line[0]) != EmptySquare;
13768
13769     if (pn >= 2) {
13770         if (fenMode || line[0] == '#') pn--;
13771         while (pn > 0) {
13772             /* skip positions before number pn */
13773             if (fgets(line, MSG_SIZ, f) == NULL) {
13774                 Reset(TRUE, TRUE);
13775                 DisplayError(_("Position not found in file"), 0);
13776                 return FALSE;
13777             }
13778             if (fenMode || line[0] == '#') pn--;
13779         }
13780     }
13781
13782     if (fenMode) {
13783         char *p;
13784         if (!ParseFEN(initial_position, &blackPlaysFirst, line, TRUE)) {
13785             DisplayError(_("Bad FEN position in file"), 0);
13786             return FALSE;
13787         }
13788         if((strchr(line, ';')) && (p = strstr(line, " bm "))) { // EPD with best move
13789             sscanf(p+4, "%[^;]", bestMove);
13790         } else *bestMove = NULLCHAR;
13791         if((strchr(line, ';')) && (p = strstr(line, " am "))) { // EPD with avoid move
13792             sscanf(p+4, "%[^;]", avoidMove);
13793         } else *avoidMove = NULLCHAR;
13794     } else {
13795         (void) fgets(line, MSG_SIZ, f);
13796         (void) fgets(line, MSG_SIZ, f);
13797
13798         for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13799             (void) fgets(line, MSG_SIZ, f);
13800             for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
13801                 if (*p == ' ')
13802                   continue;
13803                 initial_position[i][j++] = CharToPiece(*p);
13804             }
13805         }
13806
13807         blackPlaysFirst = FALSE;
13808         if (!feof(f)) {
13809             (void) fgets(line, MSG_SIZ, f);
13810             if (strncmp(line, "black", strlen("black"))==0)
13811               blackPlaysFirst = TRUE;
13812         }
13813     }
13814     startedFromSetupPosition = TRUE;
13815
13816     CopyBoard(boards[0], initial_position);
13817     if (blackPlaysFirst) {
13818         currentMove = forwardMostMove = backwardMostMove = 1;
13819         safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13820         safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13821         CopyBoard(boards[1], initial_position);
13822         DisplayMessage("", _("Black to play"));
13823     } else {
13824         currentMove = forwardMostMove = backwardMostMove = 0;
13825         DisplayMessage("", _("White to play"));
13826     }
13827     initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
13828     if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
13829         SendToProgram("force\n", &first);
13830         SendBoard(&first, forwardMostMove);
13831     }
13832     if (appData.debugMode) {
13833 int i, j;
13834   for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
13835   for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
13836         fprintf(debugFP, "Load Position\n");
13837     }
13838
13839     if (positionNumber > 1) {
13840       snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
13841         DisplayTitle(line);
13842     } else {
13843         DisplayTitle(title);
13844     }
13845     gameMode = EditGame;
13846     ModeHighlight();
13847     ResetClocks();
13848     timeRemaining[0][1] = whiteTimeRemaining;
13849     timeRemaining[1][1] = blackTimeRemaining;
13850     DrawPosition(FALSE, boards[currentMove]);
13851
13852     return TRUE;
13853 }
13854
13855
13856 void
13857 CopyPlayerNameIntoFileName (char **dest, char *src)
13858 {
13859     while (*src != NULLCHAR && *src != ',') {
13860         if (*src == ' ') {
13861             *(*dest)++ = '_';
13862             src++;
13863         } else {
13864             *(*dest)++ = *src++;
13865         }
13866     }
13867 }
13868
13869 char *
13870 DefaultFileName (char *ext)
13871 {
13872     static char def[MSG_SIZ];
13873     char *p;
13874
13875     if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
13876         p = def;
13877         CopyPlayerNameIntoFileName(&p, gameInfo.white);
13878         *p++ = '-';
13879         CopyPlayerNameIntoFileName(&p, gameInfo.black);
13880         *p++ = '.';
13881         safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
13882     } else {
13883         def[0] = NULLCHAR;
13884     }
13885     return def;
13886 }
13887
13888 /* Save the current game to the given file */
13889 int
13890 SaveGameToFile (char *filename, int append)
13891 {
13892     FILE *f;
13893     char buf[MSG_SIZ];
13894     int result, i, t,tot=0;
13895
13896     if (strcmp(filename, "-") == 0) {
13897         return SaveGame(stdout, 0, NULL);
13898     } else {
13899         for(i=0; i<10; i++) { // upto 10 tries
13900              f = fopen(filename, append ? "a" : "w");
13901              if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
13902              if(f || errno != 13) break;
13903              DoSleep(t = 5 + random()%11); // wait 5-15 msec
13904              tot += t;
13905         }
13906         if (f == NULL) {
13907             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13908             DisplayError(buf, errno);
13909             return FALSE;
13910         } else {
13911             safeStrCpy(buf, lastMsg, MSG_SIZ);
13912             DisplayMessage(_("Waiting for access to save file"), "");
13913             flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
13914             DisplayMessage(_("Saving game"), "");
13915             if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno);     // better safe than sorry...
13916             result = SaveGame(f, 0, NULL);
13917             DisplayMessage(buf, "");
13918             return result;
13919         }
13920     }
13921 }
13922
13923 char *
13924 SavePart (char *str)
13925 {
13926     static char buf[MSG_SIZ];
13927     char *p;
13928
13929     p = strchr(str, ' ');
13930     if (p == NULL) return str;
13931     strncpy(buf, str, p - str);
13932     buf[p - str] = NULLCHAR;
13933     return buf;
13934 }
13935
13936 #define PGN_MAX_LINE 75
13937
13938 #define PGN_SIDE_WHITE  0
13939 #define PGN_SIDE_BLACK  1
13940
13941 static int
13942 FindFirstMoveOutOfBook (int side)
13943 {
13944     int result = -1;
13945
13946     if( backwardMostMove == 0 && ! startedFromSetupPosition) {
13947         int index = backwardMostMove;
13948         int has_book_hit = 0;
13949
13950         if( (index % 2) != side ) {
13951             index++;
13952         }
13953
13954         while( index < forwardMostMove ) {
13955             /* Check to see if engine is in book */
13956             int depth = pvInfoList[index].depth;
13957             int score = pvInfoList[index].score;
13958             int in_book = 0;
13959
13960             if( depth <= 2 ) {
13961                 in_book = 1;
13962             }
13963             else if( score == 0 && depth == 63 ) {
13964                 in_book = 1; /* Zappa */
13965             }
13966             else if( score == 2 && depth == 99 ) {
13967                 in_book = 1; /* Abrok */
13968             }
13969
13970             has_book_hit += in_book;
13971
13972             if( ! in_book ) {
13973                 result = index;
13974
13975                 break;
13976             }
13977
13978             index += 2;
13979         }
13980     }
13981
13982     return result;
13983 }
13984
13985 void
13986 GetOutOfBookInfo (char * buf)
13987 {
13988     int oob[2];
13989     int i;
13990     int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13991
13992     oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
13993     oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
13994
13995     *buf = '\0';
13996
13997     if( oob[0] >= 0 || oob[1] >= 0 ) {
13998         for( i=0; i<2; i++ ) {
13999             int idx = oob[i];
14000
14001             if( idx >= 0 ) {
14002                 if( i > 0 && oob[0] >= 0 ) {
14003                     strcat( buf, "   " );
14004                 }
14005
14006                 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
14007                 sprintf( buf+strlen(buf), "%s%.2f",
14008                     pvInfoList[idx].score >= 0 ? "+" : "",
14009                     pvInfoList[idx].score / 100.0 );
14010             }
14011         }
14012     }
14013 }
14014
14015 /* Save game in PGN style */
14016 static void
14017 SaveGamePGN2 (FILE *f)
14018 {
14019     int i, offset, linelen, newblock;
14020 //    char *movetext;
14021     char numtext[32];
14022     int movelen, numlen, blank;
14023     char move_buffer[100]; /* [AS] Buffer for move+PV info */
14024
14025     offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
14026
14027     PrintPGNTags(f, &gameInfo);
14028
14029     if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
14030
14031     if (backwardMostMove > 0 || startedFromSetupPosition) {
14032         char *fen = PositionToFEN(backwardMostMove, NULL, 1);
14033         fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
14034         fprintf(f, "\n{--------------\n");
14035         PrintPosition(f, backwardMostMove);
14036         fprintf(f, "--------------}\n");
14037         free(fen);
14038     }
14039     else {
14040         /* [AS] Out of book annotation */
14041         if( appData.saveOutOfBookInfo ) {
14042             char buf[64];
14043
14044             GetOutOfBookInfo( buf );
14045
14046             if( buf[0] != '\0' ) {
14047                 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
14048             }
14049         }
14050
14051         fprintf(f, "\n");
14052     }
14053
14054     i = backwardMostMove;
14055     linelen = 0;
14056     newblock = TRUE;
14057
14058     while (i < forwardMostMove) {
14059         /* Print comments preceding this move */
14060         if (commentList[i] != NULL) {
14061             if (linelen > 0) fprintf(f, "\n");
14062             fprintf(f, "%s", commentList[i]);
14063             linelen = 0;
14064             newblock = TRUE;
14065         }
14066
14067         /* Format move number */
14068         if ((i % 2) == 0)
14069           snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
14070         else
14071           if (newblock)
14072             snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
14073           else
14074             numtext[0] = NULLCHAR;
14075
14076         numlen = strlen(numtext);
14077         newblock = FALSE;
14078
14079         /* Print move number */
14080         blank = linelen > 0 && numlen > 0;
14081         if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
14082             fprintf(f, "\n");
14083             linelen = 0;
14084             blank = 0;
14085         }
14086         if (blank) {
14087             fprintf(f, " ");
14088             linelen++;
14089         }
14090         fprintf(f, "%s", numtext);
14091         linelen += numlen;
14092
14093         /* Get move */
14094         safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
14095         movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
14096
14097         /* Print move */
14098         blank = linelen > 0 && movelen > 0;
14099         if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
14100             fprintf(f, "\n");
14101             linelen = 0;
14102             blank = 0;
14103         }
14104         if (blank) {
14105             fprintf(f, " ");
14106             linelen++;
14107         }
14108         fprintf(f, "%s", move_buffer);
14109         linelen += movelen;
14110
14111         /* [AS] Add PV info if present */
14112         if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
14113             /* [HGM] add time */
14114             char buf[MSG_SIZ]; int seconds;
14115
14116             seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
14117
14118             if( seconds <= 0)
14119               buf[0] = 0;
14120             else
14121               if( seconds < 30 )
14122                 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
14123               else
14124                 {
14125                   seconds = (seconds + 4)/10; // round to full seconds
14126                   if( seconds < 60 )
14127                     snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
14128                   else
14129                     snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
14130                 }
14131
14132             if(appData.cumulativeTimePGN) {
14133                 snprintf(buf, MSG_SIZ, " %+ld", timeRemaining[i & 1][i+1]/1000);
14134             }
14135
14136             snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
14137                       pvInfoList[i].score >= 0 ? "+" : "",
14138                       pvInfoList[i].score / 100.0,
14139                       pvInfoList[i].depth,
14140                       buf );
14141
14142             movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
14143
14144             /* Print score/depth */
14145             blank = linelen > 0 && movelen > 0;
14146             if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
14147                 fprintf(f, "\n");
14148                 linelen = 0;
14149                 blank = 0;
14150             }
14151             if (blank) {
14152                 fprintf(f, " ");
14153                 linelen++;
14154             }
14155             fprintf(f, "%s", move_buffer);
14156             linelen += movelen;
14157         }
14158
14159         i++;
14160     }
14161
14162     /* Start a new line */
14163     if (linelen > 0) fprintf(f, "\n");
14164
14165     /* Print comments after last move */
14166     if (commentList[i] != NULL) {
14167         fprintf(f, "%s\n", commentList[i]);
14168     }
14169
14170     /* Print result */
14171     if (gameInfo.resultDetails != NULL &&
14172         gameInfo.resultDetails[0] != NULLCHAR) {
14173         char buf[MSG_SIZ], *p = gameInfo.resultDetails;
14174         if(gameInfo.result == GameUnfinished && appData.clockMode &&
14175            (gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay)) // [HGM] adjourn: save clock settings
14176             snprintf(buf, MSG_SIZ, "%s (Clocks: %ld, %ld)", p, whiteTimeRemaining/1000, blackTimeRemaining/1000), p = buf;
14177         fprintf(f, "{%s} %s\n\n", p, PGNResult(gameInfo.result));
14178     } else {
14179         fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
14180     }
14181 }
14182
14183 /* Save game in PGN style and close the file */
14184 int
14185 SaveGamePGN (FILE *f)
14186 {
14187     SaveGamePGN2(f);
14188     fclose(f);
14189     lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
14190     return TRUE;
14191 }
14192
14193 /* Save game in old style and close the file */
14194 int
14195 SaveGameOldStyle (FILE *f)
14196 {
14197     int i, offset;
14198     time_t tm;
14199
14200     tm = time((time_t *) NULL);
14201
14202     fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
14203     PrintOpponents(f);
14204
14205     if (backwardMostMove > 0 || startedFromSetupPosition) {
14206         fprintf(f, "\n[--------------\n");
14207         PrintPosition(f, backwardMostMove);
14208         fprintf(f, "--------------]\n");
14209     } else {
14210         fprintf(f, "\n");
14211     }
14212
14213     i = backwardMostMove;
14214     offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
14215
14216     while (i < forwardMostMove) {
14217         if (commentList[i] != NULL) {
14218             fprintf(f, "[%s]\n", commentList[i]);
14219         }
14220
14221         if ((i % 2) == 1) {
14222             fprintf(f, "%d. ...  %s\n", (i - offset)/2 + 1, parseList[i]);
14223             i++;
14224         } else {
14225             fprintf(f, "%d. %s  ", (i - offset)/2 + 1, parseList[i]);
14226             i++;
14227             if (commentList[i] != NULL) {
14228                 fprintf(f, "\n");
14229                 continue;
14230             }
14231             if (i >= forwardMostMove) {
14232                 fprintf(f, "\n");
14233                 break;
14234             }
14235             fprintf(f, "%s\n", parseList[i]);
14236             i++;
14237         }
14238     }
14239
14240     if (commentList[i] != NULL) {
14241         fprintf(f, "[%s]\n", commentList[i]);
14242     }
14243
14244     /* This isn't really the old style, but it's close enough */
14245     if (gameInfo.resultDetails != NULL &&
14246         gameInfo.resultDetails[0] != NULLCHAR) {
14247         fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
14248                 gameInfo.resultDetails);
14249     } else {
14250         fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
14251     }
14252
14253     fclose(f);
14254     return TRUE;
14255 }
14256
14257 /* Save the current game to open file f and close the file */
14258 int
14259 SaveGame (FILE *f, int dummy, char *dummy2)
14260 {
14261     if (gameMode == EditPosition) EditPositionDone(TRUE);
14262     lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
14263     if (appData.oldSaveStyle)
14264       return SaveGameOldStyle(f);
14265     else
14266       return SaveGamePGN(f);
14267 }
14268
14269 /* Save the current position to the given file */
14270 int
14271 SavePositionToFile (char *filename)
14272 {
14273     FILE *f;
14274     char buf[MSG_SIZ];
14275
14276     if (strcmp(filename, "-") == 0) {
14277         return SavePosition(stdout, 0, NULL);
14278     } else {
14279         f = fopen(filename, "a");
14280         if (f == NULL) {
14281             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
14282             DisplayError(buf, errno);
14283             return FALSE;
14284         } else {
14285             safeStrCpy(buf, lastMsg, MSG_SIZ);
14286             DisplayMessage(_("Waiting for access to save file"), "");
14287             flock(fileno(f), LOCK_EX); // [HGM] lock
14288             DisplayMessage(_("Saving position"), "");
14289             lseek(fileno(f), 0, SEEK_END);     // better safe than sorry...
14290             SavePosition(f, 0, NULL);
14291             DisplayMessage(buf, "");
14292             return TRUE;
14293         }
14294     }
14295 }
14296
14297 /* Save the current position to the given open file and close the file */
14298 int
14299 SavePosition (FILE *f, int dummy, char *dummy2)
14300 {
14301     time_t tm;
14302     char *fen;
14303
14304     if (gameMode == EditPosition) EditPositionDone(TRUE);
14305     if (appData.oldSaveStyle) {
14306         tm = time((time_t *) NULL);
14307
14308         fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
14309         PrintOpponents(f);
14310         fprintf(f, "[--------------\n");
14311         PrintPosition(f, currentMove);
14312         fprintf(f, "--------------]\n");
14313     } else {
14314         fen = PositionToFEN(currentMove, NULL, 1);
14315         fprintf(f, "%s\n", fen);
14316         free(fen);
14317     }
14318     fclose(f);
14319     return TRUE;
14320 }
14321
14322 void
14323 ReloadCmailMsgEvent (int unregister)
14324 {
14325 #if !WIN32
14326     static char *inFilename = NULL;
14327     static char *outFilename;
14328     int i;
14329     struct stat inbuf, outbuf;
14330     int status;
14331
14332     /* Any registered moves are unregistered if unregister is set, */
14333     /* i.e. invoked by the signal handler */
14334     if (unregister) {
14335         for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
14336             cmailMoveRegistered[i] = FALSE;
14337             if (cmailCommentList[i] != NULL) {
14338                 free(cmailCommentList[i]);
14339                 cmailCommentList[i] = NULL;
14340             }
14341         }
14342         nCmailMovesRegistered = 0;
14343     }
14344
14345     for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
14346         cmailResult[i] = CMAIL_NOT_RESULT;
14347     }
14348     nCmailResults = 0;
14349
14350     if (inFilename == NULL) {
14351         /* Because the filenames are static they only get malloced once  */
14352         /* and they never get freed                                      */
14353         inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
14354         sprintf(inFilename, "%s.game.in", appData.cmailGameName);
14355
14356         outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
14357         sprintf(outFilename, "%s.out", appData.cmailGameName);
14358     }
14359
14360     status = stat(outFilename, &outbuf);
14361     if (status < 0) {
14362         cmailMailedMove = FALSE;
14363     } else {
14364         status = stat(inFilename, &inbuf);
14365         cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
14366     }
14367
14368     /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
14369        counts the games, notes how each one terminated, etc.
14370
14371        It would be nice to remove this kludge and instead gather all
14372        the information while building the game list.  (And to keep it
14373        in the game list nodes instead of having a bunch of fixed-size
14374        parallel arrays.)  Note this will require getting each game's
14375        termination from the PGN tags, as the game list builder does
14376        not process the game moves.  --mann
14377        */
14378     cmailMsgLoaded = TRUE;
14379     LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
14380
14381     /* Load first game in the file or popup game menu */
14382     LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
14383
14384 #endif /* !WIN32 */
14385     return;
14386 }
14387
14388 int
14389 RegisterMove ()
14390 {
14391     FILE *f;
14392     char string[MSG_SIZ];
14393
14394     if (   cmailMailedMove
14395         || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
14396         return TRUE;            /* Allow free viewing  */
14397     }
14398
14399     /* Unregister move to ensure that we don't leave RegisterMove        */
14400     /* with the move registered when the conditions for registering no   */
14401     /* longer hold                                                       */
14402     if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
14403         cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
14404         nCmailMovesRegistered --;
14405
14406         if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
14407           {
14408               free(cmailCommentList[lastLoadGameNumber - 1]);
14409               cmailCommentList[lastLoadGameNumber - 1] = NULL;
14410           }
14411     }
14412
14413     if (cmailOldMove == -1) {
14414         DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
14415         return FALSE;
14416     }
14417
14418     if (currentMove > cmailOldMove + 1) {
14419         DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
14420         return FALSE;
14421     }
14422
14423     if (currentMove < cmailOldMove) {
14424         DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
14425         return FALSE;
14426     }
14427
14428     if (forwardMostMove > currentMove) {
14429         /* Silently truncate extra moves */
14430         TruncateGame();
14431     }
14432
14433     if (   (currentMove == cmailOldMove + 1)
14434         || (   (currentMove == cmailOldMove)
14435             && (   (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
14436                 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
14437         if (gameInfo.result != GameUnfinished) {
14438             cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
14439         }
14440
14441         if (commentList[currentMove] != NULL) {
14442             cmailCommentList[lastLoadGameNumber - 1]
14443               = StrSave(commentList[currentMove]);
14444         }
14445         safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
14446
14447         if (appData.debugMode)
14448           fprintf(debugFP, "Saving %s for game %d\n",
14449                   cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
14450
14451         snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
14452
14453         f = fopen(string, "w");
14454         if (appData.oldSaveStyle) {
14455             SaveGameOldStyle(f); /* also closes the file */
14456
14457             snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
14458             f = fopen(string, "w");
14459             SavePosition(f, 0, NULL); /* also closes the file */
14460         } else {
14461             fprintf(f, "{--------------\n");
14462             PrintPosition(f, currentMove);
14463             fprintf(f, "--------------}\n\n");
14464
14465             SaveGame(f, 0, NULL); /* also closes the file*/
14466         }
14467
14468         cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
14469         nCmailMovesRegistered ++;
14470     } else if (nCmailGames == 1) {
14471         DisplayError(_("You have not made a move yet"), 0);
14472         return FALSE;
14473     }
14474
14475     return TRUE;
14476 }
14477
14478 void
14479 MailMoveEvent ()
14480 {
14481 #if !WIN32
14482     static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
14483     FILE *commandOutput;
14484     char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
14485     int nBytes = 0;             /*  Suppress warnings on uninitialized variables    */
14486     int nBuffers;
14487     int i;
14488     int archived;
14489     char *arcDir;
14490
14491     if (! cmailMsgLoaded) {
14492         DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
14493         return;
14494     }
14495
14496     if (nCmailGames == nCmailResults) {
14497         DisplayError(_("No unfinished games"), 0);
14498         return;
14499     }
14500
14501 #if CMAIL_PROHIBIT_REMAIL
14502     if (cmailMailedMove) {
14503       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);
14504         DisplayError(msg, 0);
14505         return;
14506     }
14507 #endif
14508
14509     if (! (cmailMailedMove || RegisterMove())) return;
14510
14511     if (   cmailMailedMove
14512         || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
14513       snprintf(string, MSG_SIZ, partCommandString,
14514                appData.debugMode ? " -v" : "", appData.cmailGameName);
14515         commandOutput = popen(string, "r");
14516
14517         if (commandOutput == NULL) {
14518             DisplayError(_("Failed to invoke cmail"), 0);
14519         } else {
14520             for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
14521                 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
14522             }
14523             if (nBuffers > 1) {
14524                 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
14525                 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
14526                 nBytes = MSG_SIZ - 1;
14527             } else {
14528                 (void) memcpy(msg, buffer, nBytes);
14529             }
14530             *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
14531
14532             if(StrStr(msg, "Mailed cmail message to ") != NULL) {
14533                 cmailMailedMove = TRUE; /* Prevent >1 moves    */
14534
14535                 archived = TRUE;
14536                 for (i = 0; i < nCmailGames; i ++) {
14537                     if (cmailResult[i] == CMAIL_NOT_RESULT) {
14538                         archived = FALSE;
14539                     }
14540                 }
14541                 if (   archived
14542                     && (   (arcDir = (char *) getenv("CMAIL_ARCDIR"))
14543                         != NULL)) {
14544                   snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
14545                            arcDir,
14546                            appData.cmailGameName,
14547                            gameInfo.date);
14548                     LoadGameFromFile(buffer, 1, buffer, FALSE);
14549                     cmailMsgLoaded = FALSE;
14550                 }
14551             }
14552
14553             DisplayInformation(msg);
14554             pclose(commandOutput);
14555         }
14556     } else {
14557         if ((*cmailMsg) != '\0') {
14558             DisplayInformation(cmailMsg);
14559         }
14560     }
14561
14562     return;
14563 #endif /* !WIN32 */
14564 }
14565
14566 char *
14567 CmailMsg ()
14568 {
14569 #if WIN32
14570     return NULL;
14571 #else
14572     int  prependComma = 0;
14573     char number[5];
14574     char string[MSG_SIZ];       /* Space for game-list */
14575     int  i;
14576
14577     if (!cmailMsgLoaded) return "";
14578
14579     if (cmailMailedMove) {
14580       snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
14581     } else {
14582         /* Create a list of games left */
14583       snprintf(string, MSG_SIZ, "[");
14584         for (i = 0; i < nCmailGames; i ++) {
14585             if (! (   cmailMoveRegistered[i]
14586                    || (cmailResult[i] == CMAIL_OLD_RESULT))) {
14587                 if (prependComma) {
14588                     snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
14589                 } else {
14590                     snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
14591                     prependComma = 1;
14592                 }
14593
14594                 strcat(string, number);
14595             }
14596         }
14597         strcat(string, "]");
14598
14599         if (nCmailMovesRegistered + nCmailResults == 0) {
14600             switch (nCmailGames) {
14601               case 1:
14602                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
14603                 break;
14604
14605               case 2:
14606                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
14607                 break;
14608
14609               default:
14610                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
14611                          nCmailGames);
14612                 break;
14613             }
14614         } else {
14615             switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
14616               case 1:
14617                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
14618                          string);
14619                 break;
14620
14621               case 0:
14622                 if (nCmailResults == nCmailGames) {
14623                   snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
14624                 } else {
14625                   snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
14626                 }
14627                 break;
14628
14629               default:
14630                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
14631                          string);
14632             }
14633         }
14634     }
14635     return cmailMsg;
14636 #endif /* WIN32 */
14637 }
14638
14639 void
14640 ResetGameEvent ()
14641 {
14642     if (gameMode == Training)
14643       SetTrainingModeOff();
14644
14645     Reset(TRUE, TRUE);
14646     cmailMsgLoaded = FALSE;
14647     if (appData.icsActive) {
14648       SendToICS(ics_prefix);
14649       SendToICS("refresh\n");
14650     }
14651 }
14652
14653 void
14654 ExitEvent (int status)
14655 {
14656     exiting++;
14657     if (exiting > 2) {
14658       /* Give up on clean exit */
14659       exit(status);
14660     }
14661     if (exiting > 1) {
14662       /* Keep trying for clean exit */
14663       return;
14664     }
14665
14666     if (appData.icsActive) printf("\n"); // [HGM] end on new line after closing XBoard
14667     if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
14668
14669     if (telnetISR != NULL) {
14670       RemoveInputSource(telnetISR);
14671     }
14672     if (icsPR != NoProc) {
14673       DestroyChildProcess(icsPR, TRUE);
14674     }
14675
14676     /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
14677     GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
14678
14679     /* [HGM] crash: the above GameEnds() is a dud if another one was running */
14680     /* make sure this other one finishes before killing it!                  */
14681     if(endingGame) { int count = 0;
14682         if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
14683         while(endingGame && count++ < 10) DoSleep(1);
14684         if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
14685     }
14686
14687     /* Kill off chess programs */
14688     if (first.pr != NoProc) {
14689         ExitAnalyzeMode();
14690
14691         DoSleep( appData.delayBeforeQuit );
14692         SendToProgram("quit\n", &first);
14693         DestroyChildProcess(first.pr, 4 + first.useSigterm /* [AS] first.useSigterm */ );
14694     }
14695     if (second.pr != NoProc) {
14696         DoSleep( appData.delayBeforeQuit );
14697         SendToProgram("quit\n", &second);
14698         DestroyChildProcess(second.pr, 4 + second.useSigterm /* [AS] second.useSigterm */ );
14699     }
14700     if (first.isr != NULL) {
14701         RemoveInputSource(first.isr);
14702     }
14703     if (second.isr != NULL) {
14704         RemoveInputSource(second.isr);
14705     }
14706
14707     if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
14708     if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
14709
14710     ShutDownFrontEnd();
14711     exit(status);
14712 }
14713
14714 void
14715 PauseEngine (ChessProgramState *cps)
14716 {
14717     SendToProgram("pause\n", cps);
14718     cps->pause = 2;
14719 }
14720
14721 void
14722 UnPauseEngine (ChessProgramState *cps)
14723 {
14724     SendToProgram("resume\n", cps);
14725     cps->pause = 1;
14726 }
14727
14728 void
14729 PauseEvent ()
14730 {
14731     if (appData.debugMode)
14732         fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
14733     if (pausing) {
14734         pausing = FALSE;
14735         ModeHighlight();
14736         if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
14737             StartClocks();
14738             if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
14739                 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
14740                 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
14741             }
14742             if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
14743             HandleMachineMove(stashedInputMove, stalledEngine);
14744             stalledEngine = NULL;
14745             return;
14746         }
14747         if (gameMode == MachinePlaysWhite ||
14748             gameMode == TwoMachinesPlay   ||
14749             gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
14750             if(first.pause)  UnPauseEngine(&first);
14751             else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
14752             if(second.pause) UnPauseEngine(&second);
14753             else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
14754             StartClocks();
14755         } else {
14756             DisplayBothClocks();
14757         }
14758         if (gameMode == PlayFromGameFile) {
14759             if (appData.timeDelay >= 0)
14760                 AutoPlayGameLoop();
14761         } else if (gameMode == IcsExamining && pauseExamInvalid) {
14762             Reset(FALSE, TRUE);
14763             SendToICS(ics_prefix);
14764             SendToICS("refresh\n");
14765         } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
14766             ForwardInner(forwardMostMove);
14767         }
14768         pauseExamInvalid = FALSE;
14769     } else {
14770         switch (gameMode) {
14771           default:
14772             return;
14773           case IcsExamining:
14774             pauseExamForwardMostMove = forwardMostMove;
14775             pauseExamInvalid = FALSE;
14776             /* fall through */
14777           case IcsObserving:
14778           case IcsPlayingWhite:
14779           case IcsPlayingBlack:
14780             pausing = TRUE;
14781             ModeHighlight();
14782             return;
14783           case PlayFromGameFile:
14784             (void) StopLoadGameTimer();
14785             pausing = TRUE;
14786             ModeHighlight();
14787             break;
14788           case BeginningOfGame:
14789             if (appData.icsActive) return;
14790             /* else fall through */
14791           case MachinePlaysWhite:
14792           case MachinePlaysBlack:
14793           case TwoMachinesPlay:
14794             if (forwardMostMove == 0)
14795               return;           /* don't pause if no one has moved */
14796             if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
14797                 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
14798                 if(onMove->pause) {           // thinking engine can be paused
14799                     PauseEngine(onMove);      // do it
14800                     if(onMove->other->pause)  // pondering opponent can always be paused immediately
14801                         PauseEngine(onMove->other);
14802                     else
14803                         SendToProgram("easy\n", onMove->other);
14804                     StopClocks();
14805                 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
14806             } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
14807                 if(first.pause) {
14808                     PauseEngine(&first);
14809                     StopClocks();
14810                 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
14811             } else { // human on move, pause pondering by either method
14812                 if(first.pause)
14813                     PauseEngine(&first);
14814                 else if(appData.ponderNextMove)
14815                     SendToProgram("easy\n", &first);
14816                 StopClocks();
14817             }
14818             // if no immediate pausing is possible, wait for engine to move, and stop clocks then
14819           case AnalyzeMode:
14820             pausing = TRUE;
14821             ModeHighlight();
14822             break;
14823         }
14824     }
14825 }
14826
14827 void
14828 EditCommentEvent ()
14829 {
14830     char title[MSG_SIZ];
14831
14832     if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
14833       safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
14834     } else {
14835       snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
14836                WhiteOnMove(currentMove - 1) ? " " : ".. ",
14837                parseList[currentMove - 1]);
14838     }
14839
14840     EditCommentPopUp(currentMove, title, commentList[currentMove]);
14841 }
14842
14843
14844 void
14845 EditTagsEvent ()
14846 {
14847     char *tags = PGNTags(&gameInfo);
14848     bookUp = FALSE;
14849     EditTagsPopUp(tags, NULL);
14850     free(tags);
14851 }
14852
14853 void
14854 StartSecond ()
14855 {
14856     if(WaitForEngine(&second, StartSecond)) return;
14857     InitChessProgram(&second, FALSE);
14858     FeedMovesToProgram(&second, currentMove);
14859
14860     SendToProgram("analyze\n", &second);
14861     second.analyzing = TRUE;
14862     ThawUI();
14863 }
14864
14865 void
14866 ToggleSecond ()
14867 {
14868   if(second.analyzing) {
14869     SendToProgram("exit\n", &second);
14870     second.analyzing = FALSE;
14871   } else {
14872     StartSecond();
14873   }
14874 }
14875
14876 /* Toggle ShowThinking */
14877 void
14878 ToggleShowThinking()
14879 {
14880   appData.showThinking = !appData.showThinking;
14881   ShowThinkingEvent();
14882 }
14883
14884 int
14885 AnalyzeModeEvent ()
14886 {
14887     char buf[MSG_SIZ];
14888
14889     if (!first.analysisSupport) {
14890       snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14891       DisplayError(buf, 0);
14892       return 0;
14893     }
14894     /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
14895     if (appData.icsActive) {
14896         if (gameMode != IcsObserving) {
14897           snprintf(buf, MSG_SIZ, _("You are not observing a game"));
14898             DisplayError(buf, 0);
14899             /* secure check */
14900             if (appData.icsEngineAnalyze) {
14901                 if (appData.debugMode)
14902                     fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
14903                 ExitAnalyzeMode();
14904                 ModeHighlight();
14905             }
14906             return 0;
14907         }
14908         /* if enable, user wants to disable icsEngineAnalyze */
14909         if (appData.icsEngineAnalyze) {
14910                 ExitAnalyzeMode();
14911                 ModeHighlight();
14912                 return 0;
14913         }
14914         appData.icsEngineAnalyze = TRUE;
14915         if (appData.debugMode)
14916             fprintf(debugFP, "ICS engine analyze starting... \n");
14917     }
14918
14919     if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
14920     if (appData.noChessProgram || gameMode == AnalyzeMode)
14921       return 0;
14922
14923     if (gameMode != AnalyzeFile) {
14924         if (!appData.icsEngineAnalyze) {
14925                EditGameEvent();
14926                if (gameMode != EditGame) return 0;
14927         }
14928         if (!appData.showThinking) ToggleShowThinking();
14929         ResurrectChessProgram();
14930         SendToProgram("analyze\n", &first);
14931         first.analyzing = TRUE;
14932         /*first.maybeThinking = TRUE;*/
14933         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14934         EngineOutputPopUp();
14935     }
14936     if (!appData.icsEngineAnalyze) {
14937         gameMode = AnalyzeMode;
14938         ClearEngineOutputPane(0); // [TK] exclude: to print exclusion/multipv header
14939     }
14940     pausing = FALSE;
14941     ModeHighlight();
14942     SetGameInfo();
14943
14944     StartAnalysisClock();
14945     GetTimeMark(&lastNodeCountTime);
14946     lastNodeCount = 0;
14947     return 1;
14948 }
14949
14950 void
14951 AnalyzeFileEvent ()
14952 {
14953     if (appData.noChessProgram || gameMode == AnalyzeFile)
14954       return;
14955
14956     if (!first.analysisSupport) {
14957       char buf[MSG_SIZ];
14958       snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14959       DisplayError(buf, 0);
14960       return;
14961     }
14962
14963     if (gameMode != AnalyzeMode) {
14964         keepInfo = 1; // mere annotating should not alter PGN tags
14965         EditGameEvent();
14966         keepInfo = 0;
14967         if (gameMode != EditGame) return;
14968         if (!appData.showThinking) ToggleShowThinking();
14969         ResurrectChessProgram();
14970         SendToProgram("analyze\n", &first);
14971         first.analyzing = TRUE;
14972         /*first.maybeThinking = TRUE;*/
14973         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14974         EngineOutputPopUp();
14975     }
14976     gameMode = AnalyzeFile;
14977     pausing = FALSE;
14978     ModeHighlight();
14979
14980     StartAnalysisClock();
14981     GetTimeMark(&lastNodeCountTime);
14982     lastNodeCount = 0;
14983     if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
14984     AnalysisPeriodicEvent(1);
14985 }
14986
14987 void
14988 MachineWhiteEvent ()
14989 {
14990     char buf[MSG_SIZ];
14991     char *bookHit = NULL;
14992
14993     if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
14994       return;
14995
14996
14997     if (gameMode == PlayFromGameFile ||
14998         gameMode == TwoMachinesPlay  ||
14999         gameMode == Training         ||
15000         gameMode == AnalyzeMode      ||
15001         gameMode == EndOfGame)
15002         EditGameEvent();
15003
15004     if (gameMode == EditPosition)
15005         EditPositionDone(TRUE);
15006
15007     if (!WhiteOnMove(currentMove)) {
15008         DisplayError(_("It is not White's turn"), 0);
15009         return;
15010     }
15011
15012     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
15013       ExitAnalyzeMode();
15014
15015     if (gameMode == EditGame || gameMode == AnalyzeMode ||
15016         gameMode == AnalyzeFile)
15017         TruncateGame();
15018
15019     ResurrectChessProgram();    /* in case it isn't running */
15020     if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
15021         gameMode = MachinePlaysWhite;
15022         ResetClocks();
15023     } else
15024     gameMode = MachinePlaysWhite;
15025     pausing = FALSE;
15026     ModeHighlight();
15027     SetGameInfo();
15028     snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15029     DisplayTitle(buf);
15030     if (first.sendName) {
15031       snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
15032       SendToProgram(buf, &first);
15033     }
15034     if (first.sendTime) {
15035       if (first.useColors) {
15036         SendToProgram("black\n", &first); /*gnu kludge*/
15037       }
15038       SendTimeRemaining(&first, TRUE);
15039     }
15040     if (first.useColors) {
15041       SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
15042     }
15043     bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
15044     SetMachineThinkingEnables();
15045     first.maybeThinking = TRUE;
15046     StartClocks();
15047     firstMove = FALSE;
15048
15049     if (appData.autoFlipView && !flipView) {
15050       flipView = !flipView;
15051       DrawPosition(FALSE, NULL);
15052       DisplayBothClocks();       // [HGM] logo: clocks might have to be exchanged;
15053     }
15054
15055     if(bookHit) { // [HGM] book: simulate book reply
15056         static char bookMove[MSG_SIZ]; // a bit generous?
15057
15058         programStats.nodes = programStats.depth = programStats.time =
15059         programStats.score = programStats.got_only_move = 0;
15060         sprintf(programStats.movelist, "%s (xbook)", bookHit);
15061
15062         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15063         strcat(bookMove, bookHit);
15064         savedMessage = bookMove; // args for deferred call
15065         savedState = &first;
15066         ScheduleDelayedEvent(DeferredBookMove, 1);
15067     }
15068 }
15069
15070 void
15071 MachineBlackEvent ()
15072 {
15073   char buf[MSG_SIZ];
15074   char *bookHit = NULL;
15075
15076     if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
15077         return;
15078
15079
15080     if (gameMode == PlayFromGameFile ||
15081         gameMode == TwoMachinesPlay  ||
15082         gameMode == Training         ||
15083         gameMode == AnalyzeMode      ||
15084         gameMode == EndOfGame)
15085         EditGameEvent();
15086
15087     if (gameMode == EditPosition)
15088         EditPositionDone(TRUE);
15089
15090     if (WhiteOnMove(currentMove)) {
15091         DisplayError(_("It is not Black's turn"), 0);
15092         return;
15093     }
15094
15095     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
15096       ExitAnalyzeMode();
15097
15098     if (gameMode == EditGame || gameMode == AnalyzeMode ||
15099         gameMode == AnalyzeFile)
15100         TruncateGame();
15101
15102     ResurrectChessProgram();    /* in case it isn't running */
15103     gameMode = MachinePlaysBlack;
15104     pausing = FALSE;
15105     ModeHighlight();
15106     SetGameInfo();
15107     snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15108     DisplayTitle(buf);
15109     if (first.sendName) {
15110       snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
15111       SendToProgram(buf, &first);
15112     }
15113     if (first.sendTime) {
15114       if (first.useColors) {
15115         SendToProgram("white\n", &first); /*gnu kludge*/
15116       }
15117       SendTimeRemaining(&first, FALSE);
15118     }
15119     if (first.useColors) {
15120       SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
15121     }
15122     bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
15123     SetMachineThinkingEnables();
15124     first.maybeThinking = TRUE;
15125     StartClocks();
15126
15127     if (appData.autoFlipView && flipView) {
15128       flipView = !flipView;
15129       DrawPosition(FALSE, NULL);
15130       DisplayBothClocks();       // [HGM] logo: clocks might have to be exchanged;
15131     }
15132     if(bookHit) { // [HGM] book: simulate book reply
15133         static char bookMove[MSG_SIZ]; // a bit generous?
15134
15135         programStats.nodes = programStats.depth = programStats.time =
15136         programStats.score = programStats.got_only_move = 0;
15137         sprintf(programStats.movelist, "%s (xbook)", bookHit);
15138
15139         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15140         strcat(bookMove, bookHit);
15141         savedMessage = bookMove; // args for deferred call
15142         savedState = &first;
15143         ScheduleDelayedEvent(DeferredBookMove, 1);
15144     }
15145 }
15146
15147
15148 void
15149 DisplayTwoMachinesTitle ()
15150 {
15151     char buf[MSG_SIZ];
15152     if (appData.matchGames > 0) {
15153         if(appData.tourneyFile[0]) {
15154           snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
15155                    gameInfo.white, _("vs."), gameInfo.black,
15156                    nextGame+1, appData.matchGames+1,
15157                    appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
15158         } else
15159         if (first.twoMachinesColor[0] == 'w') {
15160           snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
15161                    gameInfo.white, _("vs."),  gameInfo.black,
15162                    first.matchWins, second.matchWins,
15163                    matchGame - 1 - (first.matchWins + second.matchWins));
15164         } else {
15165           snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
15166                    gameInfo.white, _("vs."), gameInfo.black,
15167                    second.matchWins, first.matchWins,
15168                    matchGame - 1 - (first.matchWins + second.matchWins));
15169         }
15170     } else {
15171       snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15172     }
15173     DisplayTitle(buf);
15174 }
15175
15176 void
15177 SettingsMenuIfReady ()
15178 {
15179   if (second.lastPing != second.lastPong) {
15180     DisplayMessage("", _("Waiting for second chess program"));
15181     ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
15182     return;
15183   }
15184   ThawUI();
15185   DisplayMessage("", "");
15186   SettingsPopUp(&second);
15187 }
15188
15189 int
15190 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
15191 {
15192     char buf[MSG_SIZ];
15193     if (cps->pr == NoProc) {
15194         StartChessProgram(cps);
15195         if (cps->protocolVersion == 1) {
15196           retry();
15197           ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
15198         } else {
15199           /* kludge: allow timeout for initial "feature" command */
15200           if(retry != TwoMachinesEventIfReady) FreezeUI();
15201           snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
15202           DisplayMessage("", buf);
15203           ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
15204         }
15205         return 1;
15206     }
15207     return 0;
15208 }
15209
15210 void
15211 TwoMachinesEvent P((void))
15212 {
15213     int i, move = forwardMostMove;
15214     char buf[MSG_SIZ];
15215     ChessProgramState *onmove;
15216     char *bookHit = NULL;
15217     static int stalling = 0;
15218     TimeMark now;
15219     long wait;
15220
15221     if (appData.noChessProgram) return;
15222
15223     switch (gameMode) {
15224       case TwoMachinesPlay:
15225         return;
15226       case MachinePlaysWhite:
15227       case MachinePlaysBlack:
15228         if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15229             DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
15230             return;
15231         }
15232         /* fall through */
15233       case BeginningOfGame:
15234       case PlayFromGameFile:
15235       case EndOfGame:
15236         EditGameEvent();
15237         if (gameMode != EditGame) return;
15238         break;
15239       case EditPosition:
15240         EditPositionDone(TRUE);
15241         break;
15242       case AnalyzeMode:
15243       case AnalyzeFile:
15244         ExitAnalyzeMode();
15245         break;
15246       case EditGame:
15247       default:
15248         break;
15249     }
15250
15251 //    forwardMostMove = currentMove;
15252     TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
15253     startingEngine = TRUE;
15254
15255     if(!ResurrectChessProgram()) return;   /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
15256
15257     if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
15258     if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
15259       ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
15260       return;
15261     }
15262   if(!appData.epd) {
15263     if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
15264
15265     if(!SupportedVariant(second.variants, gameInfo.variant, gameInfo.boardWidth,
15266                          gameInfo.boardHeight, gameInfo.holdingsSize, second.protocolVersion, second.tidy)) {
15267         startingEngine = matchMode = FALSE;
15268         DisplayError("second engine does not play this", 0);
15269         gameMode = TwoMachinesPlay; ModeHighlight(); // Needed to make sure menu item is unchecked
15270         EditGameEvent(); // switch back to EditGame mode
15271         return;
15272     }
15273
15274     if(!stalling) {
15275       InitChessProgram(&second, FALSE); // unbalances ping of second engine
15276       SendToProgram("force\n", &second);
15277       stalling = 1;
15278       ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
15279       return;
15280     }
15281   }
15282     GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
15283     if(appData.matchPause>10000 || appData.matchPause<10)
15284                 appData.matchPause = 10000; /* [HGM] make pause adjustable */
15285     wait = SubtractTimeMarks(&now, &pauseStart);
15286     if(wait < appData.matchPause) {
15287         ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
15288         return;
15289     }
15290     // we are now committed to starting the game
15291     stalling = 0;
15292     DisplayMessage("", "");
15293   if(!appData.epd) {
15294     if (startedFromSetupPosition) {
15295         SendBoard(&second, backwardMostMove);
15296     if (appData.debugMode) {
15297         fprintf(debugFP, "Two Machines\n");
15298     }
15299     }
15300     for (i = backwardMostMove; i < forwardMostMove; i++) {
15301         SendMoveToProgram(i, &second);
15302     }
15303   }
15304
15305     gameMode = TwoMachinesPlay;
15306     pausing = startingEngine = FALSE;
15307     ModeHighlight(); // [HGM] logo: this triggers display update of logos
15308     SetGameInfo();
15309     DisplayTwoMachinesTitle();
15310     firstMove = TRUE;
15311     if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
15312         onmove = &first;
15313     } else {
15314         onmove = &second;
15315     }
15316     if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
15317     SendToProgram(first.computerString, &first);
15318     if (first.sendName) {
15319       snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
15320       SendToProgram(buf, &first);
15321     }
15322   if(!appData.epd) {
15323     SendToProgram(second.computerString, &second);
15324     if (second.sendName) {
15325       snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
15326       SendToProgram(buf, &second);
15327     }
15328   }
15329
15330     if (!first.sendTime || !second.sendTime || move == 0) { // [HGM] first engine changed sides from Reset, so recalc time odds
15331         ResetClocks();
15332         timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15333         timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15334     }
15335     if (onmove->sendTime) {
15336       if (onmove->useColors) {
15337         SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
15338       }
15339       SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
15340     }
15341     if (onmove->useColors) {
15342       SendToProgram(onmove->twoMachinesColor, onmove);
15343     }
15344     bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
15345 //    SendToProgram("go\n", onmove);
15346     onmove->maybeThinking = TRUE;
15347     SetMachineThinkingEnables();
15348
15349     StartClocks();
15350
15351     if(bookHit) { // [HGM] book: simulate book reply
15352         static char bookMove[MSG_SIZ]; // a bit generous?
15353
15354         programStats.nodes = programStats.depth = programStats.time =
15355         programStats.score = programStats.got_only_move = 0;
15356         sprintf(programStats.movelist, "%s (xbook)", bookHit);
15357
15358         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15359         strcat(bookMove, bookHit);
15360         savedMessage = bookMove; // args for deferred call
15361         savedState = onmove;
15362         ScheduleDelayedEvent(DeferredBookMove, 1);
15363     }
15364 }
15365
15366 void
15367 TrainingEvent ()
15368 {
15369     if (gameMode == Training) {
15370       SetTrainingModeOff();
15371       gameMode = PlayFromGameFile;
15372       DisplayMessage("", _("Training mode off"));
15373     } else {
15374       gameMode = Training;
15375       animateTraining = appData.animate;
15376
15377       /* make sure we are not already at the end of the game */
15378       if (currentMove < forwardMostMove) {
15379         SetTrainingModeOn();
15380         DisplayMessage("", _("Training mode on"));
15381       } else {
15382         gameMode = PlayFromGameFile;
15383         DisplayError(_("Already at end of game"), 0);
15384       }
15385     }
15386     ModeHighlight();
15387 }
15388
15389 void
15390 IcsClientEvent ()
15391 {
15392     if (!appData.icsActive) return;
15393     switch (gameMode) {
15394       case IcsPlayingWhite:
15395       case IcsPlayingBlack:
15396       case IcsObserving:
15397       case IcsIdle:
15398       case BeginningOfGame:
15399       case IcsExamining:
15400         return;
15401
15402       case EditGame:
15403         break;
15404
15405       case EditPosition:
15406         EditPositionDone(TRUE);
15407         break;
15408
15409       case AnalyzeMode:
15410       case AnalyzeFile:
15411         ExitAnalyzeMode();
15412         break;
15413
15414       default:
15415         EditGameEvent();
15416         break;
15417     }
15418
15419     gameMode = IcsIdle;
15420     ModeHighlight();
15421     return;
15422 }
15423
15424 void
15425 EditGameEvent ()
15426 {
15427     int i;
15428
15429     switch (gameMode) {
15430       case Training:
15431         SetTrainingModeOff();
15432         break;
15433       case MachinePlaysWhite:
15434       case MachinePlaysBlack:
15435       case BeginningOfGame:
15436         SendToProgram("force\n", &first);
15437         if(gameMode == (forwardMostMove & 1 ? MachinePlaysBlack : MachinePlaysWhite)) { // engine is thinking
15438             if (first.usePing) { // [HGM] always send ping when we might interrupt machine thinking
15439                 char buf[MSG_SIZ];
15440                 abortEngineThink = TRUE;
15441                 snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++first.lastPing);
15442                 SendToProgram(buf, &first);
15443                 DisplayMessage("Aborting engine think", "");
15444                 FreezeUI();
15445             }
15446         }
15447         SetUserThinkingEnables();
15448         break;
15449       case PlayFromGameFile:
15450         (void) StopLoadGameTimer();
15451         if (gameFileFP != NULL) {
15452             gameFileFP = NULL;
15453         }
15454         break;
15455       case EditPosition:
15456         EditPositionDone(TRUE);
15457         break;
15458       case AnalyzeMode:
15459       case AnalyzeFile:
15460         ExitAnalyzeMode();
15461         SendToProgram("force\n", &first);
15462         break;
15463       case TwoMachinesPlay:
15464         GameEnds(EndOfFile, NULL, GE_PLAYER);
15465         ResurrectChessProgram();
15466         SetUserThinkingEnables();
15467         break;
15468       case EndOfGame:
15469         ResurrectChessProgram();
15470         break;
15471       case IcsPlayingBlack:
15472       case IcsPlayingWhite:
15473         DisplayError(_("Warning: You are still playing a game"), 0);
15474         break;
15475       case IcsObserving:
15476         DisplayError(_("Warning: You are still observing a game"), 0);
15477         break;
15478       case IcsExamining:
15479         DisplayError(_("Warning: You are still examining a game"), 0);
15480         break;
15481       case IcsIdle:
15482         break;
15483       case EditGame:
15484       default:
15485         return;
15486     }
15487
15488     pausing = FALSE;
15489     StopClocks();
15490     first.offeredDraw = second.offeredDraw = 0;
15491
15492     if (gameMode == PlayFromGameFile) {
15493         whiteTimeRemaining = timeRemaining[0][currentMove];
15494         blackTimeRemaining = timeRemaining[1][currentMove];
15495         DisplayTitle("");
15496     }
15497
15498     if (gameMode == MachinePlaysWhite ||
15499         gameMode == MachinePlaysBlack ||
15500         gameMode == TwoMachinesPlay ||
15501         gameMode == EndOfGame) {
15502         i = forwardMostMove;
15503         while (i > currentMove) {
15504             SendToProgram("undo\n", &first);
15505             i--;
15506         }
15507         if(!adjustedClock) {
15508         whiteTimeRemaining = timeRemaining[0][currentMove];
15509         blackTimeRemaining = timeRemaining[1][currentMove];
15510         DisplayBothClocks();
15511         }
15512         if (whiteFlag || blackFlag) {
15513             whiteFlag = blackFlag = 0;
15514         }
15515         DisplayTitle("");
15516     }
15517
15518     gameMode = EditGame;
15519     ModeHighlight();
15520     SetGameInfo();
15521 }
15522
15523 void
15524 EditPositionEvent ()
15525 {
15526     int i;
15527     if (gameMode == EditPosition) {
15528         EditGameEvent();
15529         return;
15530     }
15531
15532     EditGameEvent();
15533     if (gameMode != EditGame) return;
15534
15535     gameMode = EditPosition;
15536     ModeHighlight();
15537     SetGameInfo();
15538     CopyBoard(rightsBoard, nullBoard);
15539     if (currentMove > 0)
15540       CopyBoard(boards[0], boards[currentMove]);
15541     for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
15542       rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
15543
15544     blackPlaysFirst = !WhiteOnMove(currentMove);
15545     ResetClocks();
15546     currentMove = forwardMostMove = backwardMostMove = 0;
15547     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15548     DisplayMove(-1);
15549     if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
15550 }
15551
15552 void
15553 ExitAnalyzeMode ()
15554 {
15555     /* [DM] icsEngineAnalyze - possible call from other functions */
15556     if (appData.icsEngineAnalyze) {
15557         appData.icsEngineAnalyze = FALSE;
15558
15559         DisplayMessage("",_("Close ICS engine analyze..."));
15560     }
15561     if (first.analysisSupport && first.analyzing) {
15562       SendToBoth("exit\n");
15563       first.analyzing = second.analyzing = FALSE;
15564     }
15565     thinkOutput[0] = NULLCHAR;
15566 }
15567
15568 void
15569 EditPositionDone (Boolean fakeRights)
15570 {
15571     int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
15572
15573     startedFromSetupPosition = TRUE;
15574     InitChessProgram(&first, FALSE);
15575     if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
15576       int r, f;
15577       boards[0][EP_STATUS] = EP_NONE;
15578       for(f=0; f<=nrCastlingRights; f++) boards[0][CASTLING][f] = NoRights;
15579       for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // first pass: Kings & e.p.
15580         if(rightsBoard[r][f]) {
15581           ChessSquare p = boards[0][r][f];
15582           if(p == (blackPlaysFirst ? WhitePawn : BlackPawn)) boards[0][EP_STATUS] = f;
15583           else if(p == king) boards[0][CASTLING][2] = f;
15584           else if(p == WHITE_TO_BLACK king) boards[0][CASTLING][5] = f;
15585           else rightsBoard[r][f] = 2; // mark for second pass
15586         }
15587       }
15588       for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // second pass: Rooks
15589         if(rightsBoard[r][f] == 2) {
15590           ChessSquare p = boards[0][r][f];
15591           if(p == WhiteRook) boards[0][CASTLING][(f < boards[0][CASTLING][2])] = f; else
15592           if(p == BlackRook) boards[0][CASTLING][(f < boards[0][CASTLING][5])+3] = f;
15593         }
15594       }
15595     }
15596     SendToProgram("force\n", &first);
15597     if (blackPlaysFirst) {
15598         safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
15599         safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
15600         currentMove = forwardMostMove = backwardMostMove = 1;
15601         CopyBoard(boards[1], boards[0]);
15602     } else {
15603         currentMove = forwardMostMove = backwardMostMove = 0;
15604     }
15605     SendBoard(&first, forwardMostMove);
15606     if (appData.debugMode) {
15607         fprintf(debugFP, "EditPosDone\n");
15608     }
15609     DisplayTitle("");
15610     DisplayMessage("", "");
15611     timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15612     timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15613     gameMode = EditGame;
15614     ModeHighlight();
15615     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15616     ClearHighlights(); /* [AS] */
15617 }
15618
15619 /* Pause for `ms' milliseconds */
15620 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15621 void
15622 TimeDelay (long ms)
15623 {
15624     TimeMark m1, m2;
15625
15626     GetTimeMark(&m1);
15627     do {
15628         GetTimeMark(&m2);
15629     } while (SubtractTimeMarks(&m2, &m1) < ms);
15630 }
15631
15632 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15633 void
15634 SendMultiLineToICS (char *buf)
15635 {
15636     char temp[MSG_SIZ+1], *p;
15637     int len;
15638
15639     len = strlen(buf);
15640     if (len > MSG_SIZ)
15641       len = MSG_SIZ;
15642
15643     strncpy(temp, buf, len);
15644     temp[len] = 0;
15645
15646     p = temp;
15647     while (*p) {
15648         if (*p == '\n' || *p == '\r')
15649           *p = ' ';
15650         ++p;
15651     }
15652
15653     strcat(temp, "\n");
15654     SendToICS(temp);
15655     SendToPlayer(temp, strlen(temp));
15656 }
15657
15658 void
15659 SetWhiteToPlayEvent ()
15660 {
15661     if (gameMode == EditPosition) {
15662         blackPlaysFirst = FALSE;
15663         DisplayBothClocks();    /* works because currentMove is 0 */
15664     } else if (gameMode == IcsExamining) {
15665         SendToICS(ics_prefix);
15666         SendToICS("tomove white\n");
15667     }
15668 }
15669
15670 void
15671 SetBlackToPlayEvent ()
15672 {
15673     if (gameMode == EditPosition) {
15674         blackPlaysFirst = TRUE;
15675         currentMove = 1;        /* kludge */
15676         DisplayBothClocks();
15677         currentMove = 0;
15678     } else if (gameMode == IcsExamining) {
15679         SendToICS(ics_prefix);
15680         SendToICS("tomove black\n");
15681     }
15682 }
15683
15684 void
15685 EditPositionMenuEvent (ChessSquare selection, int x, int y)
15686 {
15687     char buf[MSG_SIZ];
15688     ChessSquare piece = boards[0][y][x];
15689     static Board erasedBoard, currentBoard, menuBoard, nullBoard;
15690     static int lastVariant;
15691     int baseRank = BOARD_HEIGHT-1, hasRights = 0;
15692
15693     if (gameMode != EditPosition && gameMode != IcsExamining) return;
15694
15695     switch (selection) {
15696       case ClearBoard:
15697         fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
15698         MarkTargetSquares(1);
15699         CopyBoard(currentBoard, boards[0]);
15700         CopyBoard(menuBoard, initialPosition);
15701         if (gameMode == IcsExamining && ics_type == ICS_FICS) {
15702             SendToICS(ics_prefix);
15703             SendToICS("bsetup clear\n");
15704         } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
15705             SendToICS(ics_prefix);
15706             SendToICS("clearboard\n");
15707         } else {
15708             int nonEmpty = 0;
15709             for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
15710                 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
15711                 for (y = 0; y < BOARD_HEIGHT; y++) {
15712                     if (gameMode == IcsExamining) {
15713                         if (boards[currentMove][y][x] != EmptySquare) {
15714                           snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
15715                                     AAA + x, ONE + y);
15716                             SendToICS(buf);
15717                         }
15718                     } else if(boards[0][y][x] != DarkSquare) {
15719                         if(boards[0][y][x] != p) nonEmpty++;
15720                         boards[0][y][x] = p;
15721                     }
15722                 }
15723             }
15724             CopyBoard(rightsBoard, nullBoard);
15725             if(gameMode != IcsExamining) { // [HGM] editpos: cycle trough boards
15726                 int r, i;
15727                 for(r = 0; r < BOARD_HEIGHT; r++) {
15728                   for(x = BOARD_LEFT; x < BOARD_RGHT; x++) { // create 'menu board' by removing duplicates 
15729                     ChessSquare p = menuBoard[r][x];
15730                     for(y = x + 1; y < BOARD_RGHT; y++) if(menuBoard[r][y] == p) menuBoard[r][y] = EmptySquare;
15731                   }
15732                 }
15733                 menuBoard[CASTLING][0] = menuBoard[CASTLING][3] = NoRights; // h-side Rook was deleted
15734                 DisplayMessage("Clicking clock again restores position", "");
15735                 if(gameInfo.variant != lastVariant) lastVariant = gameInfo.variant, CopyBoard(erasedBoard, boards[0]);
15736                 if(!nonEmpty) { // asked to clear an empty board
15737                     CopyBoard(boards[0], menuBoard);
15738                 } else
15739                 if(CompareBoards(currentBoard, menuBoard)) { // asked to clear an empty board
15740                     CopyBoard(boards[0], initialPosition);
15741                 } else
15742                 if(CompareBoards(currentBoard, initialPosition) && !CompareBoards(currentBoard, erasedBoard)
15743                                                                  && !CompareBoards(nullBoard, erasedBoard)) {
15744                     CopyBoard(boards[0], erasedBoard);
15745                 } else
15746                     CopyBoard(erasedBoard, currentBoard);
15747
15748                 for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
15749                     rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
15750             }
15751         }
15752         if (gameMode == EditPosition) {
15753             DrawPosition(FALSE, boards[0]);
15754         }
15755         break;
15756
15757       case WhitePlay:
15758         SetWhiteToPlayEvent();
15759         break;
15760
15761       case BlackPlay:
15762         SetBlackToPlayEvent();
15763         break;
15764
15765       case EmptySquare:
15766         if (gameMode == IcsExamining) {
15767             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15768             snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
15769             SendToICS(buf);
15770         } else {
15771             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15772                 if(x == BOARD_LEFT-2) {
15773                     if(y < handSize-1-gameInfo.holdingsSize) break;
15774                     boards[0][y][1] = 0;
15775                 } else
15776                 if(x == BOARD_RGHT+1) {
15777                     if(y >= gameInfo.holdingsSize) break;
15778                     boards[0][y][BOARD_WIDTH-2] = 0;
15779                 } else break;
15780             }
15781             boards[0][y][x] = EmptySquare;
15782             DrawPosition(FALSE, boards[0]);
15783         }
15784         break;
15785
15786       case PromotePiece:
15787         if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
15788            piece >= (int)BlackPawn && piece < (int)BlackMan   ) {
15789             selection = (ChessSquare) (PROMOTED(piece));
15790         } else if(piece == EmptySquare) selection = WhiteSilver;
15791         else selection = (ChessSquare)((int)piece - 1);
15792         goto defaultlabel;
15793
15794       case DemotePiece:
15795         if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
15796            piece > (int)BlackMan && piece <= (int)BlackKing   ) {
15797             selection = (ChessSquare) (DEMOTED(piece));
15798         } else if(piece == EmptySquare) selection = BlackSilver;
15799         else selection = (ChessSquare)((int)piece + 1);
15800         goto defaultlabel;
15801
15802       case WhiteQueen:
15803       case BlackQueen:
15804         if(gameInfo.variant == VariantShatranj ||
15805            gameInfo.variant == VariantXiangqi  ||
15806            gameInfo.variant == VariantCourier  ||
15807            gameInfo.variant == VariantASEAN    ||
15808            gameInfo.variant == VariantMakruk     )
15809             selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
15810         goto defaultlabel;
15811
15812       case WhiteRook:
15813         baseRank = 0;
15814       case BlackRook:
15815         if(y == baseRank && (x == BOARD_LEFT || x == BOARD_RGHT-1 || appData.fischerCastling)) hasRights = 1;
15816         if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
15817         goto defaultlabel;
15818
15819       case WhiteKing:
15820         baseRank = 0;
15821       case BlackKing:
15822         if(gameInfo.variant == VariantXiangqi)
15823             selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
15824         if(gameInfo.variant == VariantKnightmate)
15825             selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
15826         if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
15827       default:
15828         defaultlabel:
15829         if (gameMode == IcsExamining) {
15830             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15831             snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
15832                      PieceToChar(selection), AAA + x, ONE + y);
15833             SendToICS(buf);
15834         } else {
15835             rightsBoard[y][x] = hasRights;
15836             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15837                 int n;
15838                 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
15839                     n = PieceToNumber(selection - BlackPawn);
15840                     if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
15841                     boards[0][handSize-1-n][0] = selection;
15842                     boards[0][handSize-1-n][1]++;
15843                 } else
15844                 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
15845                     n = PieceToNumber(selection);
15846                     if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
15847                     boards[0][n][BOARD_WIDTH-1] = selection;
15848                     boards[0][n][BOARD_WIDTH-2]++;
15849                 }
15850             } else
15851             boards[0][y][x] = selection;
15852             DrawPosition(TRUE, boards[0]);
15853             ClearHighlights();
15854             fromX = fromY = -1;
15855         }
15856         break;
15857     }
15858 }
15859
15860
15861 void
15862 DropMenuEvent (ChessSquare selection, int x, int y)
15863 {
15864     ChessMove moveType;
15865
15866     switch (gameMode) {
15867       case IcsPlayingWhite:
15868       case MachinePlaysBlack:
15869         if (!WhiteOnMove(currentMove)) {
15870             DisplayMoveError(_("It is Black's turn"));
15871             return;
15872         }
15873         moveType = WhiteDrop;
15874         break;
15875       case IcsPlayingBlack:
15876       case MachinePlaysWhite:
15877         if (WhiteOnMove(currentMove)) {
15878             DisplayMoveError(_("It is White's turn"));
15879             return;
15880         }
15881         moveType = BlackDrop;
15882         break;
15883       case EditGame:
15884         moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
15885         break;
15886       default:
15887         return;
15888     }
15889
15890     if (moveType == BlackDrop && selection < BlackPawn) {
15891       selection = (ChessSquare) ((int) selection
15892                                  + (int) BlackPawn - (int) WhitePawn);
15893     }
15894     if (boards[currentMove][y][x] != EmptySquare) {
15895         DisplayMoveError(_("That square is occupied"));
15896         return;
15897     }
15898
15899     FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
15900 }
15901
15902 void
15903 AcceptEvent ()
15904 {
15905     /* Accept a pending offer of any kind from opponent */
15906
15907     if (appData.icsActive) {
15908         SendToICS(ics_prefix);
15909         SendToICS("accept\n");
15910     } else if (cmailMsgLoaded) {
15911         if (currentMove == cmailOldMove &&
15912             commentList[cmailOldMove] != NULL &&
15913             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15914                    "Black offers a draw" : "White offers a draw")) {
15915             TruncateGame();
15916             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15917             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15918         } else {
15919             DisplayError(_("There is no pending offer on this move"), 0);
15920             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15921         }
15922     } else {
15923         /* Not used for offers from chess program */
15924     }
15925 }
15926
15927 void
15928 DeclineEvent ()
15929 {
15930     /* Decline a pending offer of any kind from opponent */
15931
15932     if (appData.icsActive) {
15933         SendToICS(ics_prefix);
15934         SendToICS("decline\n");
15935     } else if (cmailMsgLoaded) {
15936         if (currentMove == cmailOldMove &&
15937             commentList[cmailOldMove] != NULL &&
15938             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15939                    "Black offers a draw" : "White offers a draw")) {
15940 #ifdef NOTDEF
15941             AppendComment(cmailOldMove, "Draw declined", TRUE);
15942             DisplayComment(cmailOldMove - 1, "Draw declined");
15943 #endif /*NOTDEF*/
15944         } else {
15945             DisplayError(_("There is no pending offer on this move"), 0);
15946         }
15947     } else {
15948         /* Not used for offers from chess program */
15949     }
15950 }
15951
15952 void
15953 RematchEvent ()
15954 {
15955     /* Issue ICS rematch command */
15956     if (appData.icsActive) {
15957         SendToICS(ics_prefix);
15958         SendToICS("rematch\n");
15959     }
15960 }
15961
15962 void
15963 CallFlagEvent ()
15964 {
15965     /* Call your opponent's flag (claim a win on time) */
15966     if (appData.icsActive) {
15967         SendToICS(ics_prefix);
15968         SendToICS("flag\n");
15969     } else {
15970         switch (gameMode) {
15971           default:
15972             return;
15973           case MachinePlaysWhite:
15974             if (whiteFlag) {
15975                 if (blackFlag)
15976                   GameEnds(GameIsDrawn, "Both players ran out of time",
15977                            GE_PLAYER);
15978                 else
15979                   GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
15980             } else {
15981                 DisplayError(_("Your opponent is not out of time"), 0);
15982             }
15983             break;
15984           case MachinePlaysBlack:
15985             if (blackFlag) {
15986                 if (whiteFlag)
15987                   GameEnds(GameIsDrawn, "Both players ran out of time",
15988                            GE_PLAYER);
15989                 else
15990                   GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
15991             } else {
15992                 DisplayError(_("Your opponent is not out of time"), 0);
15993             }
15994             break;
15995         }
15996     }
15997 }
15998
15999 void
16000 ClockClick (int which)
16001 {       // [HGM] code moved to back-end from winboard.c
16002         if(which) { // black clock
16003           if (gameMode == EditPosition || gameMode == IcsExamining) {
16004             if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
16005             SetBlackToPlayEvent();
16006           } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
16007                       gameMode == MachinePlaysBlack && PosFlags(0) & F_NULL_MOVE && !blackFlag && !shiftKey) && WhiteOnMove(currentMove)) {
16008           UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
16009           } else if (shiftKey) {
16010             AdjustClock(which, -1);
16011           } else if (gameMode == IcsPlayingWhite ||
16012                      gameMode == MachinePlaysBlack) {
16013             CallFlagEvent();
16014           }
16015         } else { // white clock
16016           if (gameMode == EditPosition || gameMode == IcsExamining) {
16017             if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
16018             SetWhiteToPlayEvent();
16019           } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
16020                       gameMode == MachinePlaysWhite && PosFlags(0) & F_NULL_MOVE && !whiteFlag && !shiftKey) && !WhiteOnMove(currentMove)) {
16021           UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
16022           } else if (shiftKey) {
16023             AdjustClock(which, -1);
16024           } else if (gameMode == IcsPlayingBlack ||
16025                    gameMode == MachinePlaysWhite) {
16026             CallFlagEvent();
16027           }
16028         }
16029 }
16030
16031 void
16032 DrawEvent ()
16033 {
16034     /* Offer draw or accept pending draw offer from opponent */
16035
16036     if (appData.icsActive) {
16037         /* Note: tournament rules require draw offers to be
16038            made after you make your move but before you punch
16039            your clock.  Currently ICS doesn't let you do that;
16040            instead, you immediately punch your clock after making
16041            a move, but you can offer a draw at any time. */
16042
16043         SendToICS(ics_prefix);
16044         SendToICS("draw\n");
16045         userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
16046     } else if (cmailMsgLoaded) {
16047         if (currentMove == cmailOldMove &&
16048             commentList[cmailOldMove] != NULL &&
16049             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
16050                    "Black offers a draw" : "White offers a draw")) {
16051             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
16052             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
16053         } else if (currentMove == cmailOldMove + 1) {
16054             char *offer = WhiteOnMove(cmailOldMove) ?
16055               "White offers a draw" : "Black offers a draw";
16056             AppendComment(currentMove, offer, TRUE);
16057             DisplayComment(currentMove - 1, offer);
16058             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
16059         } else {
16060             DisplayError(_("You must make your move before offering a draw"), 0);
16061             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
16062         }
16063     } else if (first.offeredDraw) {
16064         GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
16065     } else {
16066         if (first.sendDrawOffers) {
16067             SendToProgram("draw\n", &first);
16068             userOfferedDraw = TRUE;
16069         }
16070     }
16071 }
16072
16073 void
16074 AdjournEvent ()
16075 {
16076     /* Offer Adjourn or accept pending Adjourn offer from opponent */
16077
16078     if (appData.icsActive) {
16079         SendToICS(ics_prefix);
16080         SendToICS("adjourn\n");
16081     } else {
16082         /* Currently GNU Chess doesn't offer or accept Adjourns */
16083     }
16084 }
16085
16086
16087 void
16088 AbortEvent ()
16089 {
16090     /* Offer Abort or accept pending Abort offer from opponent */
16091
16092     if (appData.icsActive) {
16093         SendToICS(ics_prefix);
16094         SendToICS("abort\n");
16095     } else {
16096         GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
16097     }
16098 }
16099
16100 void
16101 ResignEvent ()
16102 {
16103     /* Resign.  You can do this even if it's not your turn. */
16104
16105     if (appData.icsActive) {
16106         SendToICS(ics_prefix);
16107         SendToICS("resign\n");
16108     } else {
16109         switch (gameMode) {
16110           case MachinePlaysWhite:
16111             GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
16112             break;
16113           case MachinePlaysBlack:
16114             GameEnds(BlackWins, "White resigns", GE_PLAYER);
16115             break;
16116           case EditGame:
16117             if (cmailMsgLoaded) {
16118                 TruncateGame();
16119                 if (WhiteOnMove(cmailOldMove)) {
16120                     GameEnds(BlackWins, "White resigns", GE_PLAYER);
16121                 } else {
16122                     GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
16123                 }
16124                 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
16125             }
16126             break;
16127           default:
16128             break;
16129         }
16130     }
16131 }
16132
16133
16134 void
16135 StopObservingEvent ()
16136 {
16137     /* Stop observing current games */
16138     SendToICS(ics_prefix);
16139     SendToICS("unobserve\n");
16140 }
16141
16142 void
16143 StopExaminingEvent ()
16144 {
16145     /* Stop observing current game */
16146     SendToICS(ics_prefix);
16147     SendToICS("unexamine\n");
16148 }
16149
16150 void
16151 ForwardInner (int target)
16152 {
16153     int limit; int oldSeekGraphUp = seekGraphUp;
16154
16155     if (appData.debugMode)
16156         fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
16157                 target, currentMove, forwardMostMove);
16158
16159     if (gameMode == EditPosition)
16160       return;
16161
16162     seekGraphUp = FALSE;
16163     MarkTargetSquares(1);
16164     fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
16165
16166     if (gameMode == PlayFromGameFile && !pausing)
16167       PauseEvent();
16168
16169     if (gameMode == IcsExamining && pausing)
16170       limit = pauseExamForwardMostMove;
16171     else
16172       limit = forwardMostMove;
16173
16174     if (target > limit) target = limit;
16175
16176     if (target > 0 && moveList[target - 1][0]) {
16177         int fromX, fromY, toX, toY;
16178         toX = moveList[target - 1][2] - AAA;
16179         toY = moveList[target - 1][3] - ONE;
16180         if (moveList[target - 1][1] == '@') {
16181             if (appData.highlightLastMove) {
16182                 SetHighlights(-1, -1, toX, toY);
16183             }
16184         } else {
16185             fromX = moveList[target - 1][0] - AAA;
16186             fromY = moveList[target - 1][1] - ONE;
16187             if (target == currentMove + 1) {
16188                 if(moveList[target - 1][4] == ';') { // multi-leg
16189                     killX = moveList[target - 1][5] - AAA;
16190                     killY = moveList[target - 1][6] - ONE;
16191                 }
16192                 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
16193                 killX = killY = -1;
16194             }
16195             if (appData.highlightLastMove) {
16196                 SetHighlights(fromX, fromY, toX, toY);
16197             }
16198         }
16199     }
16200     if (gameMode == EditGame || gameMode == AnalyzeMode ||
16201         gameMode == Training || gameMode == PlayFromGameFile ||
16202         gameMode == AnalyzeFile) {
16203         while (currentMove < target) {
16204             if(second.analyzing) SendMoveToProgram(currentMove, &second);
16205             SendMoveToProgram(currentMove++, &first);
16206         }
16207     } else {
16208         currentMove = target;
16209     }
16210
16211     if (gameMode == EditGame || gameMode == EndOfGame) {
16212         whiteTimeRemaining = timeRemaining[0][currentMove];
16213         blackTimeRemaining = timeRemaining[1][currentMove];
16214     }
16215     DisplayBothClocks();
16216     DisplayMove(currentMove - 1);
16217     DrawPosition(oldSeekGraphUp, boards[currentMove]);
16218     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
16219     if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
16220         DisplayComment(currentMove - 1, commentList[currentMove]);
16221     }
16222     ClearMap(); // [HGM] exclude: invalidate map
16223 }
16224
16225
16226 void
16227 ForwardEvent ()
16228 {
16229     if (gameMode == IcsExamining && !pausing) {
16230         SendToICS(ics_prefix);
16231         SendToICS("forward\n");
16232     } else {
16233         ForwardInner(currentMove + 1);
16234     }
16235 }
16236
16237 void
16238 ToEndEvent ()
16239 {
16240     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16241         /* to optimze, we temporarily turn off analysis mode while we feed
16242          * the remaining moves to the engine. Otherwise we get analysis output
16243          * after each move.
16244          */
16245         if (first.analysisSupport) {
16246           SendToProgram("exit\nforce\n", &first);
16247           first.analyzing = FALSE;
16248         }
16249     }
16250
16251     if (gameMode == IcsExamining && !pausing) {
16252         SendToICS(ics_prefix);
16253         SendToICS("forward 999999\n");
16254     } else {
16255         ForwardInner(forwardMostMove);
16256     }
16257
16258     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16259         /* we have fed all the moves, so reactivate analysis mode */
16260         SendToProgram("analyze\n", &first);
16261         first.analyzing = TRUE;
16262         /*first.maybeThinking = TRUE;*/
16263         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
16264     }
16265 }
16266
16267 void
16268 BackwardInner (int target)
16269 {
16270     int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
16271
16272     if (appData.debugMode)
16273         fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
16274                 target, currentMove, forwardMostMove);
16275
16276     if (gameMode == EditPosition) return;
16277     seekGraphUp = FALSE;
16278     MarkTargetSquares(1);
16279     fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
16280     if (currentMove <= backwardMostMove) {
16281         ClearHighlights();
16282         DrawPosition(full_redraw, boards[currentMove]);
16283         return;
16284     }
16285     if (gameMode == PlayFromGameFile && !pausing)
16286       PauseEvent();
16287
16288     if (moveList[target][0]) {
16289         int fromX, fromY, toX, toY;
16290         toX = moveList[target][2] - AAA;
16291         toY = moveList[target][3] - ONE;
16292         if (moveList[target][1] == '@') {
16293             if (appData.highlightLastMove) {
16294                 SetHighlights(-1, -1, toX, toY);
16295             }
16296         } else {
16297             fromX = moveList[target][0] - AAA;
16298             fromY = moveList[target][1] - ONE;
16299             if (target == currentMove - 1) {
16300                 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
16301             }
16302             if (appData.highlightLastMove) {
16303                 SetHighlights(fromX, fromY, toX, toY);
16304             }
16305         }
16306     }
16307     if (gameMode == EditGame || gameMode==AnalyzeMode ||
16308         gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
16309         while (currentMove > target) {
16310             if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
16311                 // null move cannot be undone. Reload program with move history before it.
16312                 int i;
16313                 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
16314                     if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
16315                 }
16316                 SendBoard(&first, i);
16317               if(second.analyzing) SendBoard(&second, i);
16318                 for(currentMove=i; currentMove<target; currentMove++) {
16319                     SendMoveToProgram(currentMove, &first);
16320                     if(second.analyzing) SendMoveToProgram(currentMove, &second);
16321                 }
16322                 break;
16323             }
16324             SendToBoth("undo\n");
16325             currentMove--;
16326         }
16327     } else {
16328         currentMove = target;
16329     }
16330
16331     if (gameMode == EditGame || gameMode == EndOfGame) {
16332         whiteTimeRemaining = timeRemaining[0][currentMove];
16333         blackTimeRemaining = timeRemaining[1][currentMove];
16334     }
16335     DisplayBothClocks();
16336     DisplayMove(currentMove - 1);
16337     DrawPosition(full_redraw, boards[currentMove]);
16338     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
16339     // [HGM] PV info: routine tests if comment empty
16340     DisplayComment(currentMove - 1, commentList[currentMove]);
16341     ClearMap(); // [HGM] exclude: invalidate map
16342 }
16343
16344 void
16345 BackwardEvent ()
16346 {
16347     if (gameMode == IcsExamining && !pausing) {
16348         SendToICS(ics_prefix);
16349         SendToICS("backward\n");
16350     } else {
16351         BackwardInner(currentMove - 1);
16352     }
16353 }
16354
16355 void
16356 ToStartEvent ()
16357 {
16358     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16359         /* to optimize, we temporarily turn off analysis mode while we undo
16360          * all the moves. Otherwise we get analysis output after each undo.
16361          */
16362         if (first.analysisSupport) {
16363           SendToProgram("exit\nforce\n", &first);
16364           first.analyzing = FALSE;
16365         }
16366     }
16367
16368     if (gameMode == IcsExamining && !pausing) {
16369         SendToICS(ics_prefix);
16370         SendToICS("backward 999999\n");
16371     } else {
16372         BackwardInner(backwardMostMove);
16373     }
16374
16375     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16376         /* we have fed all the moves, so reactivate analysis mode */
16377         SendToProgram("analyze\n", &first);
16378         first.analyzing = TRUE;
16379         /*first.maybeThinking = TRUE;*/
16380         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
16381     }
16382 }
16383
16384 void
16385 ToNrEvent (int to)
16386 {
16387   if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
16388   if (to >= forwardMostMove) to = forwardMostMove;
16389   if (to <= backwardMostMove) to = backwardMostMove;
16390   if (to < currentMove) {
16391     BackwardInner(to);
16392   } else {
16393     ForwardInner(to);
16394   }
16395 }
16396
16397 void
16398 RevertEvent (Boolean annotate)
16399 {
16400     if(PopTail(annotate)) { // [HGM] vari: restore old game tail
16401         return;
16402     }
16403     if (gameMode != IcsExamining) {
16404         DisplayError(_("You are not examining a game"), 0);
16405         return;
16406     }
16407     if (pausing) {
16408         DisplayError(_("You can't revert while pausing"), 0);
16409         return;
16410     }
16411     SendToICS(ics_prefix);
16412     SendToICS("revert\n");
16413 }
16414
16415 void
16416 RetractMoveEvent ()
16417 {
16418     switch (gameMode) {
16419       case MachinePlaysWhite:
16420       case MachinePlaysBlack:
16421         if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
16422             DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
16423             return;
16424         }
16425         if (forwardMostMove < 2) return;
16426         currentMove = forwardMostMove = forwardMostMove - 2;
16427         whiteTimeRemaining = timeRemaining[0][currentMove];
16428         blackTimeRemaining = timeRemaining[1][currentMove];
16429         DisplayBothClocks();
16430         DisplayMove(currentMove - 1);
16431         ClearHighlights();/*!! could figure this out*/
16432         DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
16433         SendToProgram("remove\n", &first);
16434         /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
16435         break;
16436
16437       case BeginningOfGame:
16438       default:
16439         break;
16440
16441       case IcsPlayingWhite:
16442       case IcsPlayingBlack:
16443         if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
16444             SendToICS(ics_prefix);
16445             SendToICS("takeback 2\n");
16446         } else {
16447             SendToICS(ics_prefix);
16448             SendToICS("takeback 1\n");
16449         }
16450         break;
16451     }
16452 }
16453
16454 void
16455 MoveNowEvent ()
16456 {
16457     ChessProgramState *cps;
16458
16459     switch (gameMode) {
16460       case MachinePlaysWhite:
16461         if (!WhiteOnMove(forwardMostMove)) {
16462             DisplayError(_("It is your turn"), 0);
16463             return;
16464         }
16465         cps = &first;
16466         break;
16467       case MachinePlaysBlack:
16468         if (WhiteOnMove(forwardMostMove)) {
16469             DisplayError(_("It is your turn"), 0);
16470             return;
16471         }
16472         cps = &first;
16473         break;
16474       case TwoMachinesPlay:
16475         if (WhiteOnMove(forwardMostMove) ==
16476             (first.twoMachinesColor[0] == 'w')) {
16477             cps = &first;
16478         } else {
16479             cps = &second;
16480         }
16481         break;
16482       case BeginningOfGame:
16483       default:
16484         return;
16485     }
16486     SendToProgram("?\n", cps);
16487 }
16488
16489 void
16490 TruncateGameEvent ()
16491 {
16492     EditGameEvent();
16493     if (gameMode != EditGame) return;
16494     TruncateGame();
16495 }
16496
16497 void
16498 TruncateGame ()
16499 {
16500     CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
16501     if (forwardMostMove > currentMove) {
16502         if (gameInfo.resultDetails != NULL) {
16503             free(gameInfo.resultDetails);
16504             gameInfo.resultDetails = NULL;
16505             gameInfo.result = GameUnfinished;
16506         }
16507         forwardMostMove = currentMove;
16508         HistorySet(parseList, backwardMostMove, forwardMostMove,
16509                    currentMove-1);
16510     }
16511 }
16512
16513 void
16514 HintEvent ()
16515 {
16516     if (appData.noChessProgram) return;
16517     switch (gameMode) {
16518       case MachinePlaysWhite:
16519         if (WhiteOnMove(forwardMostMove)) {
16520             DisplayError(_("Wait until your turn."), 0);
16521             return;
16522         }
16523         break;
16524       case BeginningOfGame:
16525       case MachinePlaysBlack:
16526         if (!WhiteOnMove(forwardMostMove)) {
16527             DisplayError(_("Wait until your turn."), 0);
16528             return;
16529         }
16530         break;
16531       default:
16532         DisplayError(_("No hint available"), 0);
16533         return;
16534     }
16535     SendToProgram("hint\n", &first);
16536     hintRequested = TRUE;
16537 }
16538
16539 int
16540 SaveSelected (FILE *g, int dummy, char *dummy2)
16541 {
16542     ListGame * lg = (ListGame *) gameList.head;
16543     int nItem, cnt=0;
16544     FILE *f;
16545
16546     if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
16547         DisplayError(_("Game list not loaded or empty"), 0);
16548         return 0;
16549     }
16550
16551     creatingBook = TRUE; // suppresses stuff during load game
16552
16553     /* Get list size */
16554     for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16555         if(lg->position >= 0) { // selected?
16556             LoadGame(f, nItem, "", TRUE);
16557             SaveGamePGN2(g); // leaves g open
16558             cnt++; DoEvents();
16559         }
16560         lg = (ListGame *) lg->node.succ;
16561     }
16562
16563     fclose(g);
16564     creatingBook = FALSE;
16565
16566     return cnt;
16567 }
16568
16569 void
16570 CreateBookEvent ()
16571 {
16572     ListGame * lg = (ListGame *) gameList.head;
16573     FILE *f, *g;
16574     int nItem;
16575     static int secondTime = FALSE;
16576
16577     if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
16578         DisplayError(_("Game list not loaded or empty"), 0);
16579         return;
16580     }
16581
16582     if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
16583         fclose(g);
16584         secondTime++;
16585         DisplayNote(_("Book file exists! Try again for overwrite."));
16586         return;
16587     }
16588
16589     creatingBook = TRUE;
16590     secondTime = FALSE;
16591
16592     /* Get list size */
16593     for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16594         if(lg->position >= 0) {
16595             LoadGame(f, nItem, "", TRUE);
16596             AddGameToBook(TRUE);
16597             DoEvents();
16598         }
16599         lg = (ListGame *) lg->node.succ;
16600     }
16601
16602     creatingBook = FALSE;
16603     FlushBook();
16604 }
16605
16606 void
16607 BookEvent ()
16608 {
16609     if (appData.noChessProgram) return;
16610     switch (gameMode) {
16611       case MachinePlaysWhite:
16612         if (WhiteOnMove(forwardMostMove)) {
16613             DisplayError(_("Wait until your turn."), 0);
16614             return;
16615         }
16616         break;
16617       case BeginningOfGame:
16618       case MachinePlaysBlack:
16619         if (!WhiteOnMove(forwardMostMove)) {
16620             DisplayError(_("Wait until your turn."), 0);
16621             return;
16622         }
16623         break;
16624       case EditPosition:
16625         EditPositionDone(TRUE);
16626         break;
16627       case TwoMachinesPlay:
16628         return;
16629       default:
16630         break;
16631     }
16632     SendToProgram("bk\n", &first);
16633     bookOutput[0] = NULLCHAR;
16634     bookRequested = TRUE;
16635 }
16636
16637 void
16638 AboutGameEvent ()
16639 {
16640     char *tags = PGNTags(&gameInfo);
16641     TagsPopUp(tags, CmailMsg());
16642     free(tags);
16643 }
16644
16645 /* end button procedures */
16646
16647 void
16648 PrintPosition (FILE *fp, int move)
16649 {
16650     int i, j;
16651
16652     for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16653         for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16654             char c = PieceToChar(boards[move][i][j]);
16655             fputc(c == '?' ? '.' : c, fp);
16656             fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
16657         }
16658     }
16659     if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
16660       fprintf(fp, "white to play\n");
16661     else
16662       fprintf(fp, "black to play\n");
16663 }
16664
16665 void
16666 PrintOpponents (FILE *fp)
16667 {
16668     if (gameInfo.white != NULL) {
16669         fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
16670     } else {
16671         fprintf(fp, "\n");
16672     }
16673 }
16674
16675 /* Find last component of program's own name, using some heuristics */
16676 void
16677 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
16678 {
16679     char *p, *q, c;
16680     int local = (strcmp(host, "localhost") == 0);
16681     while (!local && (p = strchr(prog, ';')) != NULL) {
16682         p++;
16683         while (*p == ' ') p++;
16684         prog = p;
16685     }
16686     if (*prog == '"' || *prog == '\'') {
16687         q = strchr(prog + 1, *prog);
16688     } else {
16689         q = strchr(prog, ' ');
16690     }
16691     if (q == NULL) q = prog + strlen(prog);
16692     p = q;
16693     while (p >= prog && *p != '/' && *p != '\\') p--;
16694     p++;
16695     if(p == prog && *p == '"') p++;
16696     c = *q; *q = 0;
16697     if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
16698     memcpy(buf, p, q - p);
16699     buf[q - p] = NULLCHAR;
16700     if (!local) {
16701         strcat(buf, "@");
16702         strcat(buf, host);
16703     }
16704 }
16705
16706 char *
16707 TimeControlTagValue ()
16708 {
16709     char buf[MSG_SIZ];
16710     if (!appData.clockMode) {
16711       safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
16712     } else if (movesPerSession > 0) {
16713       snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
16714     } else if (timeIncrement == 0) {
16715       snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
16716     } else {
16717       snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
16718     }
16719     return StrSave(buf);
16720 }
16721
16722 void
16723 SetGameInfo ()
16724 {
16725     /* This routine is used only for certain modes */
16726     VariantClass v = gameInfo.variant;
16727     ChessMove r = GameUnfinished;
16728     char *p = NULL;
16729
16730     if(keepInfo) return;
16731
16732     if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
16733         r = gameInfo.result;
16734         p = gameInfo.resultDetails;
16735         gameInfo.resultDetails = NULL;
16736     }
16737     ClearGameInfo(&gameInfo);
16738     gameInfo.variant = v;
16739
16740     switch (gameMode) {
16741       case MachinePlaysWhite:
16742         gameInfo.event = StrSave( appData.pgnEventHeader );
16743         gameInfo.site = StrSave(HostName());
16744         gameInfo.date = PGNDate();
16745         gameInfo.round = StrSave("-");
16746         gameInfo.white = StrSave(first.tidy);
16747         gameInfo.black = StrSave(UserName());
16748         gameInfo.timeControl = TimeControlTagValue();
16749         break;
16750
16751       case MachinePlaysBlack:
16752         gameInfo.event = StrSave( appData.pgnEventHeader );
16753         gameInfo.site = StrSave(HostName());
16754         gameInfo.date = PGNDate();
16755         gameInfo.round = StrSave("-");
16756         gameInfo.white = StrSave(UserName());
16757         gameInfo.black = StrSave(first.tidy);
16758         gameInfo.timeControl = TimeControlTagValue();
16759         break;
16760
16761       case TwoMachinesPlay:
16762         gameInfo.event = StrSave( appData.pgnEventHeader );
16763         gameInfo.site = StrSave(HostName());
16764         gameInfo.date = PGNDate();
16765         if (roundNr > 0) {
16766             char buf[MSG_SIZ];
16767             snprintf(buf, MSG_SIZ, "%d", roundNr);
16768             gameInfo.round = StrSave(buf);
16769         } else {
16770             gameInfo.round = StrSave("-");
16771         }
16772         if (first.twoMachinesColor[0] == 'w') {
16773             gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16774             gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16775         } else {
16776             gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16777             gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16778         }
16779         gameInfo.timeControl = TimeControlTagValue();
16780         break;
16781
16782       case EditGame:
16783         gameInfo.event = StrSave("Edited game");
16784         gameInfo.site = StrSave(HostName());
16785         gameInfo.date = PGNDate();
16786         gameInfo.round = StrSave("-");
16787         gameInfo.white = StrSave("-");
16788         gameInfo.black = StrSave("-");
16789         gameInfo.result = r;
16790         gameInfo.resultDetails = p;
16791         break;
16792
16793       case EditPosition:
16794         gameInfo.event = StrSave("Edited position");
16795         gameInfo.site = StrSave(HostName());
16796         gameInfo.date = PGNDate();
16797         gameInfo.round = StrSave("-");
16798         gameInfo.white = StrSave("-");
16799         gameInfo.black = StrSave("-");
16800         break;
16801
16802       case IcsPlayingWhite:
16803       case IcsPlayingBlack:
16804       case IcsObserving:
16805       case IcsExamining:
16806         break;
16807
16808       case PlayFromGameFile:
16809         gameInfo.event = StrSave("Game from non-PGN file");
16810         gameInfo.site = StrSave(HostName());
16811         gameInfo.date = PGNDate();
16812         gameInfo.round = StrSave("-");
16813         gameInfo.white = StrSave("?");
16814         gameInfo.black = StrSave("?");
16815         break;
16816
16817       default:
16818         break;
16819     }
16820 }
16821
16822 void
16823 ReplaceComment (int index, char *text)
16824 {
16825     int len;
16826     char *p;
16827     float score;
16828
16829     if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
16830        pvInfoList[index-1].depth == len &&
16831        fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
16832        (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
16833     while (*text == '\n') text++;
16834     len = strlen(text);
16835     while (len > 0 && text[len - 1] == '\n') len--;
16836
16837     if (commentList[index] != NULL)
16838       free(commentList[index]);
16839
16840     if (len == 0) {
16841         commentList[index] = NULL;
16842         return;
16843     }
16844   if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
16845       *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
16846       *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
16847     commentList[index] = (char *) malloc(len + 2);
16848     strncpy(commentList[index], text, len);
16849     commentList[index][len] = '\n';
16850     commentList[index][len + 1] = NULLCHAR;
16851   } else {
16852     // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
16853     char *p;
16854     commentList[index] = (char *) malloc(len + 7);
16855     safeStrCpy(commentList[index], "{\n", 3);
16856     safeStrCpy(commentList[index]+2, text, len+1);
16857     commentList[index][len+2] = NULLCHAR;
16858     while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
16859     strcat(commentList[index], "\n}\n");
16860   }
16861 }
16862
16863 void
16864 CrushCRs (char *text)
16865 {
16866   char *p = text;
16867   char *q = text;
16868   char ch;
16869
16870   do {
16871     ch = *p++;
16872     if (ch == '\r') continue;
16873     *q++ = ch;
16874   } while (ch != '\0');
16875 }
16876
16877 void
16878 AppendComment (int index, char *text, Boolean addBraces)
16879 /* addBraces  tells if we should add {} */
16880 {
16881     int oldlen, len;
16882     char *old;
16883
16884 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
16885     if(addBraces == 3) addBraces = 0; else // force appending literally
16886     text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
16887
16888     CrushCRs(text);
16889     while (*text == '\n') text++;
16890     len = strlen(text);
16891     while (len > 0 && text[len - 1] == '\n') len--;
16892     text[len] = NULLCHAR;
16893
16894     if (len == 0) return;
16895
16896     if (commentList[index] != NULL) {
16897       Boolean addClosingBrace = addBraces;
16898         old = commentList[index];
16899         oldlen = strlen(old);
16900         while(commentList[index][oldlen-1] ==  '\n')
16901           commentList[index][--oldlen] = NULLCHAR;
16902         commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
16903         safeStrCpy(commentList[index], old, oldlen + len + 6);
16904         free(old);
16905         // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
16906         if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
16907           if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
16908           while (*text == '\n') { text++; len--; }
16909           commentList[index][--oldlen] = NULLCHAR;
16910       }
16911         if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
16912         else          strcat(commentList[index], "\n");
16913         strcat(commentList[index], text);
16914         if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
16915         else          strcat(commentList[index], "\n");
16916     } else {
16917         commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
16918         if(addBraces)
16919           safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
16920         else commentList[index][0] = NULLCHAR;
16921         strcat(commentList[index], text);
16922         strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
16923         if(addBraces == TRUE) strcat(commentList[index], "}\n");
16924     }
16925 }
16926
16927 static char *
16928 FindStr (char * text, char * sub_text)
16929 {
16930     char * result = strstr( text, sub_text );
16931
16932     if( result != NULL ) {
16933         result += strlen( sub_text );
16934     }
16935
16936     return result;
16937 }
16938
16939 /* [AS] Try to extract PV info from PGN comment */
16940 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
16941 char *
16942 GetInfoFromComment (int index, char * text)
16943 {
16944     char * sep = text, *p;
16945
16946     if( text != NULL && index > 0 ) {
16947         int score = 0;
16948         int depth = 0;
16949         int time = -1, sec = 0, deci;
16950         char * s_eval = FindStr( text, "[%eval " );
16951         char * s_emt = FindStr( text, "[%emt " );
16952 #if 0
16953         if( s_eval != NULL || s_emt != NULL ) {
16954 #else
16955         if(0) { // [HGM] this code is not finished, and could actually be detrimental
16956 #endif
16957             /* New style */
16958             char delim;
16959
16960             if( s_eval != NULL ) {
16961                 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
16962                     return text;
16963                 }
16964
16965                 if( delim != ']' ) {
16966                     return text;
16967                 }
16968             }
16969
16970             if( s_emt != NULL ) {
16971             }
16972                 return text;
16973         }
16974         else {
16975             /* We expect something like: [+|-]nnn.nn/dd */
16976             int score_lo = 0;
16977
16978             if(*text != '{') return text; // [HGM] braces: must be normal comment
16979
16980             sep = strchr( text, '/' );
16981             if( sep == NULL || sep < (text+4) ) {
16982                 return text;
16983             }
16984
16985             p = text;
16986             if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
16987             if(p[1] == '(') { // comment starts with PV
16988                p = strchr(p, ')'); // locate end of PV
16989                if(p == NULL || sep < p+5) return text;
16990                // at this point we have something like "{(.*) +0.23/6 ..."
16991                p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
16992                *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
16993                // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
16994             }
16995             time = -1; sec = -1; deci = -1;
16996             if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
16997                 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
16998                 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
16999                 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3   ) {
17000                 return text;
17001             }
17002
17003             if( score_lo < 0 || score_lo >= 100 ) {
17004                 return text;
17005             }
17006
17007             if(sec >= 0) time = 600*time + 10*sec; else
17008             if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
17009
17010             score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
17011
17012             /* [HGM] PV time: now locate end of PV info */
17013             while( *++sep >= '0' && *sep <= '9'); // strip depth
17014             if(time >= 0)
17015             while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
17016             if(sec >= 0)
17017             while( *++sep >= '0' && *sep <= '9'); // strip seconds
17018             if(deci >= 0)
17019             while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
17020             while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
17021         }
17022
17023         if( depth <= 0 ) {
17024             return text;
17025         }
17026
17027         if( time < 0 ) {
17028             time = -1;
17029         }
17030
17031         pvInfoList[index-1].depth = depth;
17032         pvInfoList[index-1].score = score;
17033         pvInfoList[index-1].time  = 10*time; // centi-sec
17034         if(*sep == '}') *sep = 0; else *--sep = '{';
17035         if(p != text) {
17036             while(*p++ = *sep++)
17037                                 ;
17038             sep = text;
17039         } // squeeze out space between PV and comment, and return both
17040     }
17041     return sep;
17042 }
17043
17044 void
17045 SendToProgram (char *message, ChessProgramState *cps)
17046 {
17047     int count, outCount, error;
17048     char buf[MSG_SIZ];
17049
17050     if (cps->pr == NoProc) return;
17051     Attention(cps);
17052
17053     if (appData.debugMode) {
17054         TimeMark now;
17055         GetTimeMark(&now);
17056         fprintf(debugFP, "%ld >%-6s: %s",
17057                 SubtractTimeMarks(&now, &programStartTime),
17058                 cps->which, message);
17059         if(serverFP)
17060             fprintf(serverFP, "%ld >%-6s: %s",
17061                 SubtractTimeMarks(&now, &programStartTime),
17062                 cps->which, message), fflush(serverFP);
17063     }
17064
17065     count = strlen(message);
17066     outCount = OutputToProcess(cps->pr, message, count, &error);
17067     if (outCount < count && !exiting
17068                          && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
17069       if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
17070       snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
17071         if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
17072             if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
17073                 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
17074                 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
17075                 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
17076             } else {
17077                 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
17078                 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
17079                 gameInfo.result = res;
17080             }
17081             gameInfo.resultDetails = StrSave(buf);
17082         }
17083         if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
17084         if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
17085     }
17086 }
17087
17088 void
17089 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
17090 {
17091     char *end_str;
17092     char buf[MSG_SIZ];
17093     ChessProgramState *cps = (ChessProgramState *)closure;
17094
17095     if (isr != cps->isr) return; /* Killed intentionally */
17096     if (count <= 0) {
17097         if (count == 0) {
17098             RemoveInputSource(cps->isr);
17099             snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
17100                     _(cps->which), cps->program);
17101             if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
17102             if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
17103                 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
17104                     snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
17105                     if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
17106                     gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
17107                 } else {
17108                     ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
17109                     if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
17110                     gameInfo.result = res;
17111                 }
17112                 gameInfo.resultDetails = StrSave(buf);
17113             }
17114             if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
17115             if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
17116         } else {
17117             snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
17118                     _(cps->which), cps->program);
17119             RemoveInputSource(cps->isr);
17120
17121             /* [AS] Program is misbehaving badly... kill it */
17122             if( count == -2 ) {
17123                 DestroyChildProcess( cps->pr, 9 );
17124                 cps->pr = NoProc;
17125             }
17126
17127             if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
17128         }
17129         return;
17130     }
17131
17132     if ((end_str = strchr(message, '\r')) != NULL)
17133       *end_str = NULLCHAR;
17134     if ((end_str = strchr(message, '\n')) != NULL)
17135       *end_str = NULLCHAR;
17136
17137     if (appData.debugMode) {
17138         TimeMark now; int print = 1;
17139         char *quote = ""; char c; int i;
17140
17141         if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
17142                 char start = message[0];
17143                 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
17144                 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
17145                    sscanf(message, "move %c", &c)!=1  && sscanf(message, "offer%c", &c)!=1 &&
17146                    sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
17147                    sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
17148                    sscanf(message, "tell%c", &c)!=1   && sscanf(message, "0-1 %c", &c)!=1 &&
17149                    sscanf(message, "1-0 %c", &c)!=1   && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
17150                    sscanf(message, "setboard %c", &c)!=1   && sscanf(message, "setup %c", &c)!=1 &&
17151                    sscanf(message, "hint: %c", &c)!=1 &&
17152                    sscanf(message, "pong %c", &c)!=1   && start != '#') {
17153                     quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
17154                     print = (appData.engineComments >= 2);
17155                 }
17156                 message[0] = start; // restore original message
17157         }
17158         if(print) {
17159                 GetTimeMark(&now);
17160                 fprintf(debugFP, "%ld <%-6s: %s%s\n",
17161                         SubtractTimeMarks(&now, &programStartTime), cps->which,
17162                         quote,
17163                         message);
17164                 if(serverFP)
17165                     fprintf(serverFP, "%ld <%-6s: %s%s\n",
17166                         SubtractTimeMarks(&now, &programStartTime), cps->which,
17167                         quote,
17168                         message), fflush(serverFP);
17169         }
17170     }
17171
17172     /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
17173     if (appData.icsEngineAnalyze) {
17174         if (strstr(message, "whisper") != NULL ||
17175              strstr(message, "kibitz") != NULL ||
17176             strstr(message, "tellics") != NULL) return;
17177     }
17178
17179     HandleMachineMove(message, cps);
17180 }
17181
17182
17183 void
17184 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
17185 {
17186     char buf[MSG_SIZ];
17187     int seconds;
17188
17189     if( timeControl_2 > 0 ) {
17190         if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
17191             tc = timeControl_2;
17192         }
17193     }
17194     tc  /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
17195     inc /= cps->timeOdds;
17196     st  /= cps->timeOdds;
17197
17198     seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
17199
17200     if (st > 0) {
17201       /* Set exact time per move, normally using st command */
17202       if (cps->stKludge) {
17203         /* GNU Chess 4 has no st command; uses level in a nonstandard way */
17204         seconds = st % 60;
17205         if (seconds == 0) {
17206           snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
17207         } else {
17208           snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
17209         }
17210       } else {
17211         snprintf(buf, MSG_SIZ, "st %d\n", st);
17212       }
17213     } else {
17214       /* Set conventional or incremental time control, using level command */
17215       if (seconds == 0) {
17216         /* Note old gnuchess bug -- minutes:seconds used to not work.
17217            Fixed in later versions, but still avoid :seconds
17218            when seconds is 0. */
17219         snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
17220       } else {
17221         snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
17222                  seconds, inc/1000.);
17223       }
17224     }
17225     SendToProgram(buf, cps);
17226
17227     /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
17228     /* Orthogonally, limit search to given depth */
17229     if (sd > 0) {
17230       if (cps->sdKludge) {
17231         snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
17232       } else {
17233         snprintf(buf, MSG_SIZ, "sd %d\n", sd);
17234       }
17235       SendToProgram(buf, cps);
17236     }
17237
17238     if(cps->nps >= 0) { /* [HGM] nps */
17239         if(cps->supportsNPS == FALSE)
17240           cps->nps = -1; // don't use if engine explicitly says not supported!
17241         else {
17242           snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
17243           SendToProgram(buf, cps);
17244         }
17245     }
17246 }
17247
17248 ChessProgramState *
17249 WhitePlayer ()
17250 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
17251 {
17252     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
17253        gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
17254         return &second;
17255     return &first;
17256 }
17257
17258 void
17259 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
17260 {
17261     char message[MSG_SIZ];
17262     long time, otime;
17263
17264     /* Note: this routine must be called when the clocks are stopped
17265        or when they have *just* been set or switched; otherwise
17266        it will be off by the time since the current tick started.
17267     */
17268     if (machineWhite) {
17269         time = whiteTimeRemaining / 10;
17270         otime = blackTimeRemaining / 10;
17271     } else {
17272         time = blackTimeRemaining / 10;
17273         otime = whiteTimeRemaining / 10;
17274     }
17275     /* [HGM] translate opponent's time by time-odds factor */
17276     otime = (otime * cps->other->timeOdds) / cps->timeOdds;
17277
17278     if (time <= 0) time = 1;
17279     if (otime <= 0) otime = 1;
17280
17281     snprintf(message, MSG_SIZ, "time %ld\n", time);
17282     SendToProgram(message, cps);
17283
17284     snprintf(message, MSG_SIZ, "otim %ld\n", otime);
17285     SendToProgram(message, cps);
17286 }
17287
17288 char *
17289 EngineDefinedVariant (ChessProgramState *cps, int n)
17290 {   // return name of n-th unknown variant that engine supports
17291     static char buf[MSG_SIZ];
17292     char *p, *s = cps->variants;
17293     if(!s) return NULL;
17294     do { // parse string from variants feature
17295       VariantClass v;
17296         p = strchr(s, ',');
17297         if(p) *p = NULLCHAR;
17298       v = StringToVariant(s);
17299       if(v == VariantNormal && strcmp(s, "normal") && !strstr(s, "_normal")) v = VariantUnknown; // garbage is recognized as normal
17300         if(v == VariantUnknown) { // non-standard variant in list of engine-supported variants
17301             if(!strcmp(s, "tenjiku") || !strcmp(s, "dai") || !strcmp(s, "dada") || // ignore Alien-Edition variants
17302                !strcmp(s, "maka") || !strcmp(s, "tai") || !strcmp(s, "kyoku") ||
17303                !strcmp(s, "checkers") || !strcmp(s, "go") || !strcmp(s, "reversi") ||
17304                !strcmp(s, "dark") || !strcmp(s, "alien") || !strcmp(s, "multi") || !strcmp(s, "amazons") ) n++;
17305             if(--n < 0) safeStrCpy(buf, s, MSG_SIZ);
17306         }
17307         if(p) *p++ = ',';
17308         if(n < 0) return buf;
17309     } while(s = p);
17310     return NULL;
17311 }
17312
17313 int
17314 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
17315 {
17316   char buf[MSG_SIZ];
17317   int len = strlen(name);
17318   int val;
17319
17320   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
17321     (*p) += len + 1;
17322     sscanf(*p, "%d", &val);
17323     *loc = (val != 0);
17324     while (**p && **p != ' ')
17325       (*p)++;
17326     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17327     SendToProgram(buf, cps);
17328     return TRUE;
17329   }
17330   return FALSE;
17331 }
17332
17333 int
17334 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
17335 {
17336   char buf[MSG_SIZ];
17337   int len = strlen(name);
17338   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
17339     (*p) += len + 1;
17340     sscanf(*p, "%d", loc);
17341     while (**p && **p != ' ') (*p)++;
17342     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17343     SendToProgram(buf, cps);
17344     return TRUE;
17345   }
17346   return FALSE;
17347 }
17348
17349 int
17350 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
17351 {
17352   char buf[MSG_SIZ];
17353   int len = strlen(name);
17354   if (strncmp((*p), name, len) == 0
17355       && (*p)[len] == '=' && (*p)[len+1] == '\"') {
17356     (*p) += len + 2;
17357     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
17358     FREE(*loc); *loc = malloc(len);
17359     strncpy(*loc, *p, len);
17360     sscanf(*p, "%[^\"]", *loc); // should always fit, because we allocated at least strlen(*p)
17361     while (**p && **p != '\"') (*p)++;
17362     if (**p == '\"') (*p)++;
17363     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17364     SendToProgram(buf, cps);
17365     return TRUE;
17366   }
17367   return FALSE;
17368 }
17369
17370 int
17371 ParseOption (Option *opt, ChessProgramState *cps)
17372 // [HGM] options: process the string that defines an engine option, and determine
17373 // name, type, default value, and allowed value range
17374 {
17375         char *p, *q, buf[MSG_SIZ];
17376         int n, min = (-1)<<31, max = 1<<31, def;
17377
17378         opt->target = &opt->value;   // OK for spin/slider and checkbox
17379         if(p = strstr(opt->name, " -spin ")) {
17380             if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
17381             if(max < min) max = min; // enforce consistency
17382             if(def < min) def = min;
17383             if(def > max) def = max;
17384             opt->value = def;
17385             opt->min = min;
17386             opt->max = max;
17387             opt->type = Spin;
17388         } else if((p = strstr(opt->name, " -slider "))) {
17389             // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
17390             if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
17391             if(max < min) max = min; // enforce consistency
17392             if(def < min) def = min;
17393             if(def > max) def = max;
17394             opt->value = def;
17395             opt->min = min;
17396             opt->max = max;
17397             opt->type = Spin; // Slider;
17398         } else if((p = strstr(opt->name, " -string "))) {
17399             opt->textValue = p+9;
17400             opt->type = TextBox;
17401             opt->target = &opt->textValue;
17402         } else if((p = strstr(opt->name, " -file "))) {
17403             // for now -file is a synonym for -string, to already provide compatibility with future polyglots
17404             opt->target = opt->textValue = p+7;
17405             opt->type = FileName; // FileName;
17406             opt->target = &opt->textValue;
17407         } else if((p = strstr(opt->name, " -path "))) {
17408             // for now -file is a synonym for -string, to already provide compatibility with future polyglots
17409             opt->target = opt->textValue = p+7;
17410             opt->type = PathName; // PathName;
17411             opt->target = &opt->textValue;
17412         } else if(p = strstr(opt->name, " -check ")) {
17413             if(sscanf(p, " -check %d", &def) < 1) return FALSE;
17414             opt->value = (def != 0);
17415             opt->type = CheckBox;
17416         } else if(p = strstr(opt->name, " -combo ")) {
17417             opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
17418             cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
17419             if(*q == '*') cps->comboList[cps->comboCnt-1]++;
17420             opt->value = n = 0;
17421             while(q = StrStr(q, " /// ")) {
17422                 n++; *q = 0;    // count choices, and null-terminate each of them
17423                 q += 5;
17424                 if(*q == '*') { // remember default, which is marked with * prefix
17425                     q++;
17426                     opt->value = n;
17427                 }
17428                 cps->comboList[cps->comboCnt++] = q;
17429             }
17430             cps->comboList[cps->comboCnt++] = NULL;
17431             opt->max = n + 1;
17432             opt->type = ComboBox;
17433         } else if(p = strstr(opt->name, " -button")) {
17434             opt->type = Button;
17435         } else if(p = strstr(opt->name, " -save")) {
17436             opt->type = SaveButton;
17437         } else return FALSE;
17438         *p = 0; // terminate option name
17439         *(int*) (opt->name + MSG_SIZ - 104) = opt->value; // hide default values somewhere
17440         if(opt->target == &opt->textValue) strncpy(opt->name + MSG_SIZ - 100, opt->textValue, 99);
17441         // now look if the command-line options define a setting for this engine option.
17442         if(cps->optionSettings && cps->optionSettings[0])
17443             p = strstr(cps->optionSettings, opt->name); else p = NULL;
17444         if(p && (p == cps->optionSettings || p[-1] == ',')) {
17445           snprintf(buf, MSG_SIZ, "option %s", p);
17446                 if(p = strstr(buf, ",")) *p = 0;
17447                 if(q = strchr(buf, '=')) switch(opt->type) {
17448                     case ComboBox:
17449                         for(n=0; n<opt->max; n++)
17450                             if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
17451                         break;
17452                     case TextBox:
17453                     case FileName:
17454                     case PathName:
17455                         safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
17456                         break;
17457                     case Spin:
17458                     case CheckBox:
17459                         opt->value = atoi(q+1);
17460                     default:
17461                         break;
17462                 }
17463                 strcat(buf, "\n");
17464                 SendToProgram(buf, cps);
17465         }
17466         return TRUE;
17467 }
17468
17469 void
17470 FeatureDone (ChessProgramState *cps, int val)
17471 {
17472   DelayedEventCallback cb = GetDelayedEvent();
17473   if ((cb == InitBackEnd3 && cps == &first) ||
17474       (cb == SettingsMenuIfReady && cps == &second) ||
17475       (cb == LoadEngine) || (cb == StartSecond) ||
17476       (cb == TwoMachinesEventIfReady)) {
17477     CancelDelayedEvent();
17478     ScheduleDelayedEvent(cb, val ? 1 : 3600000);
17479   } else if(!val && !cps->reload) ClearOptions(cps); // let 'spurious' done=0 clear engine's option list
17480   cps->initDone = val;
17481   if(val) cps->reload = FALSE,  RefreshSettingsDialog(cps, val);
17482 }
17483
17484 /* Parse feature command from engine */
17485 void
17486 ParseFeatures (char *args, ChessProgramState *cps)
17487 {
17488   char *p = args;
17489   char *q = NULL;
17490   int val;
17491   char buf[MSG_SIZ];
17492
17493   for (;;) {
17494     while (*p == ' ') p++;
17495     if (*p == NULLCHAR) return;
17496
17497     if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
17498     if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
17499     if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
17500     if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
17501     if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
17502     if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
17503     if (BoolFeature(&p, "reuse", &val, cps)) {
17504       /* Engine can disable reuse, but can't enable it if user said no */
17505       if (!val) cps->reuse = FALSE;
17506       continue;
17507     }
17508     if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
17509     if (StringFeature(&p, "myname", &cps->tidy, cps)) {
17510       if (gameMode == TwoMachinesPlay) {
17511         DisplayTwoMachinesTitle();
17512       } else {
17513         DisplayTitle("");
17514       }
17515       continue;
17516     }
17517     if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
17518     if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
17519     if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
17520     if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
17521     if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
17522     if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
17523     if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
17524     if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
17525     if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
17526     if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
17527     if (IntFeature(&p, "done", &val, cps)) {
17528       FeatureDone(cps, val);
17529       continue;
17530     }
17531     /* Added by Tord: */
17532     if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
17533     if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
17534     /* End of additions by Tord */
17535
17536     /* [HGM] added features: */
17537     if (BoolFeature(&p, "highlight", &cps->highlight, cps)) continue;
17538     if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
17539     if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
17540     if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
17541     if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
17542     if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
17543     if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
17544     if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
17545         if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
17546         if(cps->nrOptions == 0) { ASSIGN(cps->option[0].name, _("Make Persistent -save")); ParseOption(&(cps->option[cps->nrOptions++]), cps); }
17547         FREE(cps->option[cps->nrOptions].name);
17548         cps->option[cps->nrOptions].name = q; q = NULL;
17549         if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
17550           snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
17551             SendToProgram(buf, cps);
17552             continue;
17553         }
17554         if(cps->nrOptions >= MAX_OPTIONS) {
17555             cps->nrOptions--;
17556             snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
17557             DisplayError(buf, 0);
17558         }
17559         continue;
17560     }
17561     /* End of additions by HGM */
17562
17563     /* unknown feature: complain and skip */
17564     q = p;
17565     while (*q && *q != '=') q++;
17566     snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
17567     SendToProgram(buf, cps);
17568     p = q;
17569     if (*p == '=') {
17570       p++;
17571       if (*p == '\"') {
17572         p++;
17573         while (*p && *p != '\"') p++;
17574         if (*p == '\"') p++;
17575       } else {
17576         while (*p && *p != ' ') p++;
17577       }
17578     }
17579   }
17580
17581 }
17582
17583 void
17584 PeriodicUpdatesEvent (int newState)
17585 {
17586     if (newState == appData.periodicUpdates)
17587       return;
17588
17589     appData.periodicUpdates=newState;
17590
17591     /* Display type changes, so update it now */
17592 //    DisplayAnalysis();
17593
17594     /* Get the ball rolling again... */
17595     if (newState) {
17596         AnalysisPeriodicEvent(1);
17597         StartAnalysisClock();
17598     }
17599 }
17600
17601 void
17602 PonderNextMoveEvent (int newState)
17603 {
17604     if (newState == appData.ponderNextMove) return;
17605     if (gameMode == EditPosition) EditPositionDone(TRUE);
17606     if (newState) {
17607         SendToProgram("hard\n", &first);
17608         if (gameMode == TwoMachinesPlay) {
17609             SendToProgram("hard\n", &second);
17610         }
17611     } else {
17612         SendToProgram("easy\n", &first);
17613         thinkOutput[0] = NULLCHAR;
17614         if (gameMode == TwoMachinesPlay) {
17615             SendToProgram("easy\n", &second);
17616         }
17617     }
17618     appData.ponderNextMove = newState;
17619 }
17620
17621 void
17622 NewSettingEvent (int option, int *feature, char *command, int value)
17623 {
17624     char buf[MSG_SIZ];
17625
17626     if (gameMode == EditPosition) EditPositionDone(TRUE);
17627     snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
17628     if(feature == NULL || *feature) SendToProgram(buf, &first);
17629     if (gameMode == TwoMachinesPlay) {
17630         if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
17631     }
17632 }
17633
17634 void
17635 ShowThinkingEvent ()
17636 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
17637 {
17638     static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
17639     int newState = appData.showThinking
17640         // [HGM] thinking: other features now need thinking output as well
17641         || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
17642
17643     if (oldState == newState) return;
17644     oldState = newState;
17645     if (gameMode == EditPosition) EditPositionDone(TRUE);
17646     if (oldState) {
17647         SendToProgram("post\n", &first);
17648         if (gameMode == TwoMachinesPlay) {
17649             SendToProgram("post\n", &second);
17650         }
17651     } else {
17652         SendToProgram("nopost\n", &first);
17653         thinkOutput[0] = NULLCHAR;
17654         if (gameMode == TwoMachinesPlay) {
17655             SendToProgram("nopost\n", &second);
17656         }
17657     }
17658 //    appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
17659 }
17660
17661 void
17662 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
17663 {
17664   ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
17665   if (pr == NoProc) return;
17666   AskQuestion(title, question, replyPrefix, pr);
17667 }
17668
17669 void
17670 TypeInEvent (char firstChar)
17671 {
17672     if ((gameMode == BeginningOfGame && !appData.icsActive) ||
17673         gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
17674         gameMode == AnalyzeMode || gameMode == EditGame ||
17675         gameMode == EditPosition || gameMode == IcsExamining ||
17676         gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
17677         isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
17678                 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
17679                   gameMode == IcsObserving || gameMode == TwoMachinesPlay    ) ||
17680         gameMode == Training) PopUpMoveDialog(firstChar);
17681 }
17682
17683 void
17684 TypeInDoneEvent (char *move)
17685 {
17686         Board board;
17687         int n, fromX, fromY, toX, toY;
17688         char promoChar;
17689         ChessMove moveType;
17690
17691         // [HGM] FENedit
17692         if(gameMode == EditPosition && ParseFEN(board, &n, move, TRUE) ) {
17693                 EditPositionPasteFEN(move);
17694                 return;
17695         }
17696         // [HGM] movenum: allow move number to be typed in any mode
17697         if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
17698           ToNrEvent(2*n-1);
17699           return;
17700         }
17701         // undocumented kludge: allow command-line option to be typed in!
17702         // (potentially fatal, and does not implement the effect of the option.)
17703         // should only be used for options that are values on which future decisions will be made,
17704         // and definitely not on options that would be used during initialization.
17705         if(strstr(move, "!!! -") == move) {
17706             ParseArgsFromString(move+4);
17707             return;
17708         }
17709
17710       if (gameMode != EditGame && currentMove != forwardMostMove &&
17711         gameMode != Training) {
17712         DisplayMoveError(_("Displayed move is not current"));
17713       } else {
17714         int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17715           &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
17716         if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
17717         if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17718           &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
17719           UserMoveEvent(fromX, fromY, toX, toY, promoChar);
17720         } else {
17721           DisplayMoveError(_("Could not parse move"));
17722         }
17723       }
17724 }
17725
17726 void
17727 DisplayMove (int moveNumber)
17728 {
17729     char message[MSG_SIZ];
17730     char res[MSG_SIZ];
17731     char cpThinkOutput[MSG_SIZ];
17732
17733     if(appData.noGUI) return; // [HGM] fast: suppress display of moves
17734
17735     if (moveNumber == forwardMostMove - 1 ||
17736         gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
17737
17738         safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
17739
17740         if (strchr(cpThinkOutput, '\n')) {
17741             *strchr(cpThinkOutput, '\n') = NULLCHAR;
17742         }
17743     } else {
17744         *cpThinkOutput = NULLCHAR;
17745     }
17746
17747     /* [AS] Hide thinking from human user */
17748     if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
17749         *cpThinkOutput = NULLCHAR;
17750         if( thinkOutput[0] != NULLCHAR ) {
17751             int i;
17752
17753             for( i=0; i<=hiddenThinkOutputState; i++ ) {
17754                 cpThinkOutput[i] = '.';
17755             }
17756             cpThinkOutput[i] = NULLCHAR;
17757             hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
17758         }
17759     }
17760
17761     if (moveNumber == forwardMostMove - 1 &&
17762         gameInfo.resultDetails != NULL) {
17763         if (gameInfo.resultDetails[0] == NULLCHAR) {
17764           snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
17765         } else {
17766           snprintf(res, MSG_SIZ, " {%s} %s",
17767                     T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
17768         }
17769     } else {
17770         res[0] = NULLCHAR;
17771     }
17772
17773     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17774         DisplayMessage(res, cpThinkOutput);
17775     } else {
17776       snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
17777                 WhiteOnMove(moveNumber) ? " " : ".. ",
17778                 parseList[moveNumber], res);
17779         DisplayMessage(message, cpThinkOutput);
17780     }
17781 }
17782
17783 void
17784 DisplayComment (int moveNumber, char *text)
17785 {
17786     char title[MSG_SIZ];
17787
17788     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17789       safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
17790     } else {
17791       snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
17792               WhiteOnMove(moveNumber) ? " " : ".. ",
17793               parseList[moveNumber]);
17794     }
17795     if (text != NULL && (appData.autoDisplayComment || commentUp))
17796         CommentPopUp(title, text);
17797 }
17798
17799 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
17800  * might be busy thinking or pondering.  It can be omitted if your
17801  * gnuchess is configured to stop thinking immediately on any user
17802  * input.  However, that gnuchess feature depends on the FIONREAD
17803  * ioctl, which does not work properly on some flavors of Unix.
17804  */
17805 void
17806 Attention (ChessProgramState *cps)
17807 {
17808 #if ATTENTION
17809     if (!cps->useSigint) return;
17810     if (appData.noChessProgram || (cps->pr == NoProc)) return;
17811     switch (gameMode) {
17812       case MachinePlaysWhite:
17813       case MachinePlaysBlack:
17814       case TwoMachinesPlay:
17815       case IcsPlayingWhite:
17816       case IcsPlayingBlack:
17817       case AnalyzeMode:
17818       case AnalyzeFile:
17819         /* Skip if we know it isn't thinking */
17820         if (!cps->maybeThinking) return;
17821         if (appData.debugMode)
17822           fprintf(debugFP, "Interrupting %s\n", cps->which);
17823         InterruptChildProcess(cps->pr);
17824         cps->maybeThinking = FALSE;
17825         break;
17826       default:
17827         break;
17828     }
17829 #endif /*ATTENTION*/
17830 }
17831
17832 int
17833 CheckFlags ()
17834 {
17835     if (whiteTimeRemaining <= 0) {
17836         if (!whiteFlag) {
17837             whiteFlag = TRUE;
17838             if (appData.icsActive) {
17839                 if (appData.autoCallFlag &&
17840                     gameMode == IcsPlayingBlack && !blackFlag) {
17841                   SendToICS(ics_prefix);
17842                   SendToICS("flag\n");
17843                 }
17844             } else {
17845                 if (blackFlag) {
17846                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17847                 } else {
17848                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
17849                     if (appData.autoCallFlag) {
17850                         GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
17851                         return TRUE;
17852                     }
17853                 }
17854             }
17855         }
17856     }
17857     if (blackTimeRemaining <= 0) {
17858         if (!blackFlag) {
17859             blackFlag = TRUE;
17860             if (appData.icsActive) {
17861                 if (appData.autoCallFlag &&
17862                     gameMode == IcsPlayingWhite && !whiteFlag) {
17863                   SendToICS(ics_prefix);
17864                   SendToICS("flag\n");
17865                 }
17866             } else {
17867                 if (whiteFlag) {
17868                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17869                 } else {
17870                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
17871                     if (appData.autoCallFlag) {
17872                         GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
17873                         return TRUE;
17874                     }
17875                 }
17876             }
17877         }
17878     }
17879     return FALSE;
17880 }
17881
17882 void
17883 CheckTimeControl ()
17884 {
17885     if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
17886         gameMode == PlayFromGameFile || forwardMostMove == 0) return;
17887
17888     /*
17889      * add time to clocks when time control is achieved ([HGM] now also used for increment)
17890      */
17891     if ( !WhiteOnMove(forwardMostMove) ) {
17892         /* White made time control */
17893         lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
17894         whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
17895         /* [HGM] time odds: correct new time quota for time odds! */
17896                                             / WhitePlayer()->timeOdds;
17897         lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
17898     } else {
17899         lastBlack -= blackTimeRemaining;
17900         /* Black made time control */
17901         blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
17902                                             / WhitePlayer()->other->timeOdds;
17903         lastWhite = whiteTimeRemaining;
17904     }
17905 }
17906
17907 void
17908 DisplayBothClocks ()
17909 {
17910     int wom = gameMode == EditPosition ?
17911       !blackPlaysFirst : WhiteOnMove(currentMove);
17912     DisplayWhiteClock(whiteTimeRemaining, wom);
17913     DisplayBlackClock(blackTimeRemaining, !wom);
17914 }
17915
17916
17917 /* Timekeeping seems to be a portability nightmare.  I think everyone
17918    has ftime(), but I'm really not sure, so I'm including some ifdefs
17919    to use other calls if you don't.  Clocks will be less accurate if
17920    you have neither ftime nor gettimeofday.
17921 */
17922
17923 /* VS 2008 requires the #include outside of the function */
17924 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
17925 #include <sys/timeb.h>
17926 #endif
17927
17928 /* Get the current time as a TimeMark */
17929 void
17930 GetTimeMark (TimeMark *tm)
17931 {
17932 #if HAVE_GETTIMEOFDAY
17933
17934     struct timeval timeVal;
17935     struct timezone timeZone;
17936
17937     gettimeofday(&timeVal, &timeZone);
17938     tm->sec = (long) timeVal.tv_sec;
17939     tm->ms = (int) (timeVal.tv_usec / 1000L);
17940
17941 #else /*!HAVE_GETTIMEOFDAY*/
17942 #if HAVE_FTIME
17943
17944 // include <sys/timeb.h> / moved to just above start of function
17945     struct timeb timeB;
17946
17947     ftime(&timeB);
17948     tm->sec = (long) timeB.time;
17949     tm->ms = (int) timeB.millitm;
17950
17951 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
17952     tm->sec = (long) time(NULL);
17953     tm->ms = 0;
17954 #endif
17955 #endif
17956 }
17957
17958 /* Return the difference in milliseconds between two
17959    time marks.  We assume the difference will fit in a long!
17960 */
17961 long
17962 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
17963 {
17964     return 1000L*(tm2->sec - tm1->sec) +
17965            (long) (tm2->ms - tm1->ms);
17966 }
17967
17968
17969 /*
17970  * Code to manage the game clocks.
17971  *
17972  * In tournament play, black starts the clock and then white makes a move.
17973  * We give the human user a slight advantage if he is playing white---the
17974  * clocks don't run until he makes his first move, so it takes zero time.
17975  * Also, we don't account for network lag, so we could get out of sync
17976  * with GNU Chess's clock -- but then, referees are always right.
17977  */
17978
17979 static TimeMark tickStartTM;
17980 static long intendedTickLength;
17981
17982 long
17983 NextTickLength (long timeRemaining)
17984 {
17985     long nominalTickLength, nextTickLength;
17986
17987     if (timeRemaining > 0L && timeRemaining <= 10000L)
17988       nominalTickLength = 100L;
17989     else
17990       nominalTickLength = 1000L;
17991     nextTickLength = timeRemaining % nominalTickLength;
17992     if (nextTickLength <= 0) nextTickLength += nominalTickLength;
17993
17994     return nextTickLength;
17995 }
17996
17997 /* Adjust clock one minute up or down */
17998 void
17999 AdjustClock (Boolean which, int dir)
18000 {
18001     if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
18002     if(which) blackTimeRemaining += 60000*dir;
18003     else      whiteTimeRemaining += 60000*dir;
18004     DisplayBothClocks();
18005     adjustedClock = TRUE;
18006 }
18007
18008 /* Stop clocks and reset to a fresh time control */
18009 void
18010 ResetClocks ()
18011 {
18012     (void) StopClockTimer();
18013     if (appData.icsActive) {
18014         whiteTimeRemaining = blackTimeRemaining = 0;
18015     } else if (searchTime) {
18016         whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
18017         blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
18018     } else { /* [HGM] correct new time quote for time odds */
18019         whiteTC = blackTC = fullTimeControlString;
18020         whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
18021         blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
18022     }
18023     if (whiteFlag || blackFlag) {
18024         DisplayTitle("");
18025         whiteFlag = blackFlag = FALSE;
18026     }
18027     lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
18028     DisplayBothClocks();
18029     adjustedClock = FALSE;
18030 }
18031
18032 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
18033
18034 static int timeSuffix; // [HGM] This should realy be a passed parameter, but it has to pass through too many levels for my laziness...
18035
18036 /* Decrement running clock by amount of time that has passed */
18037 void
18038 DecrementClocks ()
18039 {
18040     long tRemaining;
18041     long lastTickLength, fudge;
18042     TimeMark now;
18043
18044     if (!appData.clockMode) return;
18045     if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
18046
18047     GetTimeMark(&now);
18048
18049     lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18050
18051     /* Fudge if we woke up a little too soon */
18052     fudge = intendedTickLength - lastTickLength;
18053     if (fudge < 0 || fudge > FUDGE) fudge = 0;
18054
18055     if (WhiteOnMove(forwardMostMove)) {
18056         if(whiteNPS >= 0) lastTickLength = 0;
18057          tRemaining = whiteTimeRemaining -= lastTickLength;
18058         if( tRemaining < 0 && !appData.icsActive) {
18059             GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
18060             if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
18061                 whiteStartMove = forwardMostMove; whiteTC = nextSession;
18062                 lastWhite=  tRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
18063             }
18064         }
18065         if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[0][forwardMostMove-1] - tRemaining;
18066         DisplayWhiteClock(whiteTimeRemaining - fudge,
18067                           WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
18068         timeSuffix = 0;
18069     } else {
18070         if(blackNPS >= 0) lastTickLength = 0;
18071          tRemaining = blackTimeRemaining -= lastTickLength;
18072         if( tRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
18073             GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
18074             if(suddenDeath) {
18075                 blackStartMove = forwardMostMove;
18076                 lastBlack =  tRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
18077             }
18078         }
18079         if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[1][forwardMostMove-1] - tRemaining;
18080         DisplayBlackClock(blackTimeRemaining - fudge,
18081                           !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
18082         timeSuffix = 0;
18083     }
18084     if (CheckFlags()) return;
18085
18086     if(twoBoards) { // count down secondary board's clocks as well
18087         activePartnerTime -= lastTickLength;
18088         partnerUp = 1;
18089         if(activePartner == 'W')
18090             DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
18091         else
18092             DisplayBlackClock(activePartnerTime, TRUE);
18093         partnerUp = 0;
18094     }
18095
18096     tickStartTM = now;
18097     intendedTickLength = NextTickLength( tRemaining - fudge) + fudge;
18098     StartClockTimer(intendedTickLength);
18099
18100     /* if the time remaining has fallen below the alarm threshold, sound the
18101      * alarm. if the alarm has sounded and (due to a takeback or time control
18102      * with increment) the time remaining has increased to a level above the
18103      * threshold, reset the alarm so it can sound again.
18104      */
18105
18106     if (appData.icsActive && appData.icsAlarm) {
18107
18108         /* make sure we are dealing with the user's clock */
18109         if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
18110                ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
18111            )) return;
18112
18113         if (alarmSounded && ( tRemaining > appData.icsAlarmTime)) {
18114             alarmSounded = FALSE;
18115         } else if (!alarmSounded && ( tRemaining <= appData.icsAlarmTime)) {
18116             PlayAlarmSound();
18117             alarmSounded = TRUE;
18118         }
18119     }
18120 }
18121
18122
18123 /* A player has just moved, so stop the previously running
18124    clock and (if in clock mode) start the other one.
18125    We redisplay both clocks in case we're in ICS mode, because
18126    ICS gives us an update to both clocks after every move.
18127    Note that this routine is called *after* forwardMostMove
18128    is updated, so the last fractional tick must be subtracted
18129    from the color that is *not* on move now.
18130 */
18131 void
18132 SwitchClocks (int newMoveNr)
18133 {
18134     long lastTickLength;
18135     TimeMark now;
18136     int flagged = FALSE;
18137
18138     GetTimeMark(&now);
18139
18140     if (StopClockTimer() && appData.clockMode) {
18141         lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18142         if (!WhiteOnMove(forwardMostMove)) {
18143             if(blackNPS >= 0) lastTickLength = 0;
18144             blackTimeRemaining -= lastTickLength;
18145            /* [HGM] PGNtime: save time for PGN file if engine did not give it */
18146 //         if(pvInfoList[forwardMostMove].time == -1)
18147                  pvInfoList[forwardMostMove].time =               // use GUI time
18148                       (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
18149         } else {
18150            if(whiteNPS >= 0) lastTickLength = 0;
18151            whiteTimeRemaining -= lastTickLength;
18152            /* [HGM] PGNtime: save time for PGN file if engine did not give it */
18153 //         if(pvInfoList[forwardMostMove].time == -1)
18154                  pvInfoList[forwardMostMove].time =
18155                       (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
18156         }
18157         flagged = CheckFlags();
18158     }
18159     forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
18160     CheckTimeControl();
18161
18162     if (flagged || !appData.clockMode) return;
18163
18164     switch (gameMode) {
18165       case MachinePlaysBlack:
18166       case MachinePlaysWhite:
18167       case BeginningOfGame:
18168         if (pausing) return;
18169         break;
18170
18171       case EditGame:
18172       case PlayFromGameFile:
18173       case IcsExamining:
18174         return;
18175
18176       default:
18177         break;
18178     }
18179
18180     if (searchTime) { // [HGM] st: set clock of player that has to move to max time
18181         if(WhiteOnMove(forwardMostMove))
18182              whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
18183         else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
18184     }
18185
18186     tickStartTM = now;
18187     intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
18188       whiteTimeRemaining : blackTimeRemaining);
18189     StartClockTimer(intendedTickLength);
18190 }
18191
18192
18193 /* Stop both clocks */
18194 void
18195 StopClocks ()
18196 {
18197     long lastTickLength;
18198     TimeMark now;
18199
18200     if (!StopClockTimer()) return;
18201     if (!appData.clockMode) return;
18202
18203     GetTimeMark(&now);
18204
18205     lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18206     if (WhiteOnMove(forwardMostMove)) {
18207         if(whiteNPS >= 0) lastTickLength = 0;
18208         whiteTimeRemaining -= lastTickLength;
18209         DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
18210     } else {
18211         if(blackNPS >= 0) lastTickLength = 0;
18212         blackTimeRemaining -= lastTickLength;
18213         DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
18214     }
18215     CheckFlags();
18216 }
18217
18218 /* Start clock of player on move.  Time may have been reset, so
18219    if clock is already running, stop and restart it. */
18220 void
18221 StartClocks ()
18222 {
18223     (void) StopClockTimer(); /* in case it was running already */
18224     DisplayBothClocks();
18225     if (CheckFlags()) return;
18226
18227     if (!appData.clockMode) return;
18228     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
18229
18230     GetTimeMark(&tickStartTM);
18231     intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
18232       whiteTimeRemaining : blackTimeRemaining);
18233
18234    /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
18235     whiteNPS = blackNPS = -1;
18236     if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
18237        || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
18238         whiteNPS = first.nps;
18239     if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
18240        || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
18241         blackNPS = first.nps;
18242     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
18243         whiteNPS = second.nps;
18244     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
18245         blackNPS = second.nps;
18246     if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
18247
18248     StartClockTimer(intendedTickLength);
18249 }
18250
18251 char *
18252 TimeString (long ms)
18253 {
18254     long second, minute, hour, day;
18255     char *sign = "";
18256     static char buf[40], moveTime[8];
18257
18258     if (ms > 0 && ms <= 9900) {
18259       /* convert milliseconds to tenths, rounding up */
18260       double tenths = floor( ((double)(ms + 99L)) / 100.00 );
18261
18262       snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
18263       return buf;
18264     }
18265
18266     /* convert milliseconds to seconds, rounding up */
18267     /* use floating point to avoid strangeness of integer division
18268        with negative dividends on many machines */
18269     second = (long) floor(((double) (ms + 999L)) / 1000.0);
18270
18271     if (second < 0) {
18272         sign = "-";
18273         second = -second;
18274     }
18275
18276     day = second / (60 * 60 * 24);
18277     second = second % (60 * 60 * 24);
18278     hour = second / (60 * 60);
18279     second = second % (60 * 60);
18280     minute = second / 60;
18281     second = second % 60;
18282
18283     if(timeSuffix) snprintf(moveTime, 8, " (%d)", timeSuffix/1000); // [HGM] kludge alert; fraction contains move time
18284     else *moveTime = NULLCHAR;
18285
18286     if (day > 0)
18287       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld%s ",
18288               sign, day, hour, minute, second, moveTime);
18289     else if (hour > 0)
18290       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld%s ", sign, hour, minute, second, moveTime);
18291     else
18292       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld%s ", sign, minute, second, moveTime);
18293
18294     return buf;
18295 }
18296
18297
18298 /*
18299  * This is necessary because some C libraries aren't ANSI C compliant yet.
18300  */
18301 char *
18302 StrStr (char *string, char *match)
18303 {
18304     int i, length;
18305
18306     length = strlen(match);
18307
18308     for (i = strlen(string) - length; i >= 0; i--, string++)
18309       if (!strncmp(match, string, length))
18310         return string;
18311
18312     return NULL;
18313 }
18314
18315 char *
18316 StrCaseStr (char *string, char *match)
18317 {
18318     int i, j, length;
18319
18320     length = strlen(match);
18321
18322     for (i = strlen(string) - length; i >= 0; i--, string++) {
18323         for (j = 0; j < length; j++) {
18324             if (ToLower(match[j]) != ToLower(string[j]))
18325               break;
18326         }
18327         if (j == length) return string;
18328     }
18329
18330     return NULL;
18331 }
18332
18333 #ifndef _amigados
18334 int
18335 StrCaseCmp (char *s1, char *s2)
18336 {
18337     char c1, c2;
18338
18339     for (;;) {
18340         c1 = ToLower(*s1++);
18341         c2 = ToLower(*s2++);
18342         if (c1 > c2) return 1;
18343         if (c1 < c2) return -1;
18344         if (c1 == NULLCHAR) return 0;
18345     }
18346 }
18347
18348
18349 int
18350 ToLower (int c)
18351 {
18352     return isupper(c) ? tolower(c) : c;
18353 }
18354
18355
18356 int
18357 ToUpper (int c)
18358 {
18359     return islower(c) ? toupper(c) : c;
18360 }
18361 #endif /* !_amigados    */
18362
18363 char *
18364 StrSave (char *s)
18365 {
18366   char *ret;
18367
18368   if ((ret = (char *) malloc(strlen(s) + 1)))
18369     {
18370       safeStrCpy(ret, s, strlen(s)+1);
18371     }
18372   return ret;
18373 }
18374
18375 char *
18376 StrSavePtr (char *s, char **savePtr)
18377 {
18378     if (*savePtr) {
18379         free(*savePtr);
18380     }
18381     if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
18382       safeStrCpy(*savePtr, s, strlen(s)+1);
18383     }
18384     return(*savePtr);
18385 }
18386
18387 char *
18388 PGNDate ()
18389 {
18390     time_t clock;
18391     struct tm *tm;
18392     char buf[MSG_SIZ];
18393
18394     clock = time((time_t *)NULL);
18395     tm = localtime(&clock);
18396     snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
18397             tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
18398     return StrSave(buf);
18399 }
18400
18401
18402 char *
18403 PositionToFEN (int move, char *overrideCastling, int moveCounts)
18404 {
18405     int i, j, fromX, fromY, toX, toY;
18406     int whiteToPlay, haveRights = nrCastlingRights;
18407     char buf[MSG_SIZ];
18408     char *p, *q;
18409     int emptycount;
18410     ChessSquare piece;
18411
18412     whiteToPlay = (gameMode == EditPosition) ?
18413       !blackPlaysFirst : (move % 2 == 0);
18414     p = buf;
18415
18416     /* Piece placement data */
18417     for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
18418         if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
18419         emptycount = 0;
18420         for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
18421             if (boards[move][i][j] == EmptySquare) {
18422                 emptycount++;
18423             } else { ChessSquare piece = boards[move][i][j];
18424                 if (emptycount > 0) {
18425                     if(emptycount<10) /* [HGM] can be >= 10 */
18426                         *p++ = '0' + emptycount;
18427                     else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
18428                     emptycount = 0;
18429                 }
18430                 if(PieceToChar(piece) == '+') {
18431                     /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
18432                     *p++ = '+';
18433                     piece = (ChessSquare)(CHUDEMOTED(piece));
18434                 }
18435                 *p++ = (piece == DarkSquare ? '*' : PieceToChar(piece));
18436                 if(*p = PieceSuffix(piece)) p++;
18437                 if(p[-1] == '~') {
18438                     /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
18439                     p[-1] = PieceToChar((ChessSquare)(CHUDEMOTED(piece)));
18440                     *p++ = '~';
18441                 }
18442             }
18443         }
18444         if (emptycount > 0) {
18445             if(emptycount<10) /* [HGM] can be >= 10 */
18446                 *p++ = '0' + emptycount;
18447             else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
18448             emptycount = 0;
18449         }
18450         *p++ = '/';
18451     }
18452     *(p - 1) = ' ';
18453
18454     /* [HGM] print Crazyhouse or Shogi holdings */
18455     if( gameInfo.holdingsWidth ) {
18456         *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
18457         q = p;
18458         for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
18459             piece = boards[move][i][BOARD_WIDTH-1];
18460             if( piece != EmptySquare )
18461               for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
18462                   *p++ = PieceToChar(piece);
18463         }
18464         for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
18465             piece = boards[move][handSize-i-1][0];
18466             if( piece != EmptySquare )
18467               for(j=0; j<(int) boards[move][handSize-i-1][1]; j++)
18468                   *p++ = PieceToChar(piece);
18469         }
18470
18471         if( q == p ) *p++ = '-';
18472         *p++ = ']';
18473         *p++ = ' ';
18474     }
18475
18476     /* Active color */
18477     *p++ = whiteToPlay ? 'w' : 'b';
18478     *p++ = ' ';
18479
18480   if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
18481     haveRights = 0; q = p;
18482     for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
18483       piece = boards[move][0][i];
18484       if(piece >= WhitePawn && piece <= WhiteKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
18485         if(!(boards[move][TOUCHED_W] & 1<<i)) *p++ = 'A' + i; // print file ID if it has not moved
18486       }
18487     }
18488     for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
18489       piece = boards[move][BOARD_HEIGHT-1][i];
18490       if(piece >= BlackPawn && piece <= BlackKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
18491         if(!(boards[move][TOUCHED_B] & 1<<i)) *p++ = 'a' + i; // print file ID if it has not moved
18492       }
18493     }
18494     if(p == q) *p++ = '-';
18495     *p++ = ' ';
18496   }
18497
18498   if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
18499     while(*p++ = *q++)
18500                       ;
18501     if(q != overrideCastling+1) p[-1] = ' '; else --p;
18502   } else {
18503   if(haveRights) {
18504      int handW=0, handB=0;
18505      if(gameInfo.variant == VariantSChess) { // for S-Chess, all virgin backrank pieces must be listed
18506         for(i=0; i<BOARD_HEIGHT; i++) handW += boards[move][i][BOARD_RGHT]; // count white held pieces
18507         for(i=0; i<BOARD_HEIGHT; i++) handB += boards[move][i][BOARD_LEFT-1]; // count black held pieces
18508      }
18509      q = p;
18510      if(appData.fischerCastling) {
18511         if(handW) { // in shuffle S-Chess simply dump all virgin pieces
18512            for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
18513                if(boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
18514         } else {
18515        /* [HGM] write directly from rights */
18516            if(boards[move][CASTLING][2] != NoRights &&
18517               boards[move][CASTLING][0] != NoRights   )
18518                 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
18519            if(boards[move][CASTLING][2] != NoRights &&
18520               boards[move][CASTLING][1] != NoRights   )
18521                 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
18522         }
18523         if(handB) {
18524            for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
18525                if(boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
18526         } else {
18527            if(boards[move][CASTLING][5] != NoRights &&
18528               boards[move][CASTLING][3] != NoRights   )
18529                 *p++ = boards[move][CASTLING][3] + AAA;
18530            if(boards[move][CASTLING][5] != NoRights &&
18531               boards[move][CASTLING][4] != NoRights   )
18532                 *p++ = boards[move][CASTLING][4] + AAA;
18533         }
18534      } else {
18535
18536         /* [HGM] write true castling rights */
18537         if( nrCastlingRights == 6 ) {
18538             int q, k=0;
18539             if(boards[move][CASTLING][0] != NoRights &&
18540                boards[move][CASTLING][2] != NoRights  ) k = 1, *p++ = 'K';
18541             q = (boards[move][CASTLING][1] != NoRights &&
18542                  boards[move][CASTLING][2] != NoRights  );
18543             if(handW) { // for S-Chess with pieces in hand, list virgin pieces between K and Q
18544                 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
18545                     if((boards[move][0][i] != WhiteKing || k+q == 0) &&
18546                         boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
18547             }
18548             if(q) *p++ = 'Q';
18549             k = 0;
18550             if(boards[move][CASTLING][3] != NoRights &&
18551                boards[move][CASTLING][5] != NoRights  ) k = 1, *p++ = 'k';
18552             q = (boards[move][CASTLING][4] != NoRights &&
18553                  boards[move][CASTLING][5] != NoRights  );
18554             if(handB) {
18555                 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
18556                     if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
18557                         boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
18558             }
18559             if(q) *p++ = 'q';
18560         }
18561      }
18562      if (q == p) *p++ = '-'; /* No castling rights */
18563      *p++ = ' ';
18564   }
18565
18566   if(gameInfo.variant != VariantShogi    && gameInfo.variant != VariantXiangqi &&
18567      gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18568      gameInfo.variant != VariantMakruk   && gameInfo.variant != VariantASEAN ) {
18569     /* En passant target square */
18570     if (move > backwardMostMove) {
18571         fromX = moveList[move - 1][0] - AAA;
18572         fromY = moveList[move - 1][1] - ONE;
18573         toX = moveList[move - 1][2] - AAA;
18574         toY = moveList[move - 1][3] - ONE;
18575         if ((whiteToPlay ? toY < fromY - 1 : toY > fromY + 1) &&
18576             boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) ) {
18577             /* 2-square pawn move just happened */
18578             *p++ = (3*toX + 5*fromX + 4)/8 + AAA;
18579             *p++ = (3*toY + 5*fromY + 4)/8 + ONE;
18580             if(gameInfo.variant == VariantBerolina) {
18581                 *p++ = toX + AAA;
18582                 *p++ = toY + ONE;
18583             }
18584         } else {
18585             *p++ = '-';
18586         }
18587     } else if(move == backwardMostMove) {
18588         // [HGM] perhaps we should always do it like this, and forget the above?
18589         if((signed char)boards[move][EP_STATUS] >= 0) {
18590             *p++ = boards[move][EP_STATUS] + AAA;
18591             *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
18592         } else {
18593             *p++ = '-';
18594         }
18595     } else {
18596         *p++ = '-';
18597     }
18598     *p++ = ' ';
18599   }
18600   }
18601
18602     i = boards[move][CHECK_COUNT];
18603     if(i) {
18604         sprintf(p, "%d+%d ", i&255, i>>8);
18605         while(*p) p++;
18606     }
18607
18608     if(moveCounts)
18609     {   int i = 0, j=move;
18610
18611         /* [HGM] find reversible plies */
18612         if (appData.debugMode) { int k;
18613             fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
18614             for(k=backwardMostMove; k<=forwardMostMove; k++)
18615                 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
18616
18617         }
18618
18619         while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
18620         if( j == backwardMostMove ) i += initialRulePlies;
18621         sprintf(p, "%d ", i);
18622         p += i>=100 ? 4 : i >= 10 ? 3 : 2;
18623
18624         /* Fullmove number */
18625         sprintf(p, "%d", (move / 2) + 1);
18626     } else *--p = NULLCHAR;
18627
18628     return StrSave(buf);
18629 }
18630
18631 Boolean
18632 ParseFEN (Board board, int *blackPlaysFirst, char *fen, Boolean autoSize)
18633 {
18634     int i, j, k, w=0, subst=0, shuffle=0, wKingRank = -1, bKingRank = -1;
18635     char *p, c;
18636     int emptycount, virgin[BOARD_FILES];
18637     ChessSquare piece, king = (gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing);
18638
18639     p = fen;
18640
18641     for(i=1; i<=deadRanks; i++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) board[BOARD_HEIGHT-i][j] = DarkSquare;
18642
18643     /* Piece placement data */
18644     for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
18645         j = 0;
18646         for (;;) {
18647             if (*p == '/' || *p == ' ' || *p == '[' ) {
18648                 if(j > w) w = j;
18649                 emptycount = gameInfo.boardWidth - j;
18650                 while (emptycount--)
18651                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18652                 if (*p == '/') p++;
18653                 else if(autoSize && i != BOARD_HEIGHT-1) { // we stumbled unexpectedly into end of board
18654                     for(k=i; k<BOARD_HEIGHT; k++) { // too few ranks; shift towards bottom
18655                         for(j=0; j<BOARD_WIDTH; j++) board[k-i][j] = board[k][j];
18656                     }
18657                     appData.NrRanks = gameInfo.boardHeight - i; i=0;
18658                 }
18659                 break;
18660 #if(BOARD_FILES >= 10)*0
18661             } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
18662                 p++; emptycount=10;
18663                 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18664                 while (emptycount--)
18665                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18666 #endif
18667             } else if (*p == '*') {
18668                 board[i][(j++)+gameInfo.holdingsWidth] = DarkSquare; p++;
18669             } else if (isdigit(*p)) {
18670                 emptycount = *p++ - '0';
18671                 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
18672                 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18673                 while (emptycount--)
18674                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18675             } else if (*p == '<') {
18676                 if(i == BOARD_HEIGHT-1) shuffle = 1;
18677                 else if (i != 0 || !shuffle) return FALSE;
18678                 p++;
18679             } else if (shuffle && *p == '>') {
18680                 p++; // for now ignore closing shuffle range, and assume rank-end
18681             } else if (*p == '?') {
18682                 if (j >= gameInfo.boardWidth) return FALSE;
18683                 if (i != 0  && i != BOARD_HEIGHT-1) return FALSE; // only on back-rank
18684                 board[i][(j++)+gameInfo.holdingsWidth] = ClearBoard; p++; subst++; // placeHolder
18685             } else if (*p == '+' || isalpha(*p)) {
18686                 char *q, *s = SUFFIXES;
18687                 if (j >= gameInfo.boardWidth) return FALSE;
18688                 if(*p=='+') {
18689                     char c = *++p;
18690                     if(q = strchr(s, p[1])) p++;
18691                     piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
18692                     if(piece == EmptySquare) return FALSE; /* unknown piece */
18693                     piece = (ChessSquare) (CHUPROMOTED(piece)); p++;
18694                     if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
18695                 } else {
18696                     char c = *p++;
18697                     if(q = strchr(s, *p)) p++;
18698                     piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
18699                 }
18700
18701                 if(piece==EmptySquare) return FALSE; /* unknown piece */
18702                 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
18703                     piece = (ChessSquare) (PROMOTED(piece));
18704                     if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
18705                     p++;
18706                 }
18707                 board[i][(j++)+gameInfo.holdingsWidth] = piece;
18708                 if(piece == king) wKingRank = i;
18709                 if(piece == WHITE_TO_BLACK king) bKingRank = i;
18710             } else {
18711                 return FALSE;
18712             }
18713         }
18714     }
18715     while (*p == '/' || *p == ' ') p++;
18716
18717     if(autoSize && w != 0) appData.NrFiles = w, InitPosition(TRUE);
18718
18719     /* [HGM] by default clear Crazyhouse holdings, if present */
18720     if(gameInfo.holdingsWidth) {
18721        for(i=0; i<handSize; i++) {
18722            board[i][0]             = EmptySquare; /* black holdings */
18723            board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
18724            board[i][1]             = (ChessSquare) 0; /* black counts */
18725            board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
18726        }
18727     }
18728
18729     /* [HGM] look for Crazyhouse holdings here */
18730     while(*p==' ') p++;
18731     if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
18732         int swap=0, wcnt=0, bcnt=0;
18733         if(*p == '[') p++;
18734         if(*p == '<') swap++, p++;
18735         if(*p == '-' ) p++; /* empty holdings */ else {
18736             if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
18737             /* if we would allow FEN reading to set board size, we would   */
18738             /* have to add holdings and shift the board read so far here   */
18739             while( (piece = CharToPiece(*p) ) != EmptySquare ) {
18740                 p++;
18741                 if((int) piece >= (int) BlackPawn ) {
18742                     i = (int)piece - (int)BlackPawn;
18743                     i = PieceToNumber((ChessSquare)i);
18744                     if( i >= gameInfo.holdingsSize ) return FALSE;
18745                     board[handSize-1-i][0] = piece; /* black holdings */
18746                     board[handSize-1-i][1]++;       /* black counts   */
18747                     bcnt++;
18748                 } else {
18749                     i = (int)piece - (int)WhitePawn;
18750                     i = PieceToNumber((ChessSquare)i);
18751                     if( i >= gameInfo.holdingsSize ) return FALSE;
18752                     board[i][BOARD_WIDTH-1] = piece;    /* white holdings */
18753                     board[i][BOARD_WIDTH-2]++;          /* black holdings */
18754                     wcnt++;
18755                 }
18756             }
18757             if(subst) { // substitute back-rank question marks by holdings pieces
18758                 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
18759                     int k, m, n = bcnt + 1;
18760                     if(board[0][j] == ClearBoard) {
18761                         if(!wcnt) return FALSE;
18762                         n = rand() % wcnt;
18763                         for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((m -= board[k][BOARD_WIDTH-2]) < 0) {
18764                             board[0][j] = board[k][BOARD_WIDTH-1]; wcnt--;
18765                             if(--board[k][BOARD_WIDTH-2] == 0) board[k][BOARD_WIDTH-1] = EmptySquare;
18766                             break;
18767                         }
18768                     }
18769                     if(board[BOARD_HEIGHT-1][j] == ClearBoard) {
18770                         if(!bcnt) return FALSE;
18771                         if(n >= bcnt) n = rand() % bcnt; // use same randomization for black and white if possible
18772                         for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((n -= board[handSize-1-k][1]) < 0) {
18773                             board[BOARD_HEIGHT-1][j] = board[handSize-1-k][0]; bcnt--;
18774                             if(--board[handSize-1-k][1] == 0) board[handSize-1-k][0] = EmptySquare;
18775                             break;
18776                         }
18777                     }
18778                 }
18779                 subst = 0;
18780             }
18781         }
18782         if(*p == ']') p++;
18783     }
18784
18785     if(subst) return FALSE; // substitution requested, but no holdings
18786
18787     while(*p == ' ') p++;
18788
18789     /* Active color */
18790     c = *p++;
18791     if(appData.colorNickNames) {
18792       if( c == appData.colorNickNames[0] ) c = 'w'; else
18793       if( c == appData.colorNickNames[1] ) c = 'b';
18794     }
18795     switch (c) {
18796       case 'w':
18797         *blackPlaysFirst = FALSE;
18798         break;
18799       case 'b':
18800         *blackPlaysFirst = TRUE;
18801         break;
18802       default:
18803         return FALSE;
18804     }
18805
18806     /* [HGM] We NO LONGER ignore the rest of the FEN notation */
18807     /* return the extra info in global variiables             */
18808
18809     while(*p==' ') p++;
18810
18811     if(!isdigit(*p) && *p != '-') { // we seem to have castling rights. Make sure they are on the rank the King actually is.
18812         if(wKingRank >= 0) for(i=0; i<3; i++) castlingRank[i] = wKingRank;
18813         if(bKingRank >= 0) for(i=3; i<6; i++) castlingRank[i] = bKingRank;
18814     }
18815
18816     /* set defaults in case FEN is incomplete */
18817     board[EP_STATUS] = EP_UNKNOWN;
18818     board[TOUCHED_W] = board[TOUCHED_B] = 0;
18819     for(i=0; i<nrCastlingRights; i++ ) {
18820         board[CASTLING][i] =
18821             appData.fischerCastling ? NoRights : initialRights[i];
18822     }   /* assume possible unless obviously impossible */
18823     if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
18824     if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
18825     if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
18826                                   && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
18827     if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
18828     if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
18829     if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
18830                                   && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
18831     FENrulePlies = 0;
18832
18833     if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
18834       char *q = p;
18835       int w=0, b=0;
18836       while(isalpha(*p)) {
18837         if(isupper(*p)) w |= 1 << (*p++ - 'A');
18838         if(islower(*p)) b |= 1 << (*p++ - 'a');
18839       }
18840       if(*p == '-') p++;
18841       if(p != q) {
18842         board[TOUCHED_W] = ~w;
18843         board[TOUCHED_B] = ~b;
18844         while(*p == ' ') p++;
18845       }
18846     } else
18847
18848     if(nrCastlingRights) {
18849       int fischer = 0;
18850       if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
18851       if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
18852           /* castling indicator present, so default becomes no castlings */
18853           for(i=0; i<nrCastlingRights; i++ ) {
18854                  board[CASTLING][i] = NoRights;
18855           }
18856       }
18857       while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
18858              (appData.fischerCastling || gameInfo.variant == VariantSChess) &&
18859              ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
18860              ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth)   ) {
18861         int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
18862
18863         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
18864             if(board[castlingRank[5]][i] == BlackKing) blackKingFile = i;
18865             if(board[castlingRank[2]][i] == WhiteKing) whiteKingFile = i;
18866         }
18867         if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
18868             whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
18869         if(whiteKingFile == NoRights || board[castlingRank[2]][whiteKingFile] != WhiteUnicorn
18870                                      && board[castlingRank[2]][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
18871         if(blackKingFile == NoRights || board[castlingRank[5]][blackKingFile] != BlackUnicorn
18872                                      && board[castlingRank[5]][blackKingFile] != BlackKing) blackKingFile = NoRights;
18873         switch(c) {
18874           case'K':
18875               for(i=BOARD_RGHT-1; board[castlingRank[2]][i]!=WhiteRook && i>whiteKingFile; i--);
18876               board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
18877               board[CASTLING][2] = whiteKingFile;
18878               if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
18879               if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18880               if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18881               break;
18882           case'Q':
18883               for(i=BOARD_LEFT;  i<BOARD_RGHT && board[castlingRank[2]][i]!=WhiteRook && i<whiteKingFile; i++);
18884               board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
18885               board[CASTLING][2] = whiteKingFile;
18886               if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
18887               if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18888               if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18889               break;
18890           case'k':
18891               for(i=BOARD_RGHT-1; board[castlingRank[5]][i]!=BlackRook && i>blackKingFile; i--);
18892               board[CASTLING][3] = i != blackKingFile ? i : NoRights;
18893               board[CASTLING][5] = blackKingFile;
18894               if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
18895               if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18896               if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18897               break;
18898           case'q':
18899               for(i=BOARD_LEFT; i<BOARD_RGHT && board[castlingRank[5]][i]!=BlackRook && i<blackKingFile; i++);
18900               board[CASTLING][4] = i != blackKingFile ? i : NoRights;
18901               board[CASTLING][5] = blackKingFile;
18902               if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
18903               if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18904               if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18905           case '-':
18906               break;
18907           default: /* FRC castlings */
18908               if(c >= 'a') { /* black rights */
18909                   if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
18910                   for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18911                     if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
18912                   if(i == BOARD_RGHT) break;
18913                   board[CASTLING][5] = i;
18914                   c -= AAA;
18915                   if(board[BOARD_HEIGHT-1][c] <  BlackPawn ||
18916                      board[BOARD_HEIGHT-1][c] >= BlackKing   ) break;
18917                   if(c > i)
18918                       board[CASTLING][3] = c;
18919                   else
18920                       board[CASTLING][4] = c;
18921               } else { /* white rights */
18922                   if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
18923                   for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18924                     if(board[0][i] == WhiteKing) break;
18925                   if(i == BOARD_RGHT) break;
18926                   board[CASTLING][2] = i;
18927                   c -= AAA - 'a' + 'A';
18928                   if(board[0][c] >= WhiteKing) break;
18929                   if(c > i)
18930                       board[CASTLING][0] = c;
18931                   else
18932                       board[CASTLING][1] = c;
18933               }
18934         }
18935       }
18936       for(i=0; i<nrCastlingRights; i++)
18937         if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
18938       if(gameInfo.variant == VariantSChess)
18939         for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = shuffle ? VIRGIN_W | VIRGIN_B : virgin[i]; // when shuffling assume all virgin
18940       if(fischer && shuffle) appData.fischerCastling = TRUE;
18941     if (appData.debugMode) {
18942         fprintf(debugFP, "FEN castling rights:");
18943         for(i=0; i<nrCastlingRights; i++)
18944         fprintf(debugFP, " %d", board[CASTLING][i]);
18945         fprintf(debugFP, "\n");
18946     }
18947
18948       while(*p==' ') p++;
18949     }
18950
18951     if(shuffle) SetUpShuffle(board, appData.defaultFrcPosition);
18952
18953     /* read e.p. field in games that know e.p. capture */
18954     if(gameInfo.variant != VariantShogi    && gameInfo.variant != VariantXiangqi &&
18955        gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18956        gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
18957       if(*p=='-') {
18958         p++; board[EP_STATUS] = EP_NONE;
18959       } else {
18960          int d, r, c = *p - AAA;
18961
18962          if(c >= BOARD_LEFT && c < BOARD_RGHT) {
18963              p++;
18964              board[EP_STATUS] = board[EP_FILE] = c; r = 0;
18965              if(*p >= '0' && *p <='9') r = board[EP_RANK] = *p++ - ONE;
18966              d = (r < BOARD_HEIGHT << 1 ? 1 : -1); // assume double-push (P next to e.p. square nearer center)
18967              if(board[r+d][c] == EmptySquare) d *= 2; // but if no Pawn there, triple push
18968              board[LAST_TO] = 256*(r + d) + c;
18969              c = *p++ - AAA;
18970              if(c >= BOARD_LEFT && c < BOARD_RGHT) { // mover explicitly mentioned
18971                  if(*p >= '0' && *p <='9') r = board[EP_RANK] = *p++ - ONE;
18972                  board[LAST_TO] = 256*r + c;
18973                  if(!(board[EP_RANK]-r & 1)) board[EP_RANK] |= 128;
18974              }
18975          }
18976       }
18977     }
18978
18979     while(*p == ' ') p++;
18980
18981     board[CHECK_COUNT] = 0; // [HGM] 3check: check-count field
18982     if(sscanf(p, "%d+%d", &i, &j) == 2) {
18983         board[CHECK_COUNT] = i + 256*j;
18984         while(*p && *p != ' ') p++;
18985     }
18986
18987     c = sscanf(p, "%d%*d +%d+%d", &i, &j, &k);
18988     if(c > 0) {
18989         FENrulePlies = i; /* 50-move ply counter */
18990         /* (The move number is still ignored)    */
18991         if(c == 3 && !board[CHECK_COUNT]) board[CHECK_COUNT] = (3 - j) + 256*(3 - k); // SCIDB-style check count
18992     }
18993
18994     return TRUE;
18995 }
18996
18997 void
18998 EditPositionPasteFEN (char *fen)
18999 {
19000   if (fen != NULL) {
19001     Board initial_position;
19002
19003     if (!ParseFEN(initial_position, &blackPlaysFirst, fen, TRUE)) {
19004       DisplayError(_("Bad FEN position in clipboard"), 0);
19005       return ;
19006     } else {
19007       int savedBlackPlaysFirst = blackPlaysFirst;
19008       EditPositionEvent();
19009       blackPlaysFirst = savedBlackPlaysFirst;
19010       CopyBoard(boards[0], initial_position);
19011       initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
19012       EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
19013       DisplayBothClocks();
19014       DrawPosition(FALSE, boards[currentMove]);
19015     }
19016   }
19017 }
19018
19019 static char cseq[12] = "\\   ";
19020
19021 Boolean
19022 set_cont_sequence (char *new_seq)
19023 {
19024     int len;
19025     Boolean ret;
19026
19027     // handle bad attempts to set the sequence
19028         if (!new_seq)
19029                 return 0; // acceptable error - no debug
19030
19031     len = strlen(new_seq);
19032     ret = (len > 0) && (len < sizeof(cseq));
19033     if (ret)
19034       safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
19035     else if (appData.debugMode)
19036       fprintf(debugFP, "Invalid continuation sequence \"%s\"  (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
19037     return ret;
19038 }
19039
19040 /*
19041     reformat a source message so words don't cross the width boundary.  internal
19042     newlines are not removed.  returns the wrapped size (no null character unless
19043     included in source message).  If dest is NULL, only calculate the size required
19044     for the dest buffer.  lp argument indicats line position upon entry, and it's
19045     passed back upon exit.
19046 */
19047 int
19048 wrap (char *dest, char *src, int count, int width, int *lp)
19049 {
19050     int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
19051
19052     cseq_len = strlen(cseq);
19053     old_line = line = *lp;
19054     ansi = len = clen = 0;
19055
19056     for (i=0; i < count; i++)
19057     {
19058         if (src[i] == '\033')
19059             ansi = 1;
19060
19061         // if we hit the width, back up
19062         if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
19063         {
19064             // store i & len in case the word is too long
19065             old_i = i, old_len = len;
19066
19067             // find the end of the last word
19068             while (i && src[i] != ' ' && src[i] != '\n')
19069             {
19070                 i--;
19071                 len--;
19072             }
19073
19074             // word too long?  restore i & len before splitting it
19075             if ((old_i-i+clen) >= width)
19076             {
19077                 i = old_i;
19078                 len = old_len;
19079             }
19080
19081             // extra space?
19082             if (i && src[i-1] == ' ')
19083                 len--;
19084
19085             if (src[i] != ' ' && src[i] != '\n')
19086             {
19087                 i--;
19088                 if (len)
19089                     len--;
19090             }
19091
19092             // now append the newline and continuation sequence
19093             if (dest)
19094                 dest[len] = '\n';
19095             len++;
19096             if (dest)
19097                 strncpy(dest+len, cseq, cseq_len);
19098             len += cseq_len;
19099             line = cseq_len;
19100             clen = cseq_len;
19101             continue;
19102         }
19103
19104         if (dest)
19105             dest[len] = src[i];
19106         len++;
19107         if (!ansi)
19108             line++;
19109         if (src[i] == '\n')
19110             line = 0;
19111         if (src[i] == 'm')
19112             ansi = 0;
19113     }
19114     if (dest && appData.debugMode)
19115     {
19116         fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
19117             count, width, line, len, *lp);
19118         show_bytes(debugFP, src, count);
19119         fprintf(debugFP, "\ndest: ");
19120         show_bytes(debugFP, dest, len);
19121         fprintf(debugFP, "\n");
19122     }
19123     *lp = dest ? line : old_line;
19124
19125     return len;
19126 }
19127
19128 // [HGM] vari: routines for shelving variations
19129 Boolean modeRestore = FALSE;
19130
19131 void
19132 PushInner (int firstMove, int lastMove)
19133 {
19134         int i, j, nrMoves = lastMove - firstMove;
19135
19136         // push current tail of game on stack
19137         savedResult[storedGames] = gameInfo.result;
19138         savedDetails[storedGames] = gameInfo.resultDetails;
19139         gameInfo.resultDetails = NULL;
19140         savedFirst[storedGames] = firstMove;
19141         savedLast [storedGames] = lastMove;
19142         savedFramePtr[storedGames] = framePtr;
19143         framePtr -= nrMoves; // reserve space for the boards
19144         for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
19145             CopyBoard(boards[framePtr+i], boards[firstMove+i]);
19146             for(j=0; j<MOVE_LEN; j++)
19147                 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
19148             for(j=0; j<2*MOVE_LEN; j++)
19149                 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
19150             timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
19151             timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
19152             pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
19153             pvInfoList[firstMove+i-1].depth = 0;
19154             commentList[framePtr+i] = commentList[firstMove+i];
19155             commentList[firstMove+i] = NULL;
19156         }
19157
19158         storedGames++;
19159         forwardMostMove = firstMove; // truncate game so we can start variation
19160 }
19161
19162 void
19163 PushTail (int firstMove, int lastMove)
19164 {
19165         if(appData.icsActive) { // only in local mode
19166                 forwardMostMove = currentMove; // mimic old ICS behavior
19167                 return;
19168         }
19169         if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
19170
19171         PushInner(firstMove, lastMove);
19172         if(storedGames == 1) GreyRevert(FALSE);
19173         if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
19174 }
19175
19176 void
19177 PopInner (Boolean annotate)
19178 {
19179         int i, j, nrMoves;
19180         char buf[8000], moveBuf[20];
19181
19182         ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
19183         storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
19184         nrMoves = savedLast[storedGames] - currentMove;
19185         if(annotate) {
19186                 int cnt = 10;
19187                 if(!WhiteOnMove(currentMove))
19188                   snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
19189                 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
19190                 for(i=currentMove; i<forwardMostMove; i++) {
19191                         if(WhiteOnMove(i))
19192                           snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
19193                         else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
19194                         strcat(buf, moveBuf);
19195                         if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
19196                         if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
19197                 }
19198                 strcat(buf, ")");
19199         }
19200         for(i=1; i<=nrMoves; i++) { // copy last variation back
19201             CopyBoard(boards[currentMove+i], boards[framePtr+i]);
19202             for(j=0; j<MOVE_LEN; j++)
19203                 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
19204             for(j=0; j<2*MOVE_LEN; j++)
19205                 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
19206             timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
19207             timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
19208             pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
19209             if(commentList[currentMove+i]) free(commentList[currentMove+i]);
19210             commentList[currentMove+i] = commentList[framePtr+i];
19211             commentList[framePtr+i] = NULL;
19212         }
19213         if(annotate) AppendComment(currentMove+1, buf, FALSE);
19214         framePtr = savedFramePtr[storedGames];
19215         gameInfo.result = savedResult[storedGames];
19216         if(gameInfo.resultDetails != NULL) {
19217             free(gameInfo.resultDetails);
19218       }
19219         gameInfo.resultDetails = savedDetails[storedGames];
19220         forwardMostMove = currentMove + nrMoves;
19221 }
19222
19223 Boolean
19224 PopTail (Boolean annotate)
19225 {
19226         if(appData.icsActive) return FALSE; // only in local mode
19227         if(!storedGames) return FALSE; // sanity
19228         CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
19229
19230         PopInner(annotate);
19231         if(currentMove < forwardMostMove) ForwardEvent(); else
19232         HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
19233
19234         if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
19235         return TRUE;
19236 }
19237
19238 void
19239 CleanupTail ()
19240 {       // remove all shelved variations
19241         int i;
19242         for(i=0; i<storedGames; i++) {
19243             if(savedDetails[i])
19244                 free(savedDetails[i]);
19245             savedDetails[i] = NULL;
19246         }
19247         for(i=framePtr; i<MAX_MOVES; i++) {
19248                 if(commentList[i]) free(commentList[i]);
19249                 commentList[i] = NULL;
19250         }
19251         framePtr = MAX_MOVES-1;
19252         storedGames = 0;
19253 }
19254
19255 void
19256 LoadVariation (int index, char *text)
19257 {       // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
19258         char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
19259         int level = 0, move;
19260
19261         if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
19262         // first find outermost bracketing variation
19263         while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
19264             if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
19265                 if(*p == '{') wait = '}'; else
19266                 if(*p == '[') wait = ']'; else
19267                 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
19268                 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
19269             }
19270             if(*p == wait) wait = NULLCHAR; // closing ]} found
19271             p++;
19272         }
19273         if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
19274         if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
19275         end[1] = NULLCHAR; // clip off comment beyond variation
19276         ToNrEvent(currentMove-1);
19277         PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
19278         // kludge: use ParsePV() to append variation to game
19279         move = currentMove;
19280         ParsePV(start, TRUE, TRUE);
19281         forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
19282         ClearPremoveHighlights();
19283         CommentPopDown();
19284         ToNrEvent(currentMove+1);
19285 }
19286
19287 int transparency[2];
19288
19289 void
19290 LoadTheme ()
19291 {
19292 #define BUF_SIZ (2*MSG_SIZ)
19293     char *p, *q, buf[BUF_SIZ];
19294     if(engineLine && engineLine[0]) { // a theme was selected from the listbox
19295         snprintf(buf, BUF_SIZ, "-theme %s", engineLine);
19296         ParseArgsFromString(buf);
19297         ActivateTheme(TRUE); // also redo colors
19298         return;
19299     }
19300     p = nickName;
19301     if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
19302     {
19303         int len;
19304         q = appData.themeNames;
19305         snprintf(buf, BUF_SIZ, "\"%s\"", nickName);
19306       if(appData.useBitmaps) {
19307         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt true -lbtf \"%s\"",
19308                 Shorten(appData.liteBackTextureFile));
19309         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dbtf \"%s\" -lbtm %d -dbtm %d",
19310                 Shorten(appData.darkBackTextureFile),
19311                 appData.liteBackTextureMode,
19312                 appData.darkBackTextureMode );
19313       } else {
19314         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt false");
19315       }
19316       if(!appData.useBitmaps || transparency[0]) {
19317         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -lsc %s", Col2Text(2) ); // lightSquareColor
19318       }
19319       if(!appData.useBitmaps || transparency[1]) {
19320         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dsc %s", Col2Text(3) ); // darkSquareColor
19321       }
19322       if(appData.useBorder) {
19323         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub true -border \"%s\"",
19324                 appData.border);
19325       } else {
19326         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub false");
19327       }
19328       if(appData.useFont) {
19329         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
19330                 appData.renderPiecesWithFont,
19331                 appData.fontToPieceTable,
19332                 Col2Text(9),    // appData.fontBackColorWhite
19333                 Col2Text(10) ); // appData.fontForeColorBlack
19334       } else {
19335         snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf false");
19336         if(appData.pieceDirectory[0]) {
19337           snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -pid \"%s\"", Shorten(appData.pieceDirectory));
19338           if(appData.trueColors != 2) // 2 is a kludge to suppress this in WinBoard
19339             snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -trueColors %s", appData.trueColors ? "true" : "false");
19340         }
19341         if(!appData.pieceDirectory[0] || !appData.trueColors)
19342           snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -wpc %s -bpc %s",
19343                 Col2Text(0),   // whitePieceColor
19344                 Col2Text(1) ); // blackPieceColor
19345       }
19346       snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -hsc %s -phc %s\n",
19347                 Col2Text(4),   // highlightSquareColor
19348                 Col2Text(5) ); // premoveHighlightColor
19349         appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
19350         if(insert != q) insert[-1] = NULLCHAR;
19351         snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
19352         if(q)   free(q);
19353     }
19354     ActivateTheme(FALSE);
19355 }