b43a970a39d0b4d87e84a8f94155c0cac93493b7
[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 Free Software Foundation, Inc.
9  *
10  * Enhancements Copyright 2005 Alessandro Scotti
11  *
12  * The following terms apply to Digital Equipment Corporation's copyright
13  * interest in XBoard:
14  * ------------------------------------------------------------------------
15  * All Rights Reserved
16  *
17  * Permission to use, copy, modify, and distribute this software and its
18  * documentation for any purpose and without fee is hereby granted,
19  * provided that the above copyright notice appear in all copies and that
20  * both that copyright notice and this permission notice appear in
21  * supporting documentation, and that the name of Digital not be
22  * used in advertising or publicity pertaining to distribution of the
23  * software without specific, written prior permission.
24  *
25  * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
26  * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
27  * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
28  * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
30  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
31  * SOFTWARE.
32  * ------------------------------------------------------------------------
33  *
34  * The following terms apply to the enhanced version of XBoard
35  * distributed by the Free Software Foundation:
36  * ------------------------------------------------------------------------
37  *
38  * GNU XBoard is free software: you can redistribute it and/or modify
39  * it under the terms of the GNU General Public License as published by
40  * the Free Software Foundation, either version 3 of the License, or (at
41  * your option) any later version.
42  *
43  * GNU XBoard is distributed in the hope that it will be useful, but
44  * WITHOUT ANY WARRANTY; without even the implied warranty of
45  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46  * General Public License for more details.
47  *
48  * You should have received a copy of the GNU General Public License
49  * along with this program. If not, see http://www.gnu.org/licenses/.  *
50  *
51  *------------------------------------------------------------------------
52  ** See the file ChangeLog for a revision history.  */
53
54 /* [AS] Also useful here for debugging */
55 #ifdef WIN32
56 #include <windows.h>
57
58 int flock(int f, int code);
59 #define LOCK_EX 2
60 #define SLASH '\\'
61
62 #else
63
64 #include <sys/file.h>
65 #define SLASH '/'
66
67 #endif
68
69 #include "config.h"
70
71 #include <assert.h>
72 #include <stdio.h>
73 #include <ctype.h>
74 #include <errno.h>
75 #include <sys/types.h>
76 #include <sys/stat.h>
77 #include <math.h>
78 #include <ctype.h>
79
80 #if STDC_HEADERS
81 # include <stdlib.h>
82 # include <string.h>
83 # include <stdarg.h>
84 #else /* not STDC_HEADERS */
85 # if HAVE_STRING_H
86 #  include <string.h>
87 # else /* not HAVE_STRING_H */
88 #  include <strings.h>
89 # endif /* not HAVE_STRING_H */
90 #endif /* not STDC_HEADERS */
91
92 #if HAVE_SYS_FCNTL_H
93 # include <sys/fcntl.h>
94 #else /* not HAVE_SYS_FCNTL_H */
95 # if HAVE_FCNTL_H
96 #  include <fcntl.h>
97 # endif /* HAVE_FCNTL_H */
98 #endif /* not HAVE_SYS_FCNTL_H */
99
100 #if TIME_WITH_SYS_TIME
101 # include <sys/time.h>
102 # include <time.h>
103 #else
104 # if HAVE_SYS_TIME_H
105 #  include <sys/time.h>
106 # else
107 #  include <time.h>
108 # endif
109 #endif
110
111 #if defined(_amigados) && !defined(__GNUC__)
112 struct timezone {
113     int tz_minuteswest;
114     int tz_dsttime;
115 };
116 extern int gettimeofday(struct timeval *, struct timezone *);
117 #endif
118
119 #if HAVE_UNISTD_H
120 # include <unistd.h>
121 #endif
122
123 #include "common.h"
124 #include "frontend.h"
125 #include "backend.h"
126 #include "parser.h"
127 #include "moves.h"
128 #if ZIPPY
129 # include "zippy.h"
130 #endif
131 #include "backendz.h"
132 #include "evalgraph.h"
133 #include "gettext.h"
134
135 #ifdef ENABLE_NLS
136 # define _(s) gettext (s)
137 # define N_(s) gettext_noop (s)
138 # define T_(s) gettext(s)
139 #else
140 # ifdef WIN32
141 #   define _(s) T_(s)
142 #   define N_(s) s
143 # else
144 #   define _(s) (s)
145 #   define N_(s) s
146 #   define T_(s) s
147 # endif
148 #endif
149
150
151 int establish P((void));
152 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
153                          char *buf, int count, int error));
154 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
155                       char *buf, int count, int error));
156 void SendToICS P((char *s));
157 void SendToICSDelayed P((char *s, long msdelay));
158 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
159 void HandleMachineMove P((char *message, ChessProgramState *cps));
160 int AutoPlayOneMove P((void));
161 int LoadGameOneMove P((ChessMove readAhead));
162 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
163 int LoadPositionFromFile P((char *filename, int n, char *title));
164 int SavePositionToFile P((char *filename));
165 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
166 void ShowMove P((int fromX, int fromY, int toX, int toY));
167 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
168                    /*char*/int promoChar));
169 void BackwardInner P((int target));
170 void ForwardInner P((int target));
171 int Adjudicate P((ChessProgramState *cps));
172 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
173 void EditPositionDone P((Boolean fakeRights));
174 void PrintOpponents P((FILE *fp));
175 void PrintPosition P((FILE *fp, int move));
176 void StartChessProgram P((ChessProgramState *cps));
177 void SendToProgram P((char *message, ChessProgramState *cps));
178 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
179 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
180                            char *buf, int count, int error));
181 void SendTimeControl P((ChessProgramState *cps,
182                         int mps, long tc, int inc, int sd, int st));
183 char *TimeControlTagValue P((void));
184 void Attention P((ChessProgramState *cps));
185 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
186 int ResurrectChessProgram P((void));
187 void DisplayComment P((int moveNumber, char *text));
188 void DisplayMove P((int moveNumber));
189
190 void ParseGameHistory P((char *game));
191 void ParseBoard12 P((char *string));
192 void KeepAlive P((void));
193 void StartClocks P((void));
194 void SwitchClocks P((int nr));
195 void StopClocks P((void));
196 void ResetClocks P((void));
197 char *PGNDate P((void));
198 void SetGameInfo P((void));
199 int RegisterMove P((void));
200 void MakeRegisteredMove P((void));
201 void TruncateGame P((void));
202 int looking_at P((char *, int *, char *));
203 void CopyPlayerNameIntoFileName P((char **, char *));
204 char *SavePart P((char *));
205 int SaveGameOldStyle P((FILE *));
206 int SaveGamePGN P((FILE *));
207 int CheckFlags P((void));
208 long NextTickLength P((long));
209 void CheckTimeControl P((void));
210 void show_bytes P((FILE *, char *, int));
211 int string_to_rating P((char *str));
212 void ParseFeatures P((char* args, ChessProgramState *cps));
213 void InitBackEnd3 P((void));
214 void FeatureDone P((ChessProgramState* cps, int val));
215 void InitChessProgram P((ChessProgramState *cps, int setup));
216 void OutputKibitz(int window, char *text);
217 int PerpetualChase(int first, int last);
218 int EngineOutputIsUp();
219 void InitDrawingSizes(int x, int y);
220 void NextMatchGame P((void));
221 int NextTourneyGame P((int nr, int *swap));
222 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
223 FILE *WriteTourneyFile P((char *results, FILE *f));
224 void DisplayTwoMachinesTitle P(());
225 static void ExcludeClick P((int index));
226 void ToggleSecond P((void));
227 void PauseEngine P((ChessProgramState *cps));
228 static int NonStandardBoardSize P((void));
229
230 #ifdef WIN32
231        extern void ConsoleCreate();
232 #endif
233
234 ChessProgramState *WhitePlayer();
235 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
236 int VerifyDisplayMode P(());
237
238 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
239 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
240 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
241 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
242 void ics_update_width P((int new_width));
243 extern char installDir[MSG_SIZ];
244 VariantClass startVariant; /* [HGM] nicks: initial variant */
245 Boolean abortMatch;
246
247 extern int tinyLayout, smallLayout;
248 ChessProgramStats programStats;
249 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
250 int endPV = -1;
251 static int exiting = 0; /* [HGM] moved to top */
252 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
253 int startedFromPositionFile = FALSE; Board filePosition;       /* [HGM] loadPos */
254 Board partnerBoard;     /* [HGM] bughouse: for peeking at partner game          */
255 int partnerHighlight[2];
256 Boolean partnerBoardValid = 0;
257 char partnerStatus[MSG_SIZ];
258 Boolean partnerUp;
259 Boolean originalFlip;
260 Boolean twoBoards = 0;
261 char endingGame = 0;    /* [HGM] crash: flag to prevent recursion of GameEnds() */
262 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS     */
263 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
264 int lastIndex = 0;      /* [HGM] autoinc: last game/position used in match mode */
265 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing      */
266 int opponentKibitzes;
267 int lastSavedGame; /* [HGM] save: ID of game */
268 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
269 extern int chatCount;
270 int chattingPartner;
271 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
272 char lastMsg[MSG_SIZ];
273 ChessSquare pieceSweep = EmptySquare;
274 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
275 int promoDefaultAltered;
276 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
277
278 /* States for ics_getting_history */
279 #define H_FALSE 0
280 #define H_REQUESTED 1
281 #define H_GOT_REQ_HEADER 2
282 #define H_GOT_UNREQ_HEADER 3
283 #define H_GETTING_MOVES 4
284 #define H_GOT_UNWANTED_HEADER 5
285
286 /* whosays values for GameEnds */
287 #define GE_ICS 0
288 #define GE_ENGINE 1
289 #define GE_PLAYER 2
290 #define GE_FILE 3
291 #define GE_XBOARD 4
292 #define GE_ENGINE1 5
293 #define GE_ENGINE2 6
294
295 /* Maximum number of games in a cmail message */
296 #define CMAIL_MAX_GAMES 20
297
298 /* Different types of move when calling RegisterMove */
299 #define CMAIL_MOVE   0
300 #define CMAIL_RESIGN 1
301 #define CMAIL_DRAW   2
302 #define CMAIL_ACCEPT 3
303
304 /* Different types of result to remember for each game */
305 #define CMAIL_NOT_RESULT 0
306 #define CMAIL_OLD_RESULT 1
307 #define CMAIL_NEW_RESULT 2
308
309 /* Telnet protocol constants */
310 #define TN_WILL 0373
311 #define TN_WONT 0374
312 #define TN_DO   0375
313 #define TN_DONT 0376
314 #define TN_IAC  0377
315 #define TN_ECHO 0001
316 #define TN_SGA  0003
317 #define TN_PORT 23
318
319 char*
320 safeStrCpy (char *dst, const char *src, size_t count)
321 { // [HGM] made safe
322   int i;
323   assert( dst != NULL );
324   assert( src != NULL );
325   assert( count > 0 );
326
327   for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
328   if(  i == count && dst[count-1] != NULLCHAR)
329     {
330       dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
331       if(appData.debugMode)
332         fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
333     }
334
335   return dst;
336 }
337
338 /* Some compiler can't cast u64 to double
339  * This function do the job for us:
340
341  * We use the highest bit for cast, this only
342  * works if the highest bit is not
343  * in use (This should not happen)
344  *
345  * We used this for all compiler
346  */
347 double
348 u64ToDouble (u64 value)
349 {
350   double r;
351   u64 tmp = value & u64Const(0x7fffffffffffffff);
352   r = (double)(s64)tmp;
353   if (value & u64Const(0x8000000000000000))
354        r +=  9.2233720368547758080e18; /* 2^63 */
355  return r;
356 }
357
358 /* Fake up flags for now, as we aren't keeping track of castling
359    availability yet. [HGM] Change of logic: the flag now only
360    indicates the type of castlings allowed by the rule of the game.
361    The actual rights themselves are maintained in the array
362    castlingRights, as part of the game history, and are not probed
363    by this function.
364  */
365 int
366 PosFlags (index)
367 {
368   int flags = F_ALL_CASTLE_OK;
369   if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
370   switch (gameInfo.variant) {
371   case VariantSuicide:
372     flags &= ~F_ALL_CASTLE_OK;
373   case VariantGiveaway:         // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
374     flags |= F_IGNORE_CHECK;
375   case VariantLosers:
376     flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
377     break;
378   case VariantAtomic:
379     flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
380     break;
381   case VariantKriegspiel:
382     flags |= F_KRIEGSPIEL_CAPTURE;
383     break;
384   case VariantCapaRandom:
385   case VariantFischeRandom:
386     flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
387   case VariantNoCastle:
388   case VariantShatranj:
389   case VariantCourier:
390   case VariantMakruk:
391   case VariantGrand:
392     flags &= ~F_ALL_CASTLE_OK;
393     break;
394   default:
395     break;
396   }
397   return flags;
398 }
399
400 FILE *gameFileFP, *debugFP, *serverFP;
401 char *currentDebugFile; // [HGM] debug split: to remember name
402
403 /*
404     [AS] Note: sometimes, the sscanf() function is used to parse the input
405     into a fixed-size buffer. Because of this, we must be prepared to
406     receive strings as long as the size of the input buffer, which is currently
407     set to 4K for Windows and 8K for the rest.
408     So, we must either allocate sufficiently large buffers here, or
409     reduce the size of the input buffer in the input reading part.
410 */
411
412 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
413 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
414 char thinkOutput1[MSG_SIZ*10];
415
416 ChessProgramState first, second, pairing;
417
418 /* premove variables */
419 int premoveToX = 0;
420 int premoveToY = 0;
421 int premoveFromX = 0;
422 int premoveFromY = 0;
423 int premovePromoChar = 0;
424 int gotPremove = 0;
425 Boolean alarmSounded;
426 /* end premove variables */
427
428 char *ics_prefix = "$";
429 enum ICS_TYPE ics_type = ICS_GENERIC;
430
431 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
432 int pauseExamForwardMostMove = 0;
433 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
434 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
435 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
436 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
437 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
438 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
439 int whiteFlag = FALSE, blackFlag = FALSE;
440 int userOfferedDraw = FALSE;
441 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
442 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
443 int cmailMoveType[CMAIL_MAX_GAMES];
444 long ics_clock_paused = 0;
445 ProcRef icsPR = NoProc, cmailPR = NoProc;
446 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
447 GameMode gameMode = BeginningOfGame;
448 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
449 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
450 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
451 int hiddenThinkOutputState = 0; /* [AS] */
452 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
453 int adjudicateLossPlies = 6;
454 char white_holding[64], black_holding[64];
455 TimeMark lastNodeCountTime;
456 long lastNodeCount=0;
457 int shiftKey, controlKey; // [HGM] set by mouse handler
458
459 int have_sent_ICS_logon = 0;
460 int movesPerSession;
461 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
462 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
463 Boolean adjustedClock;
464 long timeControl_2; /* [AS] Allow separate time controls */
465 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
466 long timeRemaining[2][MAX_MOVES];
467 int matchGame = 0, nextGame = 0, roundNr = 0;
468 Boolean waitingForGame = FALSE, startingEngine = FALSE;
469 TimeMark programStartTime, pauseStart;
470 char ics_handle[MSG_SIZ];
471 int have_set_title = 0;
472
473 /* animateTraining preserves the state of appData.animate
474  * when Training mode is activated. This allows the
475  * response to be animated when appData.animate == TRUE and
476  * appData.animateDragging == TRUE.
477  */
478 Boolean animateTraining;
479
480 GameInfo gameInfo;
481
482 AppData appData;
483
484 Board boards[MAX_MOVES];
485 /* [HGM] Following 7 needed for accurate legality tests: */
486 signed char  castlingRank[BOARD_FILES]; // and corresponding ranks
487 signed char  initialRights[BOARD_FILES];
488 int   nrCastlingRights; // For TwoKings, or to implement castling-unknown status
489 int   initialRulePlies, FENrulePlies;
490 FILE  *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
491 int loadFlag = 0;
492 Boolean shuffleOpenings;
493 int mute; // mute all sounds
494
495 // [HGM] vari: next 12 to save and restore variations
496 #define MAX_VARIATIONS 10
497 int framePtr = MAX_MOVES-1; // points to free stack entry
498 int storedGames = 0;
499 int savedFirst[MAX_VARIATIONS];
500 int savedLast[MAX_VARIATIONS];
501 int savedFramePtr[MAX_VARIATIONS];
502 char *savedDetails[MAX_VARIATIONS];
503 ChessMove savedResult[MAX_VARIATIONS];
504
505 void PushTail P((int firstMove, int lastMove));
506 Boolean PopTail P((Boolean annotate));
507 void PushInner P((int firstMove, int lastMove));
508 void PopInner P((Boolean annotate));
509 void CleanupTail P((void));
510
511 ChessSquare  FIDEArray[2][BOARD_FILES] = {
512     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
513         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
514     { BlackRook, BlackKnight, BlackBishop, BlackQueen,
515         BlackKing, BlackBishop, BlackKnight, BlackRook }
516 };
517
518 ChessSquare twoKingsArray[2][BOARD_FILES] = {
519     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
520         WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
521     { BlackRook, BlackKnight, BlackBishop, BlackQueen,
522         BlackKing, BlackKing, BlackKnight, BlackRook }
523 };
524
525 ChessSquare  KnightmateArray[2][BOARD_FILES] = {
526     { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
527         WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
528     { BlackRook, BlackMan, BlackBishop, BlackQueen,
529         BlackUnicorn, BlackBishop, BlackMan, BlackRook }
530 };
531
532 ChessSquare SpartanArray[2][BOARD_FILES] = {
533     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
534         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
535     { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
536         BlackDragon, BlackKing, BlackAngel, BlackAlfil }
537 };
538
539 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
540     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
541         WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
542     { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
543         BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
544 };
545
546 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
547     { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
548         WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
549     { BlackRook, BlackKnight, BlackAlfil, BlackKing,
550         BlackFerz, BlackAlfil, BlackKnight, BlackRook }
551 };
552
553 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
554     { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
555         WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
556     { BlackRook, BlackKnight, BlackMan, BlackFerz,
557         BlackKing, BlackMan, BlackKnight, BlackRook }
558 };
559
560
561 #if (BOARD_FILES>=10)
562 ChessSquare ShogiArray[2][BOARD_FILES] = {
563     { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
564         WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
565     { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
566         BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
567 };
568
569 ChessSquare XiangqiArray[2][BOARD_FILES] = {
570     { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
571         WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
572     { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
573         BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
574 };
575
576 ChessSquare CapablancaArray[2][BOARD_FILES] = {
577     { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
578         WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
579     { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
580         BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
581 };
582
583 ChessSquare GreatArray[2][BOARD_FILES] = {
584     { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
585         WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
586     { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
587         BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
588 };
589
590 ChessSquare JanusArray[2][BOARD_FILES] = {
591     { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
592         WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
593     { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
594         BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
595 };
596
597 ChessSquare GrandArray[2][BOARD_FILES] = {
598     { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
599         WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
600     { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
601         BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
602 };
603
604 #ifdef GOTHIC
605 ChessSquare GothicArray[2][BOARD_FILES] = {
606     { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
607         WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
608     { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
609         BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
610 };
611 #else // !GOTHIC
612 #define GothicArray CapablancaArray
613 #endif // !GOTHIC
614
615 #ifdef FALCON
616 ChessSquare FalconArray[2][BOARD_FILES] = {
617     { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
618         WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
619     { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
620         BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
621 };
622 #else // !FALCON
623 #define FalconArray CapablancaArray
624 #endif // !FALCON
625
626 #else // !(BOARD_FILES>=10)
627 #define XiangqiPosition FIDEArray
628 #define CapablancaArray FIDEArray
629 #define GothicArray FIDEArray
630 #define GreatArray FIDEArray
631 #endif // !(BOARD_FILES>=10)
632
633 #if (BOARD_FILES>=12)
634 ChessSquare CourierArray[2][BOARD_FILES] = {
635     { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
636         WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
637     { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
638         BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
639 };
640 #else // !(BOARD_FILES>=12)
641 #define CourierArray CapablancaArray
642 #endif // !(BOARD_FILES>=12)
643
644
645 Board initialPosition;
646
647
648 /* Convert str to a rating. Checks for special cases of "----",
649
650    "++++", etc. Also strips ()'s */
651 int
652 string_to_rating (char *str)
653 {
654   while(*str && !isdigit(*str)) ++str;
655   if (!*str)
656     return 0;   /* One of the special "no rating" cases */
657   else
658     return atoi(str);
659 }
660
661 void
662 ClearProgramStats ()
663 {
664     /* Init programStats */
665     programStats.movelist[0] = 0;
666     programStats.depth = 0;
667     programStats.nr_moves = 0;
668     programStats.moves_left = 0;
669     programStats.nodes = 0;
670     programStats.time = -1;        // [HGM] PGNtime: make invalid to recognize engine output
671     programStats.score = 0;
672     programStats.got_only_move = 0;
673     programStats.got_fail = 0;
674     programStats.line_is_book = 0;
675 }
676
677 void
678 CommonEngineInit ()
679 {   // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
680     if (appData.firstPlaysBlack) {
681         first.twoMachinesColor = "black\n";
682         second.twoMachinesColor = "white\n";
683     } else {
684         first.twoMachinesColor = "white\n";
685         second.twoMachinesColor = "black\n";
686     }
687
688     first.other = &second;
689     second.other = &first;
690
691     { float norm = 1;
692         if(appData.timeOddsMode) {
693             norm = appData.timeOdds[0];
694             if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
695         }
696         first.timeOdds  = appData.timeOdds[0]/norm;
697         second.timeOdds = appData.timeOdds[1]/norm;
698     }
699
700     if(programVersion) free(programVersion);
701     if (appData.noChessProgram) {
702         programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
703         sprintf(programVersion, "%s", PACKAGE_STRING);
704     } else {
705       /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
706       programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
707       sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
708     }
709 }
710
711 void
712 UnloadEngine (ChessProgramState *cps)
713 {
714         /* Kill off first chess program */
715         if (cps->isr != NULL)
716           RemoveInputSource(cps->isr);
717         cps->isr = NULL;
718
719         if (cps->pr != NoProc) {
720             ExitAnalyzeMode();
721             DoSleep( appData.delayBeforeQuit );
722             SendToProgram("quit\n", cps);
723             DoSleep( appData.delayAfterQuit );
724             DestroyChildProcess(cps->pr, cps->useSigterm);
725         }
726         cps->pr = NoProc;
727         if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
728 }
729
730 void
731 ClearOptions (ChessProgramState *cps)
732 {
733     int i;
734     cps->nrOptions = cps->comboCnt = 0;
735     for(i=0; i<MAX_OPTIONS; i++) {
736         cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
737         cps->option[i].textValue = 0;
738     }
739 }
740
741 char *engineNames[] = {
742   /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
743      such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
744 N_("first"),
745   /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
746      such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
747 N_("second")
748 };
749
750 void
751 InitEngine (ChessProgramState *cps, int n)
752 {   // [HGM] all engine initialiation put in a function that does one engine
753
754     ClearOptions(cps);
755
756     cps->which = engineNames[n];
757     cps->maybeThinking = FALSE;
758     cps->pr = NoProc;
759     cps->isr = NULL;
760     cps->sendTime = 2;
761     cps->sendDrawOffers = 1;
762
763     cps->program = appData.chessProgram[n];
764     cps->host = appData.host[n];
765     cps->dir = appData.directory[n];
766     cps->initString = appData.engInitString[n];
767     cps->computerString = appData.computerString[n];
768     cps->useSigint  = TRUE;
769     cps->useSigterm = TRUE;
770     cps->reuse = appData.reuse[n];
771     cps->nps = appData.NPS[n];   // [HGM] nps: copy nodes per second
772     cps->useSetboard = FALSE;
773     cps->useSAN = FALSE;
774     cps->usePing = FALSE;
775     cps->lastPing = 0;
776     cps->lastPong = 0;
777     cps->usePlayother = FALSE;
778     cps->useColors = TRUE;
779     cps->useUsermove = FALSE;
780     cps->sendICS = FALSE;
781     cps->sendName = appData.icsActive;
782     cps->sdKludge = FALSE;
783     cps->stKludge = FALSE;
784     if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
785     TidyProgramName(cps->program, cps->host, cps->tidy);
786     cps->matchWins = 0;
787     ASSIGN(cps->variants, appData.variant);
788     cps->analysisSupport = 2; /* detect */
789     cps->analyzing = FALSE;
790     cps->initDone = FALSE;
791     cps->reload = FALSE;
792
793     /* New features added by Tord: */
794     cps->useFEN960 = FALSE;
795     cps->useOOCastle = TRUE;
796     /* End of new features added by Tord. */
797     cps->fenOverride  = appData.fenOverride[n];
798
799     /* [HGM] time odds: set factor for each machine */
800     cps->timeOdds  = appData.timeOdds[n];
801
802     /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
803     cps->accumulateTC = appData.accumulateTC[n];
804     cps->maxNrOfSessions = 1;
805
806     /* [HGM] debug */
807     cps->debug = FALSE;
808
809     cps->supportsNPS = UNKNOWN;
810     cps->memSize = FALSE;
811     cps->maxCores = FALSE;
812     ASSIGN(cps->egtFormats, "");
813
814     /* [HGM] options */
815     cps->optionSettings  = appData.engOptions[n];
816
817     cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
818     cps->isUCI = appData.isUCI[n]; /* [AS] */
819     cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
820
821     if (appData.protocolVersion[n] > PROTOVER
822         || appData.protocolVersion[n] < 1)
823       {
824         char buf[MSG_SIZ];
825         int len;
826
827         len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
828                        appData.protocolVersion[n]);
829         if( (len >= MSG_SIZ) && appData.debugMode )
830           fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
831
832         DisplayFatalError(buf, 0, 2);
833       }
834     else
835       {
836         cps->protocolVersion = appData.protocolVersion[n];
837       }
838
839     InitEngineUCI( installDir, cps );  // [HGM] moved here from winboard.c, to make available in xboard
840     ParseFeatures(appData.featureDefaults, cps);
841 }
842
843 ChessProgramState *savCps;
844
845 GameMode oldMode;
846
847 void
848 LoadEngine ()
849 {
850     int i;
851     if(WaitForEngine(savCps, LoadEngine)) return;
852     CommonEngineInit(); // recalculate time odds
853     if(gameInfo.variant != StringToVariant(appData.variant)) {
854         // we changed variant when loading the engine; this forces us to reset
855         Reset(TRUE, savCps != &first);
856         oldMode = BeginningOfGame; // to prevent restoring old mode
857     }
858     InitChessProgram(savCps, FALSE);
859     if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
860     DisplayMessage("", "");
861     if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
862     for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
863     ThawUI();
864     SetGNUMode();
865     if(oldMode == AnalyzeMode) AnalyzeModeEvent();
866 }
867
868 void
869 ReplaceEngine (ChessProgramState *cps, int n)
870 {
871     oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
872     keepInfo = 1;
873     if(oldMode != BeginningOfGame) EditGameEvent();
874     keepInfo = 0;
875     UnloadEngine(cps);
876     appData.noChessProgram = FALSE;
877     appData.clockMode = TRUE;
878     InitEngine(cps, n);
879     UpdateLogos(TRUE);
880     if(n) return; // only startup first engine immediately; second can wait
881     savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
882     LoadEngine();
883 }
884
885 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
886 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
887
888 static char resetOptions[] =
889         "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
890         "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
891         "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 "
892         "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
893
894 void
895 FloatToFront(char **list, char *engineLine)
896 {
897     char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
898     int i=0;
899     if(appData.recentEngines <= 0) return;
900     TidyProgramName(engineLine, "localhost", tidy+1);
901     tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
902     strncpy(buf+1, *list, MSG_SIZ-50);
903     if(p = strstr(buf, tidy)) { // tidy name appears in list
904         q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
905         while(*p++ = *++q); // squeeze out
906     }
907     strcat(tidy, buf+1); // put list behind tidy name
908     p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
909     if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
910     ASSIGN(*list, tidy+1);
911 }
912
913 char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
914
915 void
916 Load (ChessProgramState *cps, int i)
917 {
918     char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ];
919     if(engineLine && engineLine[0]) { // an engine was selected from the combo box
920         snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
921         SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
922         ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
923         FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
924         appData.firstProtocolVersion = PROTOVER;
925         ParseArgsFromString(buf);
926         SwapEngines(i);
927         ReplaceEngine(cps, i);
928         FloatToFront(&appData.recentEngineList, engineLine);
929         return;
930     }
931     p = engineName;
932     while(q = strchr(p, SLASH)) p = q+1;
933     if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
934     if(engineDir[0] != NULLCHAR) {
935         ASSIGN(appData.directory[i], engineDir); p = engineName;
936     } else if(p != engineName) { // derive directory from engine path, when not given
937         p[-1] = 0;
938         ASSIGN(appData.directory[i], engineName);
939         p[-1] = SLASH;
940         if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
941     } else { ASSIGN(appData.directory[i], "."); }
942     if(params[0]) {
943         if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
944         snprintf(command, MSG_SIZ, "%s %s", p, params);
945         p = command;
946     }
947     ASSIGN(appData.chessProgram[i], p);
948     appData.isUCI[i] = isUCI;
949     appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
950     appData.hasOwnBookUCI[i] = hasBook;
951     if(!nickName[0]) useNick = FALSE;
952     if(useNick) ASSIGN(appData.pgnName[i], nickName);
953     if(addToList) {
954         int len;
955         char quote;
956         q = firstChessProgramNames;
957         if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
958         quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
959         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
960                         quote, p, quote, appData.directory[i],
961                         useNick ? " -fn \"" : "",
962                         useNick ? nickName : "",
963                         useNick ? "\"" : "",
964                         v1 ? " -firstProtocolVersion 1" : "",
965                         hasBook ? "" : " -fNoOwnBookUCI",
966                         isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
967                         storeVariant ? " -variant " : "",
968                         storeVariant ? VariantName(gameInfo.variant) : "");
969         if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf)-1, MSG_SIZ-strlen(buf), " %s\n", wbOptions);
970         firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
971         if(insert != q) insert[-1] = NULLCHAR;
972         snprintf(firstChessProgramNames, len, "%s\n%s%s", q, buf, insert);
973         if(q)   free(q);
974         FloatToFront(&appData.recentEngineList, buf);
975     }
976     ReplaceEngine(cps, i);
977 }
978
979 void
980 InitTimeControls ()
981 {
982     int matched, min, sec;
983     /*
984      * Parse timeControl resource
985      */
986     if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
987                           appData.movesPerSession)) {
988         char buf[MSG_SIZ];
989         snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
990         DisplayFatalError(buf, 0, 2);
991     }
992
993     /*
994      * Parse searchTime resource
995      */
996     if (*appData.searchTime != NULLCHAR) {
997         matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
998         if (matched == 1) {
999             searchTime = min * 60;
1000         } else if (matched == 2) {
1001             searchTime = min * 60 + sec;
1002         } else {
1003             char buf[MSG_SIZ];
1004             snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
1005             DisplayFatalError(buf, 0, 2);
1006         }
1007     }
1008 }
1009
1010 void
1011 InitBackEnd1 ()
1012 {
1013
1014     ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1015     startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1016
1017     GetTimeMark(&programStartTime);
1018     srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1019     appData.seedBase = random() + (random()<<15);
1020     pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1021
1022     ClearProgramStats();
1023     programStats.ok_to_send = 1;
1024     programStats.seen_stat = 0;
1025
1026     /*
1027      * Initialize game list
1028      */
1029     ListNew(&gameList);
1030
1031
1032     /*
1033      * Internet chess server status
1034      */
1035     if (appData.icsActive) {
1036         appData.matchMode = FALSE;
1037         appData.matchGames = 0;
1038 #if ZIPPY
1039         appData.noChessProgram = !appData.zippyPlay;
1040 #else
1041         appData.zippyPlay = FALSE;
1042         appData.zippyTalk = FALSE;
1043         appData.noChessProgram = TRUE;
1044 #endif
1045         if (*appData.icsHelper != NULLCHAR) {
1046             appData.useTelnet = TRUE;
1047             appData.telnetProgram = appData.icsHelper;
1048         }
1049     } else {
1050         appData.zippyTalk = appData.zippyPlay = FALSE;
1051     }
1052
1053     /* [AS] Initialize pv info list [HGM] and game state */
1054     {
1055         int i, j;
1056
1057         for( i=0; i<=framePtr; i++ ) {
1058             pvInfoList[i].depth = -1;
1059             boards[i][EP_STATUS] = EP_NONE;
1060             for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1061         }
1062     }
1063
1064     InitTimeControls();
1065
1066     /* [AS] Adjudication threshold */
1067     adjudicateLossThreshold = appData.adjudicateLossThreshold;
1068
1069     InitEngine(&first, 0);
1070     InitEngine(&second, 1);
1071     CommonEngineInit();
1072
1073     pairing.which = "pairing"; // pairing engine
1074     pairing.pr = NoProc;
1075     pairing.isr = NULL;
1076     pairing.program = appData.pairingEngine;
1077     pairing.host = "localhost";
1078     pairing.dir = ".";
1079
1080     if (appData.icsActive) {
1081         appData.clockMode = TRUE;  /* changes dynamically in ICS mode */
1082     } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1083         appData.clockMode = FALSE;
1084         first.sendTime = second.sendTime = 0;
1085     }
1086
1087 #if ZIPPY
1088     /* Override some settings from environment variables, for backward
1089        compatibility.  Unfortunately it's not feasible to have the env
1090        vars just set defaults, at least in xboard.  Ugh.
1091     */
1092     if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1093       ZippyInit();
1094     }
1095 #endif
1096
1097     if (!appData.icsActive) {
1098       char buf[MSG_SIZ];
1099       int len;
1100
1101       /* Check for variants that are supported only in ICS mode,
1102          or not at all.  Some that are accepted here nevertheless
1103          have bugs; see comments below.
1104       */
1105       VariantClass variant = StringToVariant(appData.variant);
1106       switch (variant) {
1107       case VariantBughouse:     /* need four players and two boards */
1108       case VariantKriegspiel:   /* need to hide pieces and move details */
1109         /* case VariantFischeRandom: (Fabien: moved below) */
1110         len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1111         if( (len >= MSG_SIZ) && appData.debugMode )
1112           fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1113
1114         DisplayFatalError(buf, 0, 2);
1115         return;
1116
1117       case VariantUnknown:
1118       case VariantLoadable:
1119       case Variant29:
1120       case Variant30:
1121       case Variant31:
1122       case Variant32:
1123       case Variant33:
1124       case Variant34:
1125       case Variant35:
1126       case Variant36:
1127       default:
1128         len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1129         if( (len >= MSG_SIZ) && appData.debugMode )
1130           fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1131
1132         DisplayFatalError(buf, 0, 2);
1133         return;
1134
1135       case VariantXiangqi:    /* [HGM] repetition rules not implemented */
1136       case VariantFairy:      /* [HGM] TestLegality definitely off! */
1137       case VariantGothic:     /* [HGM] should work */
1138       case VariantCapablanca: /* [HGM] should work */
1139       case VariantCourier:    /* [HGM] initial forced moves not implemented */
1140       case VariantShogi:      /* [HGM] could still mate with pawn drop */
1141       case VariantKnightmate: /* [HGM] should work */
1142       case VariantCylinder:   /* [HGM] untested */
1143       case VariantFalcon:     /* [HGM] untested */
1144       case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1145                                  offboard interposition not understood */
1146       case VariantNormal:     /* definitely works! */
1147       case VariantWildCastle: /* pieces not automatically shuffled */
1148       case VariantNoCastle:   /* pieces not automatically shuffled */
1149       case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1150       case VariantLosers:     /* should work except for win condition,
1151                                  and doesn't know captures are mandatory */
1152       case VariantSuicide:    /* should work except for win condition,
1153                                  and doesn't know captures are mandatory */
1154       case VariantGiveaway:   /* should work except for win condition,
1155                                  and doesn't know captures are mandatory */
1156       case VariantTwoKings:   /* should work */
1157       case VariantAtomic:     /* should work except for win condition */
1158       case Variant3Check:     /* should work except for win condition */
1159       case VariantShatranj:   /* should work except for all win conditions */
1160       case VariantMakruk:     /* should work except for draw countdown */
1161       case VariantBerolina:   /* might work if TestLegality is off */
1162       case VariantCapaRandom: /* should work */
1163       case VariantJanus:      /* should work */
1164       case VariantSuper:      /* experimental */
1165       case VariantGreat:      /* experimental, requires legality testing to be off */
1166       case VariantSChess:     /* S-Chess, should work */
1167       case VariantGrand:      /* should work */
1168       case VariantSpartan:    /* should work */
1169         break;
1170       }
1171     }
1172
1173 }
1174
1175 int
1176 NextIntegerFromString (char ** str, long * value)
1177 {
1178     int result = -1;
1179     char * s = *str;
1180
1181     while( *s == ' ' || *s == '\t' ) {
1182         s++;
1183     }
1184
1185     *value = 0;
1186
1187     if( *s >= '0' && *s <= '9' ) {
1188         while( *s >= '0' && *s <= '9' ) {
1189             *value = *value * 10 + (*s - '0');
1190             s++;
1191         }
1192
1193         result = 0;
1194     }
1195
1196     *str = s;
1197
1198     return result;
1199 }
1200
1201 int
1202 NextTimeControlFromString (char ** str, long * value)
1203 {
1204     long temp;
1205     int result = NextIntegerFromString( str, &temp );
1206
1207     if( result == 0 ) {
1208         *value = temp * 60; /* Minutes */
1209         if( **str == ':' ) {
1210             (*str)++;
1211             result = NextIntegerFromString( str, &temp );
1212             *value += temp; /* Seconds */
1213         }
1214     }
1215
1216     return result;
1217 }
1218
1219 int
1220 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1221 {   /* [HGM] routine added to read '+moves/time' for secondary time control. */
1222     int result = -1, type = 0; long temp, temp2;
1223
1224     if(**str != ':') return -1; // old params remain in force!
1225     (*str)++;
1226     if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1227     if( NextIntegerFromString( str, &temp ) ) return -1;
1228     if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1229
1230     if(**str != '/') {
1231         /* time only: incremental or sudden-death time control */
1232         if(**str == '+') { /* increment follows; read it */
1233             (*str)++;
1234             if(**str == '!') type = *(*str)++; // Bronstein TC
1235             if(result = NextIntegerFromString( str, &temp2)) return -1;
1236             *inc = temp2 * 1000;
1237             if(**str == '.') { // read fraction of increment
1238                 char *start = ++(*str);
1239                 if(result = NextIntegerFromString( str, &temp2)) return -1;
1240                 temp2 *= 1000;
1241                 while(start++ < *str) temp2 /= 10;
1242                 *inc += temp2;
1243             }
1244         } else *inc = 0;
1245         *moves = 0; *tc = temp * 1000; *incType = type;
1246         return 0;
1247     }
1248
1249     (*str)++; /* classical time control */
1250     result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1251
1252     if(result == 0) {
1253         *moves = temp;
1254         *tc    = temp2 * 1000;
1255         *inc   = 0;
1256         *incType = type;
1257     }
1258     return result;
1259 }
1260
1261 int
1262 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1263 {   /* [HGM] get time to add from the multi-session time-control string */
1264     int incType, moves=1; /* kludge to force reading of first session */
1265     long time, increment;
1266     char *s = tcString;
1267
1268     if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1269     do {
1270         if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1271         nextSession = s; suddenDeath = moves == 0 && increment == 0;
1272         if(movenr == -1) return time;    /* last move before new session     */
1273         if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1274         if(incType == '!' && lastUsed < increment) increment = lastUsed;
1275         if(!moves) return increment;     /* current session is incremental   */
1276         if(movenr >= 0) movenr -= moves; /* we already finished this session */
1277     } while(movenr >= -1);               /* try again for next session       */
1278
1279     return 0; // no new time quota on this move
1280 }
1281
1282 int
1283 ParseTimeControl (char *tc, float ti, int mps)
1284 {
1285   long tc1;
1286   long tc2;
1287   char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1288   int min, sec=0;
1289
1290   if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1291   if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1292       sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1293   if(ti > 0) {
1294
1295     if(mps)
1296       snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1297     else
1298       snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1299   } else {
1300     if(mps)
1301       snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1302     else
1303       snprintf(buf, MSG_SIZ, ":%s", mytc);
1304   }
1305   fullTimeControlString = StrSave(buf); // this should now be in PGN format
1306
1307   if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1308     return FALSE;
1309   }
1310
1311   if( *tc == '/' ) {
1312     /* Parse second time control */
1313     tc++;
1314
1315     if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1316       return FALSE;
1317     }
1318
1319     if( tc2 == 0 ) {
1320       return FALSE;
1321     }
1322
1323     timeControl_2 = tc2 * 1000;
1324   }
1325   else {
1326     timeControl_2 = 0;
1327   }
1328
1329   if( tc1 == 0 ) {
1330     return FALSE;
1331   }
1332
1333   timeControl = tc1 * 1000;
1334
1335   if (ti >= 0) {
1336     timeIncrement = ti * 1000;  /* convert to ms */
1337     movesPerSession = 0;
1338   } else {
1339     timeIncrement = 0;
1340     movesPerSession = mps;
1341   }
1342   return TRUE;
1343 }
1344
1345 void
1346 InitBackEnd2 ()
1347 {
1348     if (appData.debugMode) {
1349 #    ifdef __GIT_VERSION
1350       fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
1351 #    else
1352       fprintf(debugFP, "Version: %s\n", programVersion);
1353 #    endif
1354     }
1355     ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1356
1357     set_cont_sequence(appData.wrapContSeq);
1358     if (appData.matchGames > 0) {
1359         appData.matchMode = TRUE;
1360     } else if (appData.matchMode) {
1361         appData.matchGames = 1;
1362     }
1363     if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1364         appData.matchGames = appData.sameColorGames;
1365     if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1366         if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1367         if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1368     }
1369     Reset(TRUE, FALSE);
1370     if (appData.noChessProgram || first.protocolVersion == 1) {
1371       InitBackEnd3();
1372     } else {
1373       /* kludge: allow timeout for initial "feature" commands */
1374       FreezeUI();
1375       DisplayMessage("", _("Starting chess program"));
1376       ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1377     }
1378 }
1379
1380 int
1381 CalculateIndex (int index, int gameNr)
1382 {   // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1383     int res;
1384     if(index > 0) return index; // fixed nmber
1385     if(index == 0) return 1;
1386     res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1387     if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1388     return res;
1389 }
1390
1391 int
1392 LoadGameOrPosition (int gameNr)
1393 {   // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1394     if (*appData.loadGameFile != NULLCHAR) {
1395         if (!LoadGameFromFile(appData.loadGameFile,
1396                 CalculateIndex(appData.loadGameIndex, gameNr),
1397                               appData.loadGameFile, FALSE)) {
1398             DisplayFatalError(_("Bad game file"), 0, 1);
1399             return 0;
1400         }
1401     } else if (*appData.loadPositionFile != NULLCHAR) {
1402         if (!LoadPositionFromFile(appData.loadPositionFile,
1403                 CalculateIndex(appData.loadPositionIndex, gameNr),
1404                                   appData.loadPositionFile)) {
1405             DisplayFatalError(_("Bad position file"), 0, 1);
1406             return 0;
1407         }
1408     }
1409     return 1;
1410 }
1411
1412 void
1413 ReserveGame (int gameNr, char resChar)
1414 {
1415     FILE *tf = fopen(appData.tourneyFile, "r+");
1416     char *p, *q, c, buf[MSG_SIZ];
1417     if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1418     safeStrCpy(buf, lastMsg, MSG_SIZ);
1419     DisplayMessage(_("Pick new game"), "");
1420     flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1421     ParseArgsFromFile(tf);
1422     p = q = appData.results;
1423     if(appData.debugMode) {
1424       char *r = appData.participants;
1425       fprintf(debugFP, "results = '%s'\n", p);
1426       while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1427       fprintf(debugFP, "\n");
1428     }
1429     while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1430     nextGame = q - p;
1431     q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1432     safeStrCpy(q, p, strlen(p) + 2);
1433     if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1434     if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1435     if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1436         if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1437         q[nextGame] = '*';
1438     }
1439     fseek(tf, -(strlen(p)+4), SEEK_END);
1440     c = fgetc(tf);
1441     if(c != '"') // depending on DOS or Unix line endings we can be one off
1442          fseek(tf, -(strlen(p)+2), SEEK_END);
1443     else fseek(tf, -(strlen(p)+3), SEEK_END);
1444     fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1445     DisplayMessage(buf, "");
1446     free(p); appData.results = q;
1447     if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1448        (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1449       int round = appData.defaultMatchGames * appData.tourneyType;
1450       if(gameNr < 0 || appData.tourneyType < 1 ||  // gauntlet engine can always stay loaded as first engine
1451          appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1452         UnloadEngine(&first);  // next game belongs to other pairing;
1453         UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1454     }
1455     if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1456 }
1457
1458 void
1459 MatchEvent (int mode)
1460 {       // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1461         int dummy;
1462         if(matchMode) { // already in match mode: switch it off
1463             abortMatch = TRUE;
1464             if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1465             return;
1466         }
1467 //      if(gameMode != BeginningOfGame) {
1468 //          DisplayError(_("You can only start a match from the initial position."), 0);
1469 //          return;
1470 //      }
1471         abortMatch = FALSE;
1472         if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1473         /* Set up machine vs. machine match */
1474         nextGame = 0;
1475         NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1476         if(appData.tourneyFile[0]) {
1477             ReserveGame(-1, 0);
1478             if(nextGame > appData.matchGames) {
1479                 char buf[MSG_SIZ];
1480                 if(strchr(appData.results, '*') == NULL) {
1481                     FILE *f;
1482                     appData.tourneyCycles++;
1483                     if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1484                         fclose(f);
1485                         NextTourneyGame(-1, &dummy);
1486                         ReserveGame(-1, 0);
1487                         if(nextGame <= appData.matchGames) {
1488                             DisplayNote(_("You restarted an already completed tourney\nOne more cycle will now be added to it\nGames commence in 10 sec"));
1489                             matchMode = mode;
1490                             ScheduleDelayedEvent(NextMatchGame, 10000);
1491                             return;
1492                         }
1493                     }
1494                 }
1495                 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1496                 DisplayError(buf, 0);
1497                 appData.tourneyFile[0] = 0;
1498                 return;
1499             }
1500         } else
1501         if (appData.noChessProgram) {  // [HGM] in tourney engines are loaded automatically
1502             DisplayFatalError(_("Can't have a match with no chess programs"),
1503                               0, 2);
1504             return;
1505         }
1506         matchMode = mode;
1507         matchGame = roundNr = 1;
1508         first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1509         NextMatchGame();
1510 }
1511
1512 char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
1513
1514 void
1515 InitBackEnd3 P((void))
1516 {
1517     GameMode initialMode;
1518     char buf[MSG_SIZ];
1519     int err, len;
1520
1521     InitChessProgram(&first, startedFromSetupPosition);
1522
1523     if(!appData.noChessProgram) {  /* [HGM] tidy: redo program version to use name from myname feature */
1524         free(programVersion);
1525         programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1526         sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1527         FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
1528     }
1529
1530     if (appData.icsActive) {
1531 #ifdef WIN32
1532         /* [DM] Make a console window if needed [HGM] merged ifs */
1533         ConsoleCreate();
1534 #endif
1535         err = establish();
1536         if (err != 0)
1537           {
1538             if (*appData.icsCommPort != NULLCHAR)
1539               len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1540                              appData.icsCommPort);
1541             else
1542               len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1543                         appData.icsHost, appData.icsPort);
1544
1545             if( (len >= MSG_SIZ) && appData.debugMode )
1546               fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1547
1548             DisplayFatalError(buf, err, 1);
1549             return;
1550         }
1551         SetICSMode();
1552         telnetISR =
1553           AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1554         fromUserISR =
1555           AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1556         if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1557             ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1558     } else if (appData.noChessProgram) {
1559         SetNCPMode();
1560     } else {
1561         SetGNUMode();
1562     }
1563
1564     if (*appData.cmailGameName != NULLCHAR) {
1565         SetCmailMode();
1566         OpenLoopback(&cmailPR);
1567         cmailISR =
1568           AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1569     }
1570
1571     ThawUI();
1572     DisplayMessage("", "");
1573     if (StrCaseCmp(appData.initialMode, "") == 0) {
1574       initialMode = BeginningOfGame;
1575       if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1576         gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1577         ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1578         gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1579         ModeHighlight();
1580       }
1581     } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1582       initialMode = TwoMachinesPlay;
1583     } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1584       initialMode = AnalyzeFile;
1585     } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1586       initialMode = AnalyzeMode;
1587     } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1588       initialMode = MachinePlaysWhite;
1589     } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1590       initialMode = MachinePlaysBlack;
1591     } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1592       initialMode = EditGame;
1593     } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1594       initialMode = EditPosition;
1595     } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1596       initialMode = Training;
1597     } else {
1598       len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1599       if( (len >= MSG_SIZ) && appData.debugMode )
1600         fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1601
1602       DisplayFatalError(buf, 0, 2);
1603       return;
1604     }
1605
1606     if (appData.matchMode) {
1607         if(appData.tourneyFile[0]) { // start tourney from command line
1608             FILE *f;
1609             if(f = fopen(appData.tourneyFile, "r")) {
1610                 ParseArgsFromFile(f); // make sure tourney parmeters re known
1611                 fclose(f);
1612                 appData.clockMode = TRUE;
1613                 SetGNUMode();
1614             } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1615         }
1616         MatchEvent(TRUE);
1617     } else if (*appData.cmailGameName != NULLCHAR) {
1618         /* Set up cmail mode */
1619         ReloadCmailMsgEvent(TRUE);
1620     } else {
1621         /* Set up other modes */
1622         if (initialMode == AnalyzeFile) {
1623           if (*appData.loadGameFile == NULLCHAR) {
1624             DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1625             return;
1626           }
1627         }
1628         if (*appData.loadGameFile != NULLCHAR) {
1629             (void) LoadGameFromFile(appData.loadGameFile,
1630                                     appData.loadGameIndex,
1631                                     appData.loadGameFile, TRUE);
1632         } else if (*appData.loadPositionFile != NULLCHAR) {
1633             (void) LoadPositionFromFile(appData.loadPositionFile,
1634                                         appData.loadPositionIndex,
1635                                         appData.loadPositionFile);
1636             /* [HGM] try to make self-starting even after FEN load */
1637             /* to allow automatic setup of fairy variants with wtm */
1638             if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1639                 gameMode = BeginningOfGame;
1640                 setboardSpoiledMachineBlack = 1;
1641             }
1642             /* [HGM] loadPos: make that every new game uses the setup */
1643             /* from file as long as we do not switch variant          */
1644             if(!blackPlaysFirst) {
1645                 startedFromPositionFile = TRUE;
1646                 CopyBoard(filePosition, boards[0]);
1647             }
1648         }
1649         if (initialMode == AnalyzeMode) {
1650           if (appData.noChessProgram) {
1651             DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1652             return;
1653           }
1654           if (appData.icsActive) {
1655             DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1656             return;
1657           }
1658           AnalyzeModeEvent();
1659         } else if (initialMode == AnalyzeFile) {
1660           appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1661           ShowThinkingEvent();
1662           AnalyzeFileEvent();
1663           AnalysisPeriodicEvent(1);
1664         } else if (initialMode == MachinePlaysWhite) {
1665           if (appData.noChessProgram) {
1666             DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1667                               0, 2);
1668             return;
1669           }
1670           if (appData.icsActive) {
1671             DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1672                               0, 2);
1673             return;
1674           }
1675           MachineWhiteEvent();
1676         } else if (initialMode == MachinePlaysBlack) {
1677           if (appData.noChessProgram) {
1678             DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1679                               0, 2);
1680             return;
1681           }
1682           if (appData.icsActive) {
1683             DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1684                               0, 2);
1685             return;
1686           }
1687           MachineBlackEvent();
1688         } else if (initialMode == TwoMachinesPlay) {
1689           if (appData.noChessProgram) {
1690             DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1691                               0, 2);
1692             return;
1693           }
1694           if (appData.icsActive) {
1695             DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1696                               0, 2);
1697             return;
1698           }
1699           TwoMachinesEvent();
1700         } else if (initialMode == EditGame) {
1701           EditGameEvent();
1702         } else if (initialMode == EditPosition) {
1703           EditPositionEvent();
1704         } else if (initialMode == Training) {
1705           if (*appData.loadGameFile == NULLCHAR) {
1706             DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1707             return;
1708           }
1709           TrainingEvent();
1710         }
1711     }
1712 }
1713
1714 void
1715 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1716 {
1717     DisplayBook(current+1);
1718
1719     MoveHistorySet( movelist, first, last, current, pvInfoList );
1720
1721     EvalGraphSet( first, last, current, pvInfoList );
1722
1723     MakeEngineOutputTitle();
1724 }
1725
1726 /*
1727  * Establish will establish a contact to a remote host.port.
1728  * Sets icsPR to a ProcRef for a process (or pseudo-process)
1729  *  used to talk to the host.
1730  * Returns 0 if okay, error code if not.
1731  */
1732 int
1733 establish ()
1734 {
1735     char buf[MSG_SIZ];
1736
1737     if (*appData.icsCommPort != NULLCHAR) {
1738         /* Talk to the host through a serial comm port */
1739         return OpenCommPort(appData.icsCommPort, &icsPR);
1740
1741     } else if (*appData.gateway != NULLCHAR) {
1742         if (*appData.remoteShell == NULLCHAR) {
1743             /* Use the rcmd protocol to run telnet program on a gateway host */
1744             snprintf(buf, sizeof(buf), "%s %s %s",
1745                     appData.telnetProgram, appData.icsHost, appData.icsPort);
1746             return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1747
1748         } else {
1749             /* Use the rsh program to run telnet program on a gateway host */
1750             if (*appData.remoteUser == NULLCHAR) {
1751                 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1752                         appData.gateway, appData.telnetProgram,
1753                         appData.icsHost, appData.icsPort);
1754             } else {
1755                 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1756                         appData.remoteShell, appData.gateway,
1757                         appData.remoteUser, appData.telnetProgram,
1758                         appData.icsHost, appData.icsPort);
1759             }
1760             return StartChildProcess(buf, "", &icsPR);
1761
1762         }
1763     } else if (appData.useTelnet) {
1764         return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1765
1766     } else {
1767         /* TCP socket interface differs somewhat between
1768            Unix and NT; handle details in the front end.
1769            */
1770         return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1771     }
1772 }
1773
1774 void
1775 EscapeExpand (char *p, char *q)
1776 {       // [HGM] initstring: routine to shape up string arguments
1777         while(*p++ = *q++) if(p[-1] == '\\')
1778             switch(*q++) {
1779                 case 'n': p[-1] = '\n'; break;
1780                 case 'r': p[-1] = '\r'; break;
1781                 case 't': p[-1] = '\t'; break;
1782                 case '\\': p[-1] = '\\'; break;
1783                 case 0: *p = 0; return;
1784                 default: p[-1] = q[-1]; break;
1785             }
1786 }
1787
1788 void
1789 show_bytes (FILE *fp, char *buf, int count)
1790 {
1791     while (count--) {
1792         if (*buf < 040 || *(unsigned char *) buf > 0177) {
1793             fprintf(fp, "\\%03o", *buf & 0xff);
1794         } else {
1795             putc(*buf, fp);
1796         }
1797         buf++;
1798     }
1799     fflush(fp);
1800 }
1801
1802 /* Returns an errno value */
1803 int
1804 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1805 {
1806     char buf[8192], *p, *q, *buflim;
1807     int left, newcount, outcount;
1808
1809     if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1810         *appData.gateway != NULLCHAR) {
1811         if (appData.debugMode) {
1812             fprintf(debugFP, ">ICS: ");
1813             show_bytes(debugFP, message, count);
1814             fprintf(debugFP, "\n");
1815         }
1816         return OutputToProcess(pr, message, count, outError);
1817     }
1818
1819     buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1820     p = message;
1821     q = buf;
1822     left = count;
1823     newcount = 0;
1824     while (left) {
1825         if (q >= buflim) {
1826             if (appData.debugMode) {
1827                 fprintf(debugFP, ">ICS: ");
1828                 show_bytes(debugFP, buf, newcount);
1829                 fprintf(debugFP, "\n");
1830             }
1831             outcount = OutputToProcess(pr, buf, newcount, outError);
1832             if (outcount < newcount) return -1; /* to be sure */
1833             q = buf;
1834             newcount = 0;
1835         }
1836         if (*p == '\n') {
1837             *q++ = '\r';
1838             newcount++;
1839         } else if (((unsigned char) *p) == TN_IAC) {
1840             *q++ = (char) TN_IAC;
1841             newcount ++;
1842         }
1843         *q++ = *p++;
1844         newcount++;
1845         left--;
1846     }
1847     if (appData.debugMode) {
1848         fprintf(debugFP, ">ICS: ");
1849         show_bytes(debugFP, buf, newcount);
1850         fprintf(debugFP, "\n");
1851     }
1852     outcount = OutputToProcess(pr, buf, newcount, outError);
1853     if (outcount < newcount) return -1; /* to be sure */
1854     return count;
1855 }
1856
1857 void
1858 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1859 {
1860     int outError, outCount;
1861     static int gotEof = 0;
1862     static FILE *ini;
1863
1864     /* Pass data read from player on to ICS */
1865     if (count > 0) {
1866         gotEof = 0;
1867         outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1868         if (outCount < count) {
1869             DisplayFatalError(_("Error writing to ICS"), outError, 1);
1870         }
1871         if(have_sent_ICS_logon == 2) {
1872           if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
1873             fprintf(ini, "%s", message);
1874             have_sent_ICS_logon = 3;
1875           } else
1876             have_sent_ICS_logon = 1;
1877         } else if(have_sent_ICS_logon == 3) {
1878             fprintf(ini, "%s", message);
1879             fclose(ini);
1880           have_sent_ICS_logon = 1;
1881         }
1882     } else if (count < 0) {
1883         RemoveInputSource(isr);
1884         DisplayFatalError(_("Error reading from keyboard"), error, 1);
1885     } else if (gotEof++ > 0) {
1886         RemoveInputSource(isr);
1887         DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1888     }
1889 }
1890
1891 void
1892 KeepAlive ()
1893 {   // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1894     if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1895     connectionAlive = FALSE; // only sticks if no response to 'date' command.
1896     SendToICS("date\n");
1897     if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1898 }
1899
1900 /* added routine for printf style output to ics */
1901 void
1902 ics_printf (char *format, ...)
1903 {
1904     char buffer[MSG_SIZ];
1905     va_list args;
1906
1907     va_start(args, format);
1908     vsnprintf(buffer, sizeof(buffer), format, args);
1909     buffer[sizeof(buffer)-1] = '\0';
1910     SendToICS(buffer);
1911     va_end(args);
1912 }
1913
1914 void
1915 SendToICS (char *s)
1916 {
1917     int count, outCount, outError;
1918
1919     if (icsPR == NoProc) return;
1920
1921     count = strlen(s);
1922     outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1923     if (outCount < count) {
1924         DisplayFatalError(_("Error writing to ICS"), outError, 1);
1925     }
1926 }
1927
1928 /* This is used for sending logon scripts to the ICS. Sending
1929    without a delay causes problems when using timestamp on ICC
1930    (at least on my machine). */
1931 void
1932 SendToICSDelayed (char *s, long msdelay)
1933 {
1934     int count, outCount, outError;
1935
1936     if (icsPR == NoProc) return;
1937
1938     count = strlen(s);
1939     if (appData.debugMode) {
1940         fprintf(debugFP, ">ICS: ");
1941         show_bytes(debugFP, s, count);
1942         fprintf(debugFP, "\n");
1943     }
1944     outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1945                                       msdelay);
1946     if (outCount < count) {
1947         DisplayFatalError(_("Error writing to ICS"), outError, 1);
1948     }
1949 }
1950
1951
1952 /* Remove all highlighting escape sequences in s
1953    Also deletes any suffix starting with '('
1954    */
1955 char *
1956 StripHighlightAndTitle (char *s)
1957 {
1958     static char retbuf[MSG_SIZ];
1959     char *p = retbuf;
1960
1961     while (*s != NULLCHAR) {
1962         while (*s == '\033') {
1963             while (*s != NULLCHAR && !isalpha(*s)) s++;
1964             if (*s != NULLCHAR) s++;
1965         }
1966         while (*s != NULLCHAR && *s != '\033') {
1967             if (*s == '(' || *s == '[') {
1968                 *p = NULLCHAR;
1969                 return retbuf;
1970             }
1971             *p++ = *s++;
1972         }
1973     }
1974     *p = NULLCHAR;
1975     return retbuf;
1976 }
1977
1978 /* Remove all highlighting escape sequences in s */
1979 char *
1980 StripHighlight (char *s)
1981 {
1982     static char retbuf[MSG_SIZ];
1983     char *p = retbuf;
1984
1985     while (*s != NULLCHAR) {
1986         while (*s == '\033') {
1987             while (*s != NULLCHAR && !isalpha(*s)) s++;
1988             if (*s != NULLCHAR) s++;
1989         }
1990         while (*s != NULLCHAR && *s != '\033') {
1991             *p++ = *s++;
1992         }
1993     }
1994     *p = NULLCHAR;
1995     return retbuf;
1996 }
1997
1998 char *variantNames[] = VARIANT_NAMES;
1999 char *
2000 VariantName (VariantClass v)
2001 {
2002     return variantNames[v];
2003 }
2004
2005
2006 /* Identify a variant from the strings the chess servers use or the
2007    PGN Variant tag names we use. */
2008 VariantClass
2009 StringToVariant (char *e)
2010 {
2011     char *p;
2012     int wnum = -1;
2013     VariantClass v = VariantNormal;
2014     int i, found = FALSE;
2015     char buf[MSG_SIZ];
2016     int len;
2017
2018     if (!e) return v;
2019
2020     /* [HGM] skip over optional board-size prefixes */
2021     if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
2022         sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
2023         while( *e++ != '_');
2024     }
2025
2026     if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2027         v = VariantNormal;
2028         found = TRUE;
2029     } else
2030     for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2031       if (StrCaseStr(e, variantNames[i])) {
2032         v = (VariantClass) i;
2033         found = TRUE;
2034         break;
2035       }
2036     }
2037
2038     if (!found) {
2039       if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2040           || StrCaseStr(e, "wild/fr")
2041           || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2042         v = VariantFischeRandom;
2043       } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2044                  (i = 1, p = StrCaseStr(e, "w"))) {
2045         p += i;
2046         while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2047         if (isdigit(*p)) {
2048           wnum = atoi(p);
2049         } else {
2050           wnum = -1;
2051         }
2052         switch (wnum) {
2053         case 0: /* FICS only, actually */
2054         case 1:
2055           /* Castling legal even if K starts on d-file */
2056           v = VariantWildCastle;
2057           break;
2058         case 2:
2059         case 3:
2060         case 4:
2061           /* Castling illegal even if K & R happen to start in
2062              normal positions. */
2063           v = VariantNoCastle;
2064           break;
2065         case 5:
2066         case 7:
2067         case 8:
2068         case 10:
2069         case 11:
2070         case 12:
2071         case 13:
2072         case 14:
2073         case 15:
2074         case 18:
2075         case 19:
2076           /* Castling legal iff K & R start in normal positions */
2077           v = VariantNormal;
2078           break;
2079         case 6:
2080         case 20:
2081         case 21:
2082           /* Special wilds for position setup; unclear what to do here */
2083           v = VariantLoadable;
2084           break;
2085         case 9:
2086           /* Bizarre ICC game */
2087           v = VariantTwoKings;
2088           break;
2089         case 16:
2090           v = VariantKriegspiel;
2091           break;
2092         case 17:
2093           v = VariantLosers;
2094           break;
2095         case 22:
2096           v = VariantFischeRandom;
2097           break;
2098         case 23:
2099           v = VariantCrazyhouse;
2100           break;
2101         case 24:
2102           v = VariantBughouse;
2103           break;
2104         case 25:
2105           v = Variant3Check;
2106           break;
2107         case 26:
2108           /* Not quite the same as FICS suicide! */
2109           v = VariantGiveaway;
2110           break;
2111         case 27:
2112           v = VariantAtomic;
2113           break;
2114         case 28:
2115           v = VariantShatranj;
2116           break;
2117
2118         /* Temporary names for future ICC types.  The name *will* change in
2119            the next xboard/WinBoard release after ICC defines it. */
2120         case 29:
2121           v = Variant29;
2122           break;
2123         case 30:
2124           v = Variant30;
2125           break;
2126         case 31:
2127           v = Variant31;
2128           break;
2129         case 32:
2130           v = Variant32;
2131           break;
2132         case 33:
2133           v = Variant33;
2134           break;
2135         case 34:
2136           v = Variant34;
2137           break;
2138         case 35:
2139           v = Variant35;
2140           break;
2141         case 36:
2142           v = Variant36;
2143           break;
2144         case 37:
2145           v = VariantShogi;
2146           break;
2147         case 38:
2148           v = VariantXiangqi;
2149           break;
2150         case 39:
2151           v = VariantCourier;
2152           break;
2153         case 40:
2154           v = VariantGothic;
2155           break;
2156         case 41:
2157           v = VariantCapablanca;
2158           break;
2159         case 42:
2160           v = VariantKnightmate;
2161           break;
2162         case 43:
2163           v = VariantFairy;
2164           break;
2165         case 44:
2166           v = VariantCylinder;
2167           break;
2168         case 45:
2169           v = VariantFalcon;
2170           break;
2171         case 46:
2172           v = VariantCapaRandom;
2173           break;
2174         case 47:
2175           v = VariantBerolina;
2176           break;
2177         case 48:
2178           v = VariantJanus;
2179           break;
2180         case 49:
2181           v = VariantSuper;
2182           break;
2183         case 50:
2184           v = VariantGreat;
2185           break;
2186         case -1:
2187           /* Found "wild" or "w" in the string but no number;
2188              must assume it's normal chess. */
2189           v = VariantNormal;
2190           break;
2191         default:
2192           len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2193           if( (len >= MSG_SIZ) && appData.debugMode )
2194             fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2195
2196           DisplayError(buf, 0);
2197           v = VariantUnknown;
2198           break;
2199         }
2200       }
2201     }
2202     if (appData.debugMode) {
2203       fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
2204               e, wnum, VariantName(v));
2205     }
2206     return v;
2207 }
2208
2209 static int leftover_start = 0, leftover_len = 0;
2210 char star_match[STAR_MATCH_N][MSG_SIZ];
2211
2212 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2213    advance *index beyond it, and set leftover_start to the new value of
2214    *index; else return FALSE.  If pattern contains the character '*', it
2215    matches any sequence of characters not containing '\r', '\n', or the
2216    character following the '*' (if any), and the matched sequence(s) are
2217    copied into star_match.
2218    */
2219 int
2220 looking_at ( char *buf, int *index, char *pattern)
2221 {
2222     char *bufp = &buf[*index], *patternp = pattern;
2223     int star_count = 0;
2224     char *matchp = star_match[0];
2225
2226     for (;;) {
2227         if (*patternp == NULLCHAR) {
2228             *index = leftover_start = bufp - buf;
2229             *matchp = NULLCHAR;
2230             return TRUE;
2231         }
2232         if (*bufp == NULLCHAR) return FALSE;
2233         if (*patternp == '*') {
2234             if (*bufp == *(patternp + 1)) {
2235                 *matchp = NULLCHAR;
2236                 matchp = star_match[++star_count];
2237                 patternp += 2;
2238                 bufp++;
2239                 continue;
2240             } else if (*bufp == '\n' || *bufp == '\r') {
2241                 patternp++;
2242                 if (*patternp == NULLCHAR)
2243                   continue;
2244                 else
2245                   return FALSE;
2246             } else {
2247                 *matchp++ = *bufp++;
2248                 continue;
2249             }
2250         }
2251         if (*patternp != *bufp) return FALSE;
2252         patternp++;
2253         bufp++;
2254     }
2255 }
2256
2257 void
2258 SendToPlayer (char *data, int length)
2259 {
2260     int error, outCount;
2261     outCount = OutputToProcess(NoProc, data, length, &error);
2262     if (outCount < length) {
2263         DisplayFatalError(_("Error writing to display"), error, 1);
2264     }
2265 }
2266
2267 void
2268 PackHolding (char packed[], char *holding)
2269 {
2270     char *p = holding;
2271     char *q = packed;
2272     int runlength = 0;
2273     int curr = 9999;
2274     do {
2275         if (*p == curr) {
2276             runlength++;
2277         } else {
2278             switch (runlength) {
2279               case 0:
2280                 break;
2281               case 1:
2282                 *q++ = curr;
2283                 break;
2284               case 2:
2285                 *q++ = curr;
2286                 *q++ = curr;
2287                 break;
2288               default:
2289                 sprintf(q, "%d", runlength);
2290                 while (*q) q++;
2291                 *q++ = curr;
2292                 break;
2293             }
2294             runlength = 1;
2295             curr = *p;
2296         }
2297     } while (*p++);
2298     *q = NULLCHAR;
2299 }
2300
2301 /* Telnet protocol requests from the front end */
2302 void
2303 TelnetRequest (unsigned char ddww, unsigned char option)
2304 {
2305     unsigned char msg[3];
2306     int outCount, outError;
2307
2308     if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2309
2310     if (appData.debugMode) {
2311         char buf1[8], buf2[8], *ddwwStr, *optionStr;
2312         switch (ddww) {
2313           case TN_DO:
2314             ddwwStr = "DO";
2315             break;
2316           case TN_DONT:
2317             ddwwStr = "DONT";
2318             break;
2319           case TN_WILL:
2320             ddwwStr = "WILL";
2321             break;
2322           case TN_WONT:
2323             ddwwStr = "WONT";
2324             break;
2325           default:
2326             ddwwStr = buf1;
2327             snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2328             break;
2329         }
2330         switch (option) {
2331           case TN_ECHO:
2332             optionStr = "ECHO";
2333             break;
2334           default:
2335             optionStr = buf2;
2336             snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2337             break;
2338         }
2339         fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2340     }
2341     msg[0] = TN_IAC;
2342     msg[1] = ddww;
2343     msg[2] = option;
2344     outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2345     if (outCount < 3) {
2346         DisplayFatalError(_("Error writing to ICS"), outError, 1);
2347     }
2348 }
2349
2350 void
2351 DoEcho ()
2352 {
2353     if (!appData.icsActive) return;
2354     TelnetRequest(TN_DO, TN_ECHO);
2355 }
2356
2357 void
2358 DontEcho ()
2359 {
2360     if (!appData.icsActive) return;
2361     TelnetRequest(TN_DONT, TN_ECHO);
2362 }
2363
2364 void
2365 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2366 {
2367     /* put the holdings sent to us by the server on the board holdings area */
2368     int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2369     char p;
2370     ChessSquare piece;
2371
2372     if(gameInfo.holdingsWidth < 2)  return;
2373     if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2374         return; // prevent overwriting by pre-board holdings
2375
2376     if( (int)lowestPiece >= BlackPawn ) {
2377         holdingsColumn = 0;
2378         countsColumn = 1;
2379         holdingsStartRow = BOARD_HEIGHT-1;
2380         direction = -1;
2381     } else {
2382         holdingsColumn = BOARD_WIDTH-1;
2383         countsColumn = BOARD_WIDTH-2;
2384         holdingsStartRow = 0;
2385         direction = 1;
2386     }
2387
2388     for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2389         board[i][holdingsColumn] = EmptySquare;
2390         board[i][countsColumn]   = (ChessSquare) 0;
2391     }
2392     while( (p=*holdings++) != NULLCHAR ) {
2393         piece = CharToPiece( ToUpper(p) );
2394         if(piece == EmptySquare) continue;
2395         /*j = (int) piece - (int) WhitePawn;*/
2396         j = PieceToNumber(piece);
2397         if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2398         if(j < 0) continue;               /* should not happen */
2399         piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2400         board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2401         board[holdingsStartRow+j*direction][countsColumn]++;
2402     }
2403 }
2404
2405
2406 void
2407 VariantSwitch (Board board, VariantClass newVariant)
2408 {
2409    int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2410    static Board oldBoard;
2411
2412    startedFromPositionFile = FALSE;
2413    if(gameInfo.variant == newVariant) return;
2414
2415    /* [HGM] This routine is called each time an assignment is made to
2416     * gameInfo.variant during a game, to make sure the board sizes
2417     * are set to match the new variant. If that means adding or deleting
2418     * holdings, we shift the playing board accordingly
2419     * This kludge is needed because in ICS observe mode, we get boards
2420     * of an ongoing game without knowing the variant, and learn about the
2421     * latter only later. This can be because of the move list we requested,
2422     * in which case the game history is refilled from the beginning anyway,
2423     * but also when receiving holdings of a crazyhouse game. In the latter
2424     * case we want to add those holdings to the already received position.
2425     */
2426
2427
2428    if (appData.debugMode) {
2429      fprintf(debugFP, "Switch board from %s to %s\n",
2430              VariantName(gameInfo.variant), VariantName(newVariant));
2431      setbuf(debugFP, NULL);
2432    }
2433    shuffleOpenings = 0;       /* [HGM] shuffle */
2434    gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2435    switch(newVariant)
2436      {
2437      case VariantShogi:
2438        newWidth = 9;  newHeight = 9;
2439        gameInfo.holdingsSize = 7;
2440      case VariantBughouse:
2441      case VariantCrazyhouse:
2442        newHoldingsWidth = 2; break;
2443      case VariantGreat:
2444        newWidth = 10;
2445      case VariantSuper:
2446        newHoldingsWidth = 2;
2447        gameInfo.holdingsSize = 8;
2448        break;
2449      case VariantGothic:
2450      case VariantCapablanca:
2451      case VariantCapaRandom:
2452        newWidth = 10;
2453      default:
2454        newHoldingsWidth = gameInfo.holdingsSize = 0;
2455      };
2456
2457    if(newWidth  != gameInfo.boardWidth  ||
2458       newHeight != gameInfo.boardHeight ||
2459       newHoldingsWidth != gameInfo.holdingsWidth ) {
2460
2461      /* shift position to new playing area, if needed */
2462      if(newHoldingsWidth > gameInfo.holdingsWidth) {
2463        for(i=0; i<BOARD_HEIGHT; i++)
2464          for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2465            board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2466              board[i][j];
2467        for(i=0; i<newHeight; i++) {
2468          board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2469          board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2470        }
2471      } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2472        for(i=0; i<BOARD_HEIGHT; i++)
2473          for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2474            board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2475              board[i][j];
2476      }
2477      board[HOLDINGS_SET] = 0;
2478      gameInfo.boardWidth  = newWidth;
2479      gameInfo.boardHeight = newHeight;
2480      gameInfo.holdingsWidth = newHoldingsWidth;
2481      gameInfo.variant = newVariant;
2482      InitDrawingSizes(-2, 0);
2483    } else gameInfo.variant = newVariant;
2484    CopyBoard(oldBoard, board);   // remember correctly formatted board
2485      InitPosition(FALSE);          /* this sets up board[0], but also other stuff        */
2486    DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2487 }
2488
2489 static int loggedOn = FALSE;
2490
2491 /*-- Game start info cache: --*/
2492 int gs_gamenum;
2493 char gs_kind[MSG_SIZ];
2494 static char player1Name[128] = "";
2495 static char player2Name[128] = "";
2496 static char cont_seq[] = "\n\\   ";
2497 static int player1Rating = -1;
2498 static int player2Rating = -1;
2499 /*----------------------------*/
2500
2501 ColorClass curColor = ColorNormal;
2502 int suppressKibitz = 0;
2503
2504 // [HGM] seekgraph
2505 Boolean soughtPending = FALSE;
2506 Boolean seekGraphUp;
2507 #define MAX_SEEK_ADS 200
2508 #define SQUARE 0x80
2509 char *seekAdList[MAX_SEEK_ADS];
2510 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2511 float tcList[MAX_SEEK_ADS];
2512 char colorList[MAX_SEEK_ADS];
2513 int nrOfSeekAds = 0;
2514 int minRating = 1010, maxRating = 2800;
2515 int hMargin = 10, vMargin = 20, h, w;
2516 extern int squareSize, lineGap;
2517
2518 void
2519 PlotSeekAd (int i)
2520 {
2521         int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2522         xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2523         if(r < minRating+100 && r >=0 ) r = minRating+100;
2524         if(r > maxRating) r = maxRating;
2525         if(tc < 1.f) tc = 1.f;
2526         if(tc > 95.f) tc = 95.f;
2527         x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2528         y = ((double)r - minRating)/(maxRating - minRating)
2529             * (h-vMargin-squareSize/8-1) + vMargin;
2530         if(ratingList[i] < 0) y = vMargin + squareSize/4;
2531         if(strstr(seekAdList[i], " u ")) color = 1;
2532         if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2533            !strstr(seekAdList[i], "bullet") &&
2534            !strstr(seekAdList[i], "blitz") &&
2535            !strstr(seekAdList[i], "standard") ) color = 2;
2536         if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2537         DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2538 }
2539
2540 void
2541 PlotSingleSeekAd (int i)
2542 {
2543         PlotSeekAd(i);
2544 }
2545
2546 void
2547 AddAd (char *handle, char *rating, int base, int inc,  char rated, char *type, int nr, Boolean plot)
2548 {
2549         char buf[MSG_SIZ], *ext = "";
2550         VariantClass v = StringToVariant(type);
2551         if(strstr(type, "wild")) {
2552             ext = type + 4; // append wild number
2553             if(v == VariantFischeRandom) type = "chess960"; else
2554             if(v == VariantLoadable) type = "setup"; else
2555             type = VariantName(v);
2556         }
2557         snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2558         if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2559             if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2560             ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2561             sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2562             tcList[nrOfSeekAds] = base + (2./3.)*inc;
2563             seekNrList[nrOfSeekAds] = nr;
2564             zList[nrOfSeekAds] = 0;
2565             seekAdList[nrOfSeekAds++] = StrSave(buf);
2566             if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
2567         }
2568 }
2569
2570 void
2571 EraseSeekDot (int i)
2572 {
2573     int x = xList[i], y = yList[i], d=squareSize/4, k;
2574     DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2575     if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2576     // now replot every dot that overlapped
2577     for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2578         int xx = xList[k], yy = yList[k];
2579         if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2580             DrawSeekDot(xx, yy, colorList[k]);
2581     }
2582 }
2583
2584 void
2585 RemoveSeekAd (int nr)
2586 {
2587         int i;
2588         for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2589             EraseSeekDot(i);
2590             if(seekAdList[i]) free(seekAdList[i]);
2591             seekAdList[i] = seekAdList[--nrOfSeekAds];
2592             seekNrList[i] = seekNrList[nrOfSeekAds];
2593             ratingList[i] = ratingList[nrOfSeekAds];
2594             colorList[i]  = colorList[nrOfSeekAds];
2595             tcList[i] = tcList[nrOfSeekAds];
2596             xList[i]  = xList[nrOfSeekAds];
2597             yList[i]  = yList[nrOfSeekAds];
2598             zList[i]  = zList[nrOfSeekAds];
2599             seekAdList[nrOfSeekAds] = NULL;
2600             break;
2601         }
2602 }
2603
2604 Boolean
2605 MatchSoughtLine (char *line)
2606 {
2607     char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2608     int nr, base, inc, u=0; char dummy;
2609
2610     if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2611        sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2612        (u=1) &&
2613        (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2614         sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7)  ) {
2615         // match: compact and save the line
2616         AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2617         return TRUE;
2618     }
2619     return FALSE;
2620 }
2621
2622 int
2623 DrawSeekGraph ()
2624 {
2625     int i;
2626     if(!seekGraphUp) return FALSE;
2627     h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2628     w = BOARD_WIDTH  * (squareSize + lineGap) + lineGap;
2629
2630     DrawSeekBackground(0, 0, w, h);
2631     DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2632     DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2633     for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2634         int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2635         yy = h-1-yy;
2636         DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
2637         if(i%500 == 0) {
2638             char buf[MSG_SIZ];
2639             snprintf(buf, MSG_SIZ, "%d", i);
2640             DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2641         }
2642     }
2643     DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2644     for(i=1; i<100; i+=(i<10?1:5)) {
2645         int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2646         DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2647         if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2648             char buf[MSG_SIZ];
2649             snprintf(buf, MSG_SIZ, "%d", i);
2650             DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2651         }
2652     }
2653     for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2654     return TRUE;
2655 }
2656
2657 int
2658 SeekGraphClick (ClickType click, int x, int y, int moving)
2659 {
2660     static int lastDown = 0, displayed = 0, lastSecond;
2661     if(y < 0) return FALSE;
2662     if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2663         (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2664         if(!seekGraphUp) return FALSE;
2665         seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2666         DrawPosition(TRUE, NULL);
2667         return TRUE;
2668     }
2669     if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2670         if(click == Release || moving) return FALSE;
2671         nrOfSeekAds = 0;
2672         soughtPending = TRUE;
2673         SendToICS(ics_prefix);
2674         SendToICS("sought\n"); // should this be "sought all"?
2675     } else { // issue challenge based on clicked ad
2676         int dist = 10000; int i, closest = 0, second = 0;
2677         for(i=0; i<nrOfSeekAds; i++) {
2678             int d = (x-xList[i])*(x-xList[i]) +  (y-yList[i])*(y-yList[i]) + zList[i];
2679             if(d < dist) { dist = d; closest = i; }
2680             second += (d - zList[i] < 120); // count in-range ads
2681             if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2682         }
2683         if(dist < 120) {
2684             char buf[MSG_SIZ];
2685             second = (second > 1);
2686             if(displayed != closest || second != lastSecond) {
2687                 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2688                 lastSecond = second; displayed = closest;
2689             }
2690             if(click == Press) {
2691                 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2692                 lastDown = closest;
2693                 return TRUE;
2694             } // on press 'hit', only show info
2695             if(moving == 2) return TRUE; // ignore right up-clicks on dot
2696             snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2697             SendToICS(ics_prefix);
2698             SendToICS(buf);
2699             return TRUE; // let incoming board of started game pop down the graph
2700         } else if(click == Release) { // release 'miss' is ignored
2701             zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2702             if(moving == 2) { // right up-click
2703                 nrOfSeekAds = 0; // refresh graph
2704                 soughtPending = TRUE;
2705                 SendToICS(ics_prefix);
2706                 SendToICS("sought\n"); // should this be "sought all"?
2707             }
2708             return TRUE;
2709         } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2710         // press miss or release hit 'pop down' seek graph
2711         seekGraphUp = FALSE;
2712         DrawPosition(TRUE, NULL);
2713     }
2714     return TRUE;
2715 }
2716
2717 void
2718 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2719 {
2720 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2721 #define STARTED_NONE 0
2722 #define STARTED_MOVES 1
2723 #define STARTED_BOARD 2
2724 #define STARTED_OBSERVE 3
2725 #define STARTED_HOLDINGS 4
2726 #define STARTED_CHATTER 5
2727 #define STARTED_COMMENT 6
2728 #define STARTED_MOVES_NOHIDE 7
2729
2730     static int started = STARTED_NONE;
2731     static char parse[20000];
2732     static int parse_pos = 0;
2733     static char buf[BUF_SIZE + 1];
2734     static int firstTime = TRUE, intfSet = FALSE;
2735     static ColorClass prevColor = ColorNormal;
2736     static int savingComment = FALSE;
2737     static int cmatch = 0; // continuation sequence match
2738     char *bp;
2739     char str[MSG_SIZ];
2740     int i, oldi;
2741     int buf_len;
2742     int next_out;
2743     int tkind;
2744     int backup;    /* [DM] For zippy color lines */
2745     char *p;
2746     char talker[MSG_SIZ]; // [HGM] chat
2747     int channel;
2748
2749     connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2750
2751     if (appData.debugMode) {
2752       if (!error) {
2753         fprintf(debugFP, "<ICS: ");
2754         show_bytes(debugFP, data, count);
2755         fprintf(debugFP, "\n");
2756       }
2757     }
2758
2759     if (appData.debugMode) { int f = forwardMostMove;
2760         fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2761                 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2762                 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2763     }
2764     if (count > 0) {
2765         /* If last read ended with a partial line that we couldn't parse,
2766            prepend it to the new read and try again. */
2767         if (leftover_len > 0) {
2768             for (i=0; i<leftover_len; i++)
2769               buf[i] = buf[leftover_start + i];
2770         }
2771
2772     /* copy new characters into the buffer */
2773     bp = buf + leftover_len;
2774     buf_len=leftover_len;
2775     for (i=0; i<count; i++)
2776     {
2777         // ignore these
2778         if (data[i] == '\r')
2779             continue;
2780
2781         // join lines split by ICS?
2782         if (!appData.noJoin)
2783         {
2784             /*
2785                 Joining just consists of finding matches against the
2786                 continuation sequence, and discarding that sequence
2787                 if found instead of copying it.  So, until a match
2788                 fails, there's nothing to do since it might be the
2789                 complete sequence, and thus, something we don't want
2790                 copied.
2791             */
2792             if (data[i] == cont_seq[cmatch])
2793             {
2794                 cmatch++;
2795                 if (cmatch == strlen(cont_seq))
2796                 {
2797                     cmatch = 0; // complete match.  just reset the counter
2798
2799                     /*
2800                         it's possible for the ICS to not include the space
2801                         at the end of the last word, making our [correct]
2802                         join operation fuse two separate words.  the server
2803                         does this when the space occurs at the width setting.
2804                     */
2805                     if (!buf_len || buf[buf_len-1] != ' ')
2806                     {
2807                         *bp++ = ' ';
2808                         buf_len++;
2809                     }
2810                 }
2811                 continue;
2812             }
2813             else if (cmatch)
2814             {
2815                 /*
2816                     match failed, so we have to copy what matched before
2817                     falling through and copying this character.  In reality,
2818                     this will only ever be just the newline character, but
2819                     it doesn't hurt to be precise.
2820                 */
2821                 strncpy(bp, cont_seq, cmatch);
2822                 bp += cmatch;
2823                 buf_len += cmatch;
2824                 cmatch = 0;
2825             }
2826         }
2827
2828         // copy this char
2829         *bp++ = data[i];
2830         buf_len++;
2831     }
2832
2833         buf[buf_len] = NULLCHAR;
2834 //      next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2835         next_out = 0;
2836         leftover_start = 0;
2837
2838         i = 0;
2839         while (i < buf_len) {
2840             /* Deal with part of the TELNET option negotiation
2841                protocol.  We refuse to do anything beyond the
2842                defaults, except that we allow the WILL ECHO option,
2843                which ICS uses to turn off password echoing when we are
2844                directly connected to it.  We reject this option
2845                if localLineEditing mode is on (always on in xboard)
2846                and we are talking to port 23, which might be a real
2847                telnet server that will try to keep WILL ECHO on permanently.
2848              */
2849             if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2850                 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2851                 unsigned char option;
2852                 oldi = i;
2853                 switch ((unsigned char) buf[++i]) {
2854                   case TN_WILL:
2855                     if (appData.debugMode)
2856                       fprintf(debugFP, "\n<WILL ");
2857                     switch (option = (unsigned char) buf[++i]) {
2858                       case TN_ECHO:
2859                         if (appData.debugMode)
2860                           fprintf(debugFP, "ECHO ");
2861                         /* Reply only if this is a change, according
2862                            to the protocol rules. */
2863                         if (remoteEchoOption) break;
2864                         if (appData.localLineEditing &&
2865                             atoi(appData.icsPort) == TN_PORT) {
2866                             TelnetRequest(TN_DONT, TN_ECHO);
2867                         } else {
2868                             EchoOff();
2869                             TelnetRequest(TN_DO, TN_ECHO);
2870                             remoteEchoOption = TRUE;
2871                         }
2872                         break;
2873                       default:
2874                         if (appData.debugMode)
2875                           fprintf(debugFP, "%d ", option);
2876                         /* Whatever this is, we don't want it. */
2877                         TelnetRequest(TN_DONT, option);
2878                         break;
2879                     }
2880                     break;
2881                   case TN_WONT:
2882                     if (appData.debugMode)
2883                       fprintf(debugFP, "\n<WONT ");
2884                     switch (option = (unsigned char) buf[++i]) {
2885                       case TN_ECHO:
2886                         if (appData.debugMode)
2887                           fprintf(debugFP, "ECHO ");
2888                         /* Reply only if this is a change, according
2889                            to the protocol rules. */
2890                         if (!remoteEchoOption) break;
2891                         EchoOn();
2892                         TelnetRequest(TN_DONT, TN_ECHO);
2893                         remoteEchoOption = FALSE;
2894                         break;
2895                       default:
2896                         if (appData.debugMode)
2897                           fprintf(debugFP, "%d ", (unsigned char) option);
2898                         /* Whatever this is, it must already be turned
2899                            off, because we never agree to turn on
2900                            anything non-default, so according to the
2901                            protocol rules, we don't reply. */
2902                         break;
2903                     }
2904                     break;
2905                   case TN_DO:
2906                     if (appData.debugMode)
2907                       fprintf(debugFP, "\n<DO ");
2908                     switch (option = (unsigned char) buf[++i]) {
2909                       default:
2910                         /* Whatever this is, we refuse to do it. */
2911                         if (appData.debugMode)
2912                           fprintf(debugFP, "%d ", option);
2913                         TelnetRequest(TN_WONT, option);
2914                         break;
2915                     }
2916                     break;
2917                   case TN_DONT:
2918                     if (appData.debugMode)
2919                       fprintf(debugFP, "\n<DONT ");
2920                     switch (option = (unsigned char) buf[++i]) {
2921                       default:
2922                         if (appData.debugMode)
2923                           fprintf(debugFP, "%d ", option);
2924                         /* Whatever this is, we are already not doing
2925                            it, because we never agree to do anything
2926                            non-default, so according to the protocol
2927                            rules, we don't reply. */
2928                         break;
2929                     }
2930                     break;
2931                   case TN_IAC:
2932                     if (appData.debugMode)
2933                       fprintf(debugFP, "\n<IAC ");
2934                     /* Doubled IAC; pass it through */
2935                     i--;
2936                     break;
2937                   default:
2938                     if (appData.debugMode)
2939                       fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2940                     /* Drop all other telnet commands on the floor */
2941                     break;
2942                 }
2943                 if (oldi > next_out)
2944                   SendToPlayer(&buf[next_out], oldi - next_out);
2945                 if (++i > next_out)
2946                   next_out = i;
2947                 continue;
2948             }
2949
2950             /* OK, this at least will *usually* work */
2951             if (!loggedOn && looking_at(buf, &i, "ics%")) {
2952                 loggedOn = TRUE;
2953             }
2954
2955             if (loggedOn && !intfSet) {
2956                 if (ics_type == ICS_ICC) {
2957                   snprintf(str, MSG_SIZ,
2958                           "/set-quietly interface %s\n/set-quietly style 12\n",
2959                           programVersion);
2960                   if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2961                       strcat(str, "/set-2 51 1\n/set seek 1\n");
2962                 } else if (ics_type == ICS_CHESSNET) {
2963                   snprintf(str, MSG_SIZ, "/style 12\n");
2964                 } else {
2965                   safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2966                   strcat(str, programVersion);
2967                   strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2968                   if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2969                       strcat(str, "$iset seekremove 1\n$set seek 1\n");
2970 #ifdef WIN32
2971                   strcat(str, "$iset nohighlight 1\n");
2972 #endif
2973                   strcat(str, "$iset lock 1\n$style 12\n");
2974                 }
2975                 SendToICS(str);
2976                 NotifyFrontendLogin();
2977                 intfSet = TRUE;
2978             }
2979
2980             if (started == STARTED_COMMENT) {
2981                 /* Accumulate characters in comment */
2982                 parse[parse_pos++] = buf[i];
2983                 if (buf[i] == '\n') {
2984                     parse[parse_pos] = NULLCHAR;
2985                     if(chattingPartner>=0) {
2986                         char mess[MSG_SIZ];
2987                         snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2988                         OutputChatMessage(chattingPartner, mess);
2989                         chattingPartner = -1;
2990                         next_out = i+1; // [HGM] suppress printing in ICS window
2991                     } else
2992                     if(!suppressKibitz) // [HGM] kibitz
2993                         AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2994                     else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2995                         int nrDigit = 0, nrAlph = 0, j;
2996                         if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2997                         { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2998                         parse[parse_pos] = NULLCHAR;
2999                         // try to be smart: if it does not look like search info, it should go to
3000                         // ICS interaction window after all, not to engine-output window.
3001                         for(j=0; j<parse_pos; j++) { // count letters and digits
3002                             nrDigit += (parse[j] >= '0' && parse[j] <= '9');
3003                             nrAlph  += (parse[j] >= 'a' && parse[j] <= 'z');
3004                             nrAlph  += (parse[j] >= 'A' && parse[j] <= 'Z');
3005                         }
3006                         if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
3007                             int depth=0; float score;
3008                             if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
3009                                 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
3010                                 pvInfoList[forwardMostMove-1].depth = depth;
3011                                 pvInfoList[forwardMostMove-1].score = 100*score;
3012                             }
3013                             OutputKibitz(suppressKibitz, parse);
3014                         } else {
3015                             char tmp[MSG_SIZ];
3016                             if(gameMode == IcsObserving) // restore original ICS messages
3017                               snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
3018                             else
3019                             snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
3020                             SendToPlayer(tmp, strlen(tmp));
3021                         }
3022                         next_out = i+1; // [HGM] suppress printing in ICS window
3023                     }
3024                     started = STARTED_NONE;
3025                 } else {
3026                     /* Don't match patterns against characters in comment */
3027                     i++;
3028                     continue;
3029                 }
3030             }
3031             if (started == STARTED_CHATTER) {
3032                 if (buf[i] != '\n') {
3033                     /* Don't match patterns against characters in chatter */
3034                     i++;
3035                     continue;
3036                 }
3037                 started = STARTED_NONE;
3038                 if(suppressKibitz) next_out = i+1;
3039             }
3040
3041             /* Kludge to deal with rcmd protocol */
3042             if (firstTime && looking_at(buf, &i, "\001*")) {
3043                 DisplayFatalError(&buf[1], 0, 1);
3044                 continue;
3045             } else {
3046                 firstTime = FALSE;
3047             }
3048
3049             if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3050                 ics_type = ICS_ICC;
3051                 ics_prefix = "/";
3052                 if (appData.debugMode)
3053                   fprintf(debugFP, "ics_type %d\n", ics_type);
3054                 continue;
3055             }
3056             if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3057                 ics_type = ICS_FICS;
3058                 ics_prefix = "$";
3059                 if (appData.debugMode)
3060                   fprintf(debugFP, "ics_type %d\n", ics_type);
3061                 continue;
3062             }
3063             if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3064                 ics_type = ICS_CHESSNET;
3065                 ics_prefix = "/";
3066                 if (appData.debugMode)
3067                   fprintf(debugFP, "ics_type %d\n", ics_type);
3068                 continue;
3069             }
3070
3071             if (!loggedOn &&
3072                 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3073                  looking_at(buf, &i, "Logging you in as \"*\"") ||
3074                  looking_at(buf, &i, "will be \"*\""))) {
3075               safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3076               continue;
3077             }
3078
3079             if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3080               char buf[MSG_SIZ];
3081               snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3082               DisplayIcsInteractionTitle(buf);
3083               have_set_title = TRUE;
3084             }
3085
3086             /* skip finger notes */
3087             if (started == STARTED_NONE &&
3088                 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3089                  (buf[i] == '1' && buf[i+1] == '0')) &&
3090                 buf[i+2] == ':' && buf[i+3] == ' ') {
3091               started = STARTED_CHATTER;
3092               i += 3;
3093               continue;
3094             }
3095
3096             oldi = i;
3097             // [HGM] seekgraph: recognize sought lines and end-of-sought message
3098             if(appData.seekGraph) {
3099                 if(soughtPending && MatchSoughtLine(buf+i)) {
3100                     i = strstr(buf+i, "rated") - buf;
3101                     if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3102                     next_out = leftover_start = i;
3103                     started = STARTED_CHATTER;
3104                     suppressKibitz = TRUE;
3105                     continue;
3106                 }
3107                 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3108                         && looking_at(buf, &i, "* ads displayed")) {
3109                     soughtPending = FALSE;
3110                     seekGraphUp = TRUE;
3111                     DrawSeekGraph();
3112                     continue;
3113                 }
3114                 if(appData.autoRefresh) {
3115                     if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3116                         int s = (ics_type == ICS_ICC); // ICC format differs
3117                         if(seekGraphUp)
3118                         AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3119                               star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3120                         looking_at(buf, &i, "*% "); // eat prompt
3121                         if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3122                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3123                         next_out = i; // suppress
3124                         continue;
3125                     }
3126                     if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3127                         char *p = star_match[0];
3128                         while(*p) {
3129                             if(seekGraphUp) RemoveSeekAd(atoi(p));
3130                             while(*p && *p++ != ' '); // next
3131                         }
3132                         looking_at(buf, &i, "*% "); // eat prompt
3133                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3134                         next_out = i;
3135                         continue;
3136                     }
3137                 }
3138             }
3139
3140             /* skip formula vars */
3141             if (started == STARTED_NONE &&
3142                 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3143               started = STARTED_CHATTER;
3144               i += 3;
3145               continue;
3146             }
3147
3148             // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3149             if (appData.autoKibitz && started == STARTED_NONE &&
3150                 !appData.icsEngineAnalyze &&                     // [HGM] [DM] ICS analyze
3151                 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3152                 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3153                     looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3154                    (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3155                     StrStr(star_match[0], gameInfo.black) == star_match[0]   )) { // kibitz of self or opponent
3156                         suppressKibitz = TRUE;
3157                         if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3158                         next_out = i;
3159                         if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3160                                 && (gameMode == IcsPlayingWhite)) ||
3161                            (StrStr(star_match[0], gameInfo.black) == star_match[0]
3162                                 && (gameMode == IcsPlayingBlack))   ) // opponent kibitz
3163                             started = STARTED_CHATTER; // own kibitz we simply discard
3164                         else {
3165                             started = STARTED_COMMENT; // make sure it will be collected in parse[]
3166                             parse_pos = 0; parse[0] = NULLCHAR;
3167                             savingComment = TRUE;
3168                             suppressKibitz = gameMode != IcsObserving ? 2 :
3169                                 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3170                         }
3171                         continue;
3172                 } else
3173                 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3174                     looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3175                          && atoi(star_match[0])) {
3176                     // suppress the acknowledgements of our own autoKibitz
3177                     char *p;
3178                     if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3179                     if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3180                     SendToPlayer(star_match[0], strlen(star_match[0]));
3181                     if(looking_at(buf, &i, "*% ")) // eat prompt
3182                         suppressKibitz = FALSE;
3183                     next_out = i;
3184                     continue;
3185                 }
3186             } // [HGM] kibitz: end of patch
3187
3188             if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3189
3190             // [HGM] chat: intercept tells by users for which we have an open chat window
3191             channel = -1;
3192             if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3193                                            looking_at(buf, &i, "* whispers:") ||
3194                                            looking_at(buf, &i, "* kibitzes:") ||
3195                                            looking_at(buf, &i, "* shouts:") ||
3196                                            looking_at(buf, &i, "* c-shouts:") ||
3197                                            looking_at(buf, &i, "--> * ") ||
3198                                            looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3199                                            looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3200                                            looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3201                                            looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3202                 int p;
3203                 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3204                 chattingPartner = -1;
3205
3206                 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3207                 for(p=0; p<MAX_CHAT; p++) {
3208                     if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3209                     talker[0] = '['; strcat(talker, "] ");
3210                     Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
3211                     chattingPartner = p; break;
3212                     }
3213                 } else
3214                 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3215                 for(p=0; p<MAX_CHAT; p++) {
3216                     if(!strcmp("kibitzes", chatPartner[p])) {
3217                         talker[0] = '['; strcat(talker, "] ");
3218                         chattingPartner = p; break;
3219                     }
3220                 } else
3221                 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3222                 for(p=0; p<MAX_CHAT; p++) {
3223                     if(!strcmp("whispers", chatPartner[p])) {
3224                         talker[0] = '['; strcat(talker, "] ");
3225                         chattingPartner = p; break;
3226                     }
3227                 } else
3228                 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3229                   if(buf[i-8] == '-' && buf[i-3] == 't')
3230                   for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3231                     if(!strcmp("c-shouts", chatPartner[p])) {
3232                         talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3233                         chattingPartner = p; break;
3234                     }
3235                   }
3236                   if(chattingPartner < 0)
3237                   for(p=0; p<MAX_CHAT; p++) {
3238                     if(!strcmp("shouts", chatPartner[p])) {
3239                         if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3240                         else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3241                         else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3242                         chattingPartner = p; break;
3243                     }
3244                   }
3245                 }
3246                 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3247                 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3248                     talker[0] = 0; Colorize(ColorTell, FALSE);
3249                     chattingPartner = p; break;
3250                 }
3251                 if(chattingPartner<0) i = oldi; else {
3252                     Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3253                     if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3254                     if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3255                     started = STARTED_COMMENT;
3256                     parse_pos = 0; parse[0] = NULLCHAR;
3257                     savingComment = 3 + chattingPartner; // counts as TRUE
3258                     suppressKibitz = TRUE;
3259                     continue;
3260                 }
3261             } // [HGM] chat: end of patch
3262
3263           backup = i;
3264             if (appData.zippyTalk || appData.zippyPlay) {
3265                 /* [DM] Backup address for color zippy lines */
3266 #if ZIPPY
3267                if (loggedOn == TRUE)
3268                        if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3269                           (appData.zippyPlay && ZippyMatch(buf, &backup)));
3270 #endif
3271             } // [DM] 'else { ' deleted
3272                 if (
3273                     /* Regular tells and says */
3274                     (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3275                     looking_at(buf, &i, "* (your partner) tells you: ") ||
3276                     looking_at(buf, &i, "* says: ") ||
3277                     /* Don't color "message" or "messages" output */
3278                     (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3279                     looking_at(buf, &i, "*. * at *:*: ") ||
3280                     looking_at(buf, &i, "--* (*:*): ") ||
3281                     /* Message notifications (same color as tells) */
3282                     looking_at(buf, &i, "* has left a message ") ||
3283                     looking_at(buf, &i, "* just sent you a message:\n") ||
3284                     /* Whispers and kibitzes */
3285                     (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3286                     looking_at(buf, &i, "* kibitzes: ") ||
3287                     /* Channel tells */
3288                     (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3289
3290                   if (tkind == 1 && strchr(star_match[0], ':')) {
3291                       /* Avoid "tells you:" spoofs in channels */
3292                      tkind = 3;
3293                   }
3294                   if (star_match[0][0] == NULLCHAR ||
3295                       strchr(star_match[0], ' ') ||
3296                       (tkind == 3 && strchr(star_match[1], ' '))) {
3297                     /* Reject bogus matches */
3298                     i = oldi;
3299                   } else {
3300                     if (appData.colorize) {
3301                       if (oldi > next_out) {
3302                         SendToPlayer(&buf[next_out], oldi - next_out);
3303                         next_out = oldi;
3304                       }
3305                       switch (tkind) {
3306                       case 1:
3307                         Colorize(ColorTell, FALSE);
3308                         curColor = ColorTell;
3309                         break;
3310                       case 2:
3311                         Colorize(ColorKibitz, FALSE);
3312                         curColor = ColorKibitz;
3313                         break;
3314                       case 3:
3315                         p = strrchr(star_match[1], '(');
3316                         if (p == NULL) {
3317                           p = star_match[1];
3318                         } else {
3319                           p++;
3320                         }
3321                         if (atoi(p) == 1) {
3322                           Colorize(ColorChannel1, FALSE);
3323                           curColor = ColorChannel1;
3324                         } else {
3325                           Colorize(ColorChannel, FALSE);
3326                           curColor = ColorChannel;
3327                         }
3328                         break;
3329                       case 5:
3330                         curColor = ColorNormal;
3331                         break;
3332                       }
3333                     }
3334                     if (started == STARTED_NONE && appData.autoComment &&
3335                         (gameMode == IcsObserving ||
3336                          gameMode == IcsPlayingWhite ||
3337                          gameMode == IcsPlayingBlack)) {
3338                       parse_pos = i - oldi;
3339                       memcpy(parse, &buf[oldi], parse_pos);
3340                       parse[parse_pos] = NULLCHAR;
3341                       started = STARTED_COMMENT;
3342                       savingComment = TRUE;
3343                     } else {
3344                       started = STARTED_CHATTER;
3345                       savingComment = FALSE;
3346                     }
3347                     loggedOn = TRUE;
3348                     continue;
3349                   }
3350                 }
3351
3352                 if (looking_at(buf, &i, "* s-shouts: ") ||
3353                     looking_at(buf, &i, "* c-shouts: ")) {
3354                     if (appData.colorize) {
3355                         if (oldi > next_out) {
3356                             SendToPlayer(&buf[next_out], oldi - next_out);
3357                             next_out = oldi;
3358                         }
3359                         Colorize(ColorSShout, FALSE);
3360                         curColor = ColorSShout;
3361                     }
3362                     loggedOn = TRUE;
3363                     started = STARTED_CHATTER;
3364                     continue;
3365                 }
3366
3367                 if (looking_at(buf, &i, "--->")) {
3368                     loggedOn = TRUE;
3369                     continue;
3370                 }
3371
3372                 if (looking_at(buf, &i, "* shouts: ") ||
3373                     looking_at(buf, &i, "--> ")) {
3374                     if (appData.colorize) {
3375                         if (oldi > next_out) {
3376                             SendToPlayer(&buf[next_out], oldi - next_out);
3377                             next_out = oldi;
3378                         }
3379                         Colorize(ColorShout, FALSE);
3380                         curColor = ColorShout;
3381                     }
3382                     loggedOn = TRUE;
3383                     started = STARTED_CHATTER;
3384                     continue;
3385                 }
3386
3387                 if (looking_at( buf, &i, "Challenge:")) {
3388                     if (appData.colorize) {
3389                         if (oldi > next_out) {
3390                             SendToPlayer(&buf[next_out], oldi - next_out);
3391                             next_out = oldi;
3392                         }
3393                         Colorize(ColorChallenge, FALSE);
3394                         curColor = ColorChallenge;
3395                     }
3396                     loggedOn = TRUE;
3397                     continue;
3398                 }
3399
3400                 if (looking_at(buf, &i, "* offers you") ||
3401                     looking_at(buf, &i, "* offers to be") ||
3402                     looking_at(buf, &i, "* would like to") ||
3403                     looking_at(buf, &i, "* requests to") ||
3404                     looking_at(buf, &i, "Your opponent offers") ||
3405                     looking_at(buf, &i, "Your opponent requests")) {
3406
3407                     if (appData.colorize) {
3408                         if (oldi > next_out) {
3409                             SendToPlayer(&buf[next_out], oldi - next_out);
3410                             next_out = oldi;
3411                         }
3412                         Colorize(ColorRequest, FALSE);
3413                         curColor = ColorRequest;
3414                     }
3415                     continue;
3416                 }
3417
3418                 if (looking_at(buf, &i, "* (*) seeking")) {
3419                     if (appData.colorize) {
3420                         if (oldi > next_out) {
3421                             SendToPlayer(&buf[next_out], oldi - next_out);
3422                             next_out = oldi;
3423                         }
3424                         Colorize(ColorSeek, FALSE);
3425                         curColor = ColorSeek;
3426                     }
3427                     continue;
3428             }
3429
3430           if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3431
3432             if (looking_at(buf, &i, "\\   ")) {
3433                 if (prevColor != ColorNormal) {
3434                     if (oldi > next_out) {
3435                         SendToPlayer(&buf[next_out], oldi - next_out);
3436                         next_out = oldi;
3437                     }
3438                     Colorize(prevColor, TRUE);
3439                     curColor = prevColor;
3440                 }
3441                 if (savingComment) {
3442                     parse_pos = i - oldi;
3443                     memcpy(parse, &buf[oldi], parse_pos);
3444                     parse[parse_pos] = NULLCHAR;
3445                     started = STARTED_COMMENT;
3446                     if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3447                         chattingPartner = savingComment - 3; // kludge to remember the box
3448                 } else {
3449                     started = STARTED_CHATTER;
3450                 }
3451                 continue;
3452             }
3453
3454             if (looking_at(buf, &i, "Black Strength :") ||
3455                 looking_at(buf, &i, "<<< style 10 board >>>") ||
3456                 looking_at(buf, &i, "<10>") ||
3457                 looking_at(buf, &i, "#@#")) {
3458                 /* Wrong board style */
3459                 loggedOn = TRUE;
3460                 SendToICS(ics_prefix);
3461                 SendToICS("set style 12\n");
3462                 SendToICS(ics_prefix);
3463                 SendToICS("refresh\n");
3464                 continue;
3465             }
3466
3467             if (looking_at(buf, &i, "login:")) {
3468               if (!have_sent_ICS_logon) {
3469                 if(ICSInitScript())
3470                   have_sent_ICS_logon = 1;
3471                 else // no init script was found
3472                   have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
3473               } else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
3474                   have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
3475               }
3476                 continue;
3477             }
3478
3479             if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3480                 (looking_at(buf, &i, "\n<12> ") ||
3481                  looking_at(buf, &i, "<12> "))) {
3482                 loggedOn = TRUE;
3483                 if (oldi > next_out) {
3484                     SendToPlayer(&buf[next_out], oldi - next_out);
3485                 }
3486                 next_out = i;
3487                 started = STARTED_BOARD;
3488                 parse_pos = 0;
3489                 continue;
3490             }
3491
3492             if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3493                 looking_at(buf, &i, "<b1> ")) {
3494                 if (oldi > next_out) {
3495                     SendToPlayer(&buf[next_out], oldi - next_out);
3496                 }
3497                 next_out = i;
3498                 started = STARTED_HOLDINGS;
3499                 parse_pos = 0;
3500                 continue;
3501             }
3502
3503             if (looking_at(buf, &i, "* *vs. * *--- *")) {
3504                 loggedOn = TRUE;
3505                 /* Header for a move list -- first line */
3506
3507                 switch (ics_getting_history) {
3508                   case H_FALSE:
3509                     switch (gameMode) {
3510                       case IcsIdle:
3511                       case BeginningOfGame:
3512                         /* User typed "moves" or "oldmoves" while we
3513                            were idle.  Pretend we asked for these
3514                            moves and soak them up so user can step
3515                            through them and/or save them.
3516                            */
3517                         Reset(FALSE, TRUE);
3518                         gameMode = IcsObserving;
3519                         ModeHighlight();
3520                         ics_gamenum = -1;
3521                         ics_getting_history = H_GOT_UNREQ_HEADER;
3522                         break;
3523                       case EditGame: /*?*/
3524                       case EditPosition: /*?*/
3525                         /* Should above feature work in these modes too? */
3526                         /* For now it doesn't */
3527                         ics_getting_history = H_GOT_UNWANTED_HEADER;
3528                         break;
3529                       default:
3530                         ics_getting_history = H_GOT_UNWANTED_HEADER;
3531                         break;
3532                     }
3533                     break;
3534                   case H_REQUESTED:
3535                     /* Is this the right one? */
3536                     if (gameInfo.white && gameInfo.black &&
3537                         strcmp(gameInfo.white, star_match[0]) == 0 &&
3538                         strcmp(gameInfo.black, star_match[2]) == 0) {
3539                         /* All is well */
3540                         ics_getting_history = H_GOT_REQ_HEADER;
3541                     }
3542                     break;
3543                   case H_GOT_REQ_HEADER:
3544                   case H_GOT_UNREQ_HEADER:
3545                   case H_GOT_UNWANTED_HEADER:
3546                   case H_GETTING_MOVES:
3547                     /* Should not happen */
3548                     DisplayError(_("Error gathering move list: two headers"), 0);
3549                     ics_getting_history = H_FALSE;
3550                     break;
3551                 }
3552
3553                 /* Save player ratings into gameInfo if needed */
3554                 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3555                      ics_getting_history == H_GOT_UNREQ_HEADER) &&
3556                     (gameInfo.whiteRating == -1 ||
3557                      gameInfo.blackRating == -1)) {
3558
3559                     gameInfo.whiteRating = string_to_rating(star_match[1]);
3560                     gameInfo.blackRating = string_to_rating(star_match[3]);
3561                     if (appData.debugMode)
3562                       fprintf(debugFP, "Ratings from header: W %d, B %d\n",
3563                               gameInfo.whiteRating, gameInfo.blackRating);
3564                 }
3565                 continue;
3566             }
3567
3568             if (looking_at(buf, &i,
3569               "* * match, initial time: * minute*, increment: * second")) {
3570                 /* Header for a move list -- second line */
3571                 /* Initial board will follow if this is a wild game */
3572                 if (gameInfo.event != NULL) free(gameInfo.event);
3573                 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3574                 gameInfo.event = StrSave(str);
3575                 /* [HGM] we switched variant. Translate boards if needed. */
3576                 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3577                 continue;
3578             }
3579
3580             if (looking_at(buf, &i, "Move  ")) {
3581                 /* Beginning of a move list */
3582                 switch (ics_getting_history) {
3583                   case H_FALSE:
3584                     /* Normally should not happen */
3585                     /* Maybe user hit reset while we were parsing */
3586                     break;
3587                   case H_REQUESTED:
3588                     /* Happens if we are ignoring a move list that is not
3589                      * the one we just requested.  Common if the user
3590                      * tries to observe two games without turning off
3591                      * getMoveList */
3592                     break;
3593                   case H_GETTING_MOVES:
3594                     /* Should not happen */
3595                     DisplayError(_("Error gathering move list: nested"), 0);
3596                     ics_getting_history = H_FALSE;
3597                     break;
3598                   case H_GOT_REQ_HEADER:
3599                     ics_getting_history = H_GETTING_MOVES;
3600                     started = STARTED_MOVES;
3601                     parse_pos = 0;
3602                     if (oldi > next_out) {
3603                         SendToPlayer(&buf[next_out], oldi - next_out);
3604                     }
3605                     break;
3606                   case H_GOT_UNREQ_HEADER:
3607                     ics_getting_history = H_GETTING_MOVES;
3608                     started = STARTED_MOVES_NOHIDE;
3609                     parse_pos = 0;
3610                     break;
3611                   case H_GOT_UNWANTED_HEADER:
3612                     ics_getting_history = H_FALSE;
3613                     break;
3614                 }
3615                 continue;
3616             }
3617
3618             if (looking_at(buf, &i, "% ") ||
3619                 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3620                  && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3621                 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3622                     soughtPending = FALSE;
3623                     seekGraphUp = TRUE;
3624                     DrawSeekGraph();
3625                 }
3626                 if(suppressKibitz) next_out = i;
3627                 savingComment = FALSE;
3628                 suppressKibitz = 0;
3629                 switch (started) {
3630                   case STARTED_MOVES:
3631                   case STARTED_MOVES_NOHIDE:
3632                     memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3633                     parse[parse_pos + i - oldi] = NULLCHAR;
3634                     ParseGameHistory(parse);
3635 #if ZIPPY
3636                     if (appData.zippyPlay && first.initDone) {
3637                         FeedMovesToProgram(&first, forwardMostMove);
3638                         if (gameMode == IcsPlayingWhite) {
3639                             if (WhiteOnMove(forwardMostMove)) {
3640                                 if (first.sendTime) {
3641                                   if (first.useColors) {
3642                                     SendToProgram("black\n", &first);
3643                                   }
3644                                   SendTimeRemaining(&first, TRUE);
3645                                 }
3646                                 if (first.useColors) {
3647                                   SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3648                                 }
3649                                 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3650                                 first.maybeThinking = TRUE;
3651                             } else {
3652                                 if (first.usePlayother) {
3653                                   if (first.sendTime) {
3654                                     SendTimeRemaining(&first, TRUE);
3655                                   }
3656                                   SendToProgram("playother\n", &first);
3657                                   firstMove = FALSE;
3658                                 } else {
3659                                   firstMove = TRUE;
3660                                 }
3661                             }
3662                         } else if (gameMode == IcsPlayingBlack) {
3663                             if (!WhiteOnMove(forwardMostMove)) {
3664                                 if (first.sendTime) {
3665                                   if (first.useColors) {
3666                                     SendToProgram("white\n", &first);
3667                                   }
3668                                   SendTimeRemaining(&first, FALSE);
3669                                 }
3670                                 if (first.useColors) {
3671                                   SendToProgram("black\n", &first);
3672                                 }
3673                                 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3674                                 first.maybeThinking = TRUE;
3675                             } else {
3676                                 if (first.usePlayother) {
3677                                   if (first.sendTime) {
3678                                     SendTimeRemaining(&first, FALSE);
3679                                   }
3680                                   SendToProgram("playother\n", &first);
3681                                   firstMove = FALSE;
3682                                 } else {
3683                                   firstMove = TRUE;
3684                                 }
3685                             }
3686                         }
3687                     }
3688 #endif
3689                     if (gameMode == IcsObserving && ics_gamenum == -1) {
3690                         /* Moves came from oldmoves or moves command
3691                            while we weren't doing anything else.
3692                            */
3693                         currentMove = forwardMostMove;
3694                         ClearHighlights();/*!!could figure this out*/
3695                         flipView = appData.flipView;
3696                         DrawPosition(TRUE, boards[currentMove]);
3697                         DisplayBothClocks();
3698                         snprintf(str, MSG_SIZ, "%s %s %s",
3699                                 gameInfo.white, _("vs."),  gameInfo.black);
3700                         DisplayTitle(str);
3701                         gameMode = IcsIdle;
3702                     } else {
3703                         /* Moves were history of an active game */
3704                         if (gameInfo.resultDetails != NULL) {
3705                             free(gameInfo.resultDetails);
3706                             gameInfo.resultDetails = NULL;
3707                         }
3708                     }
3709                     HistorySet(parseList, backwardMostMove,
3710                                forwardMostMove, currentMove-1);
3711                     DisplayMove(currentMove - 1);
3712                     if (started == STARTED_MOVES) next_out = i;
3713                     started = STARTED_NONE;
3714                     ics_getting_history = H_FALSE;
3715                     break;
3716
3717                   case STARTED_OBSERVE:
3718                     started = STARTED_NONE;
3719                     SendToICS(ics_prefix);
3720                     SendToICS("refresh\n");
3721                     break;
3722
3723                   default:
3724                     break;
3725                 }
3726                 if(bookHit) { // [HGM] book: simulate book reply
3727                     static char bookMove[MSG_SIZ]; // a bit generous?
3728
3729                     programStats.nodes = programStats.depth = programStats.time =
3730                     programStats.score = programStats.got_only_move = 0;
3731                     sprintf(programStats.movelist, "%s (xbook)", bookHit);
3732
3733                     safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3734                     strcat(bookMove, bookHit);
3735                     HandleMachineMove(bookMove, &first);
3736                 }
3737                 continue;
3738             }
3739
3740             if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3741                  started == STARTED_HOLDINGS ||
3742                  started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3743                 /* Accumulate characters in move list or board */
3744                 parse[parse_pos++] = buf[i];
3745             }
3746
3747             /* Start of game messages.  Mostly we detect start of game
3748                when the first board image arrives.  On some versions
3749                of the ICS, though, we need to do a "refresh" after starting
3750                to observe in order to get the current board right away. */
3751             if (looking_at(buf, &i, "Adding game * to observation list")) {
3752                 started = STARTED_OBSERVE;
3753                 continue;
3754             }
3755
3756             /* Handle auto-observe */
3757             if (appData.autoObserve &&
3758                 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3759                 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3760                 char *player;
3761                 /* Choose the player that was highlighted, if any. */
3762                 if (star_match[0][0] == '\033' ||
3763                     star_match[1][0] != '\033') {
3764                     player = star_match[0];
3765                 } else {
3766                     player = star_match[2];
3767                 }
3768                 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3769                         ics_prefix, StripHighlightAndTitle(player));
3770                 SendToICS(str);
3771
3772                 /* Save ratings from notify string */
3773                 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3774                 player1Rating = string_to_rating(star_match[1]);
3775                 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3776                 player2Rating = string_to_rating(star_match[3]);
3777
3778                 if (appData.debugMode)
3779                   fprintf(debugFP,
3780                           "Ratings from 'Game notification:' %s %d, %s %d\n",
3781                           player1Name, player1Rating,
3782                           player2Name, player2Rating);
3783
3784                 continue;
3785             }
3786
3787             /* Deal with automatic examine mode after a game,
3788                and with IcsObserving -> IcsExamining transition */
3789             if (looking_at(buf, &i, "Entering examine mode for game *") ||
3790                 looking_at(buf, &i, "has made you an examiner of game *")) {
3791
3792                 int gamenum = atoi(star_match[0]);
3793                 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3794                     gamenum == ics_gamenum) {
3795                     /* We were already playing or observing this game;
3796                        no need to refetch history */
3797                     gameMode = IcsExamining;
3798                     if (pausing) {
3799                         pauseExamForwardMostMove = forwardMostMove;
3800                     } else if (currentMove < forwardMostMove) {
3801                         ForwardInner(forwardMostMove);
3802                     }
3803                 } else {
3804                     /* I don't think this case really can happen */
3805                     SendToICS(ics_prefix);
3806                     SendToICS("refresh\n");
3807                 }
3808                 continue;
3809             }
3810
3811             /* Error messages */
3812 //          if (ics_user_moved) {
3813             if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3814                 if (looking_at(buf, &i, "Illegal move") ||
3815                     looking_at(buf, &i, "Not a legal move") ||
3816                     looking_at(buf, &i, "Your king is in check") ||
3817                     looking_at(buf, &i, "It isn't your turn") ||
3818                     looking_at(buf, &i, "It is not your move")) {
3819                     /* Illegal move */
3820                     if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3821                         currentMove = forwardMostMove-1;
3822                         DisplayMove(currentMove - 1); /* before DMError */
3823                         DrawPosition(FALSE, boards[currentMove]);
3824                         SwitchClocks(forwardMostMove-1); // [HGM] race
3825                         DisplayBothClocks();
3826                     }
3827                     DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3828                     ics_user_moved = 0;
3829                     continue;
3830                 }
3831             }
3832
3833             if (looking_at(buf, &i, "still have time") ||
3834                 looking_at(buf, &i, "not out of time") ||
3835                 looking_at(buf, &i, "either player is out of time") ||
3836                 looking_at(buf, &i, "has timeseal; checking")) {
3837                 /* We must have called his flag a little too soon */
3838                 whiteFlag = blackFlag = FALSE;
3839                 continue;
3840             }
3841
3842             if (looking_at(buf, &i, "added * seconds to") ||
3843                 looking_at(buf, &i, "seconds were added to")) {
3844                 /* Update the clocks */
3845                 SendToICS(ics_prefix);
3846                 SendToICS("refresh\n");
3847                 continue;
3848             }
3849
3850             if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3851                 ics_clock_paused = TRUE;
3852                 StopClocks();
3853                 continue;
3854             }
3855
3856             if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3857                 ics_clock_paused = FALSE;
3858                 StartClocks();
3859                 continue;
3860             }
3861
3862             /* Grab player ratings from the Creating: message.
3863                Note we have to check for the special case when
3864                the ICS inserts things like [white] or [black]. */
3865             if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3866                 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3867                 /* star_matches:
3868                    0    player 1 name (not necessarily white)
3869                    1    player 1 rating
3870                    2    empty, white, or black (IGNORED)
3871                    3    player 2 name (not necessarily black)
3872                    4    player 2 rating
3873
3874                    The names/ratings are sorted out when the game
3875                    actually starts (below).
3876                 */
3877                 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3878                 player1Rating = string_to_rating(star_match[1]);
3879                 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3880                 player2Rating = string_to_rating(star_match[4]);
3881
3882                 if (appData.debugMode)
3883                   fprintf(debugFP,
3884                           "Ratings from 'Creating:' %s %d, %s %d\n",
3885                           player1Name, player1Rating,
3886                           player2Name, player2Rating);
3887
3888                 continue;
3889             }
3890
3891             /* Improved generic start/end-of-game messages */
3892             if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3893                 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3894                 /* If tkind == 0: */
3895                 /* star_match[0] is the game number */
3896                 /*           [1] is the white player's name */
3897                 /*           [2] is the black player's name */
3898                 /* For end-of-game: */
3899                 /*           [3] is the reason for the game end */
3900                 /*           [4] is a PGN end game-token, preceded by " " */
3901                 /* For start-of-game: */
3902                 /*           [3] begins with "Creating" or "Continuing" */
3903                 /*           [4] is " *" or empty (don't care). */
3904                 int gamenum = atoi(star_match[0]);
3905                 char *whitename, *blackname, *why, *endtoken;
3906                 ChessMove endtype = EndOfFile;
3907
3908                 if (tkind == 0) {
3909                   whitename = star_match[1];
3910                   blackname = star_match[2];
3911                   why = star_match[3];
3912                   endtoken = star_match[4];
3913                 } else {
3914                   whitename = star_match[1];
3915                   blackname = star_match[3];
3916                   why = star_match[5];
3917                   endtoken = star_match[6];
3918                 }
3919
3920                 /* Game start messages */
3921                 if (strncmp(why, "Creating ", 9) == 0 ||
3922                     strncmp(why, "Continuing ", 11) == 0) {
3923                     gs_gamenum = gamenum;
3924                     safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3925                     if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
3926                     VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3927 #if ZIPPY
3928                     if (appData.zippyPlay) {
3929                         ZippyGameStart(whitename, blackname);
3930                     }
3931 #endif /*ZIPPY*/
3932                     partnerBoardValid = FALSE; // [HGM] bughouse
3933                     continue;
3934                 }
3935
3936                 /* Game end messages */
3937                 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3938                     ics_gamenum != gamenum) {
3939                     continue;
3940                 }
3941                 while (endtoken[0] == ' ') endtoken++;
3942                 switch (endtoken[0]) {
3943                   case '*':
3944                   default:
3945                     endtype = GameUnfinished;
3946                     break;
3947                   case '0':
3948                     endtype = BlackWins;
3949                     break;
3950                   case '1':
3951                     if (endtoken[1] == '/')
3952                       endtype = GameIsDrawn;
3953                     else
3954                       endtype = WhiteWins;
3955                     break;
3956                 }
3957                 GameEnds(endtype, why, GE_ICS);
3958 #if ZIPPY
3959                 if (appData.zippyPlay && first.initDone) {
3960                     ZippyGameEnd(endtype, why);
3961                     if (first.pr == NoProc) {
3962                       /* Start the next process early so that we'll
3963                          be ready for the next challenge */
3964                       StartChessProgram(&first);
3965                     }
3966                     /* Send "new" early, in case this command takes
3967                        a long time to finish, so that we'll be ready
3968                        for the next challenge. */
3969                     gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3970                     Reset(TRUE, TRUE);
3971                 }
3972 #endif /*ZIPPY*/
3973                 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3974                 continue;
3975             }
3976
3977             if (looking_at(buf, &i, "Removing game * from observation") ||
3978                 looking_at(buf, &i, "no longer observing game *") ||
3979                 looking_at(buf, &i, "Game * (*) has no examiners")) {
3980                 if (gameMode == IcsObserving &&
3981                     atoi(star_match[0]) == ics_gamenum)
3982                   {
3983                       /* icsEngineAnalyze */
3984                       if (appData.icsEngineAnalyze) {
3985                             ExitAnalyzeMode();
3986                             ModeHighlight();
3987                       }
3988                       StopClocks();
3989                       gameMode = IcsIdle;
3990                       ics_gamenum = -1;
3991                       ics_user_moved = FALSE;
3992                   }
3993                 continue;
3994             }
3995
3996             if (looking_at(buf, &i, "no longer examining game *")) {
3997                 if (gameMode == IcsExamining &&
3998                     atoi(star_match[0]) == ics_gamenum)
3999                   {
4000                       gameMode = IcsIdle;
4001                       ics_gamenum = -1;
4002                       ics_user_moved = FALSE;
4003                   }
4004                 continue;
4005             }
4006
4007             /* Advance leftover_start past any newlines we find,
4008                so only partial lines can get reparsed */
4009             if (looking_at(buf, &i, "\n")) {
4010                 prevColor = curColor;
4011                 if (curColor != ColorNormal) {
4012                     if (oldi > next_out) {
4013                         SendToPlayer(&buf[next_out], oldi - next_out);
4014                         next_out = oldi;
4015                     }
4016                     Colorize(ColorNormal, FALSE);
4017                     curColor = ColorNormal;
4018                 }
4019                 if (started == STARTED_BOARD) {
4020                     started = STARTED_NONE;
4021                     parse[parse_pos] = NULLCHAR;
4022                     ParseBoard12(parse);
4023                     ics_user_moved = 0;
4024
4025                     /* Send premove here */
4026                     if (appData.premove) {
4027                       char str[MSG_SIZ];
4028                       if (currentMove == 0 &&
4029                           gameMode == IcsPlayingWhite &&
4030                           appData.premoveWhite) {
4031                         snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
4032                         if (appData.debugMode)
4033                           fprintf(debugFP, "Sending premove:\n");
4034                         SendToICS(str);
4035                       } else if (currentMove == 1 &&
4036                                  gameMode == IcsPlayingBlack &&
4037                                  appData.premoveBlack) {
4038                         snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4039                         if (appData.debugMode)
4040                           fprintf(debugFP, "Sending premove:\n");
4041                         SendToICS(str);
4042                       } else if (gotPremove) {
4043                         gotPremove = 0;
4044                         ClearPremoveHighlights();
4045                         if (appData.debugMode)
4046                           fprintf(debugFP, "Sending premove:\n");
4047                           UserMoveEvent(premoveFromX, premoveFromY,
4048                                         premoveToX, premoveToY,
4049                                         premovePromoChar);
4050                       }
4051                     }
4052
4053                     /* Usually suppress following prompt */
4054                     if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4055                         while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4056                         if (looking_at(buf, &i, "*% ")) {
4057                             savingComment = FALSE;
4058                             suppressKibitz = 0;
4059                         }
4060                     }
4061                     next_out = i;
4062                 } else if (started == STARTED_HOLDINGS) {
4063                     int gamenum;
4064                     char new_piece[MSG_SIZ];
4065                     started = STARTED_NONE;
4066                     parse[parse_pos] = NULLCHAR;
4067                     if (appData.debugMode)
4068                       fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4069                                                         parse, currentMove);
4070                     if (sscanf(parse, " game %d", &gamenum) == 1) {
4071                       if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4072                         if (gameInfo.variant == VariantNormal) {
4073                           /* [HGM] We seem to switch variant during a game!
4074                            * Presumably no holdings were displayed, so we have
4075                            * to move the position two files to the right to
4076                            * create room for them!
4077                            */
4078                           VariantClass newVariant;
4079                           switch(gameInfo.boardWidth) { // base guess on board width
4080                                 case 9:  newVariant = VariantShogi; break;
4081                                 case 10: newVariant = VariantGreat; break;
4082                                 default: newVariant = VariantCrazyhouse; break;
4083                           }
4084                           VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4085                           /* Get a move list just to see the header, which
4086                              will tell us whether this is really bug or zh */
4087                           if (ics_getting_history == H_FALSE) {
4088                             ics_getting_history = H_REQUESTED;
4089                             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4090                             SendToICS(str);
4091                           }
4092                         }
4093                         new_piece[0] = NULLCHAR;
4094                         sscanf(parse, "game %d white [%s black [%s <- %s",
4095                                &gamenum, white_holding, black_holding,
4096                                new_piece);
4097                         white_holding[strlen(white_holding)-1] = NULLCHAR;
4098                         black_holding[strlen(black_holding)-1] = NULLCHAR;
4099                         /* [HGM] copy holdings to board holdings area */
4100                         CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4101                         CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4102                         boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4103 #if ZIPPY
4104                         if (appData.zippyPlay && first.initDone) {
4105                             ZippyHoldings(white_holding, black_holding,
4106                                           new_piece);
4107                         }
4108 #endif /*ZIPPY*/
4109                         if (tinyLayout || smallLayout) {
4110                             char wh[16], bh[16];
4111                             PackHolding(wh, white_holding);
4112                             PackHolding(bh, black_holding);
4113                             snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4114                                     gameInfo.white, gameInfo.black);
4115                         } else {
4116                           snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4117                                     gameInfo.white, white_holding, _("vs."),
4118                                     gameInfo.black, black_holding);
4119                         }
4120                         if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4121                         DrawPosition(FALSE, boards[currentMove]);
4122                         DisplayTitle(str);
4123                       } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4124                         sscanf(parse, "game %d white [%s black [%s <- %s",
4125                                &gamenum, white_holding, black_holding,
4126                                new_piece);
4127                         white_holding[strlen(white_holding)-1] = NULLCHAR;
4128                         black_holding[strlen(black_holding)-1] = NULLCHAR;
4129                         /* [HGM] copy holdings to partner-board holdings area */
4130                         CopyHoldings(partnerBoard, white_holding, WhitePawn);
4131                         CopyHoldings(partnerBoard, black_holding, BlackPawn);
4132                         if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4133                         if(partnerUp) DrawPosition(FALSE, partnerBoard);
4134                         if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4135                       }
4136                     }
4137                     /* Suppress following prompt */
4138                     if (looking_at(buf, &i, "*% ")) {
4139                         if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4140                         savingComment = FALSE;
4141                         suppressKibitz = 0;
4142                     }
4143                     next_out = i;
4144                 }
4145                 continue;
4146             }
4147
4148             i++;                /* skip unparsed character and loop back */
4149         }
4150
4151         if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4152 //          started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4153 //          SendToPlayer(&buf[next_out], i - next_out);
4154             started != STARTED_HOLDINGS && leftover_start > next_out) {
4155             SendToPlayer(&buf[next_out], leftover_start - next_out);
4156             next_out = i;
4157         }
4158
4159         leftover_len = buf_len - leftover_start;
4160         /* if buffer ends with something we couldn't parse,
4161            reparse it after appending the next read */
4162
4163     } else if (count == 0) {
4164         RemoveInputSource(isr);
4165         DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4166     } else {
4167         DisplayFatalError(_("Error reading from ICS"), error, 1);
4168     }
4169 }
4170
4171
4172 /* Board style 12 looks like this:
4173
4174    <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
4175
4176  * The "<12> " is stripped before it gets to this routine.  The two
4177  * trailing 0's (flip state and clock ticking) are later addition, and
4178  * some chess servers may not have them, or may have only the first.
4179  * Additional trailing fields may be added in the future.
4180  */
4181
4182 #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"
4183
4184 #define RELATION_OBSERVING_PLAYED    0
4185 #define RELATION_OBSERVING_STATIC   -2   /* examined, oldmoves, or smoves */
4186 #define RELATION_PLAYING_MYMOVE      1
4187 #define RELATION_PLAYING_NOTMYMOVE  -1
4188 #define RELATION_EXAMINING           2
4189 #define RELATION_ISOLATED_BOARD     -3
4190 #define RELATION_STARTING_POSITION  -4   /* FICS only */
4191
4192 void
4193 ParseBoard12 (char *string)
4194 {
4195 #if ZIPPY
4196     int i, takeback;
4197     char *bookHit = NULL; // [HGM] book
4198 #endif
4199     GameMode newGameMode;
4200     int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
4201     int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
4202     int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4203     char to_play, board_chars[200];
4204     char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4205     char black[32], white[32];
4206     Board board;
4207     int prevMove = currentMove;
4208     int ticking = 2;
4209     ChessMove moveType;
4210     int fromX, fromY, toX, toY;
4211     char promoChar;
4212     int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4213     Boolean weird = FALSE, reqFlag = FALSE;
4214
4215     fromX = fromY = toX = toY = -1;
4216
4217     newGame = FALSE;
4218
4219     if (appData.debugMode)
4220       fprintf(debugFP, "Parsing board: %s\n", string);
4221
4222     move_str[0] = NULLCHAR;
4223     elapsed_time[0] = NULLCHAR;
4224     {   /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4225         int  i = 0, j;
4226         while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4227             if(string[i] == ' ') { ranks++; files = 0; }
4228             else files++;
4229             if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4230             i++;
4231         }
4232         for(j = 0; j <i; j++) board_chars[j] = string[j];
4233         board_chars[i] = '\0';
4234         string += i + 1;
4235     }
4236     n = sscanf(string, PATTERN, &to_play, &double_push,
4237                &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4238                &gamenum, white, black, &relation, &basetime, &increment,
4239                &white_stren, &black_stren, &white_time, &black_time,
4240                &moveNum, str, elapsed_time, move_str, &ics_flip,
4241                &ticking);
4242
4243     if (n < 21) {
4244         snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4245         DisplayError(str, 0);
4246         return;
4247     }
4248
4249     /* Convert the move number to internal form */
4250     moveNum = (moveNum - 1) * 2;
4251     if (to_play == 'B') moveNum++;
4252     if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4253       DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4254                         0, 1);
4255       return;
4256     }
4257
4258     switch (relation) {
4259       case RELATION_OBSERVING_PLAYED:
4260       case RELATION_OBSERVING_STATIC:
4261         if (gamenum == -1) {
4262             /* Old ICC buglet */
4263             relation = RELATION_OBSERVING_STATIC;
4264         }
4265         newGameMode = IcsObserving;
4266         break;
4267       case RELATION_PLAYING_MYMOVE:
4268       case RELATION_PLAYING_NOTMYMOVE:
4269         newGameMode =
4270           ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4271             IcsPlayingWhite : IcsPlayingBlack;
4272         soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4273         break;
4274       case RELATION_EXAMINING:
4275         newGameMode = IcsExamining;
4276         break;
4277       case RELATION_ISOLATED_BOARD:
4278       default:
4279         /* Just display this board.  If user was doing something else,
4280            we will forget about it until the next board comes. */
4281         newGameMode = IcsIdle;
4282         break;
4283       case RELATION_STARTING_POSITION:
4284         newGameMode = gameMode;
4285         break;
4286     }
4287
4288     if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4289         gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4290          && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4291       // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4292       int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4293       static int lastBgGame = -1;
4294       char *toSqr;
4295       for (k = 0; k < ranks; k++) {
4296         for (j = 0; j < files; j++)
4297           board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4298         if(gameInfo.holdingsWidth > 1) {
4299              board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4300              board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4301         }
4302       }
4303       CopyBoard(partnerBoard, board);
4304       if(toSqr = strchr(str, '/')) { // extract highlights from long move
4305         partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4306         partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4307       } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4308       if(toSqr = strchr(str, '-')) {
4309         partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4310         partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4311       } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4312       if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4313       if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4314       if(partnerUp) DrawPosition(FALSE, partnerBoard);
4315       if(twoBoards) {
4316           DisplayWhiteClock(white_time*fac, to_play == 'W');
4317           DisplayBlackClock(black_time*fac, to_play != 'W');
4318           activePartner = to_play;
4319           if(gamenum != lastBgGame) {
4320               char buf[MSG_SIZ];
4321               snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4322               DisplayTitle(buf);
4323           }
4324           lastBgGame = gamenum;
4325           activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4326                       partnerUp = 0; flipView = !flipView; } // [HGM] dual
4327       snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4328                  (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4329       if(!twoBoards) DisplayMessage(partnerStatus, "");
4330         partnerBoardValid = TRUE;
4331       return;
4332     }
4333
4334     if(appData.dualBoard && appData.bgObserve) {
4335         if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4336             SendToICS(ics_prefix), SendToICS("pobserve\n");
4337         else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4338             char buf[MSG_SIZ];
4339             snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4340             SendToICS(buf);
4341         }
4342     }
4343
4344     /* Modify behavior for initial board display on move listing
4345        of wild games.
4346        */
4347     switch (ics_getting_history) {
4348       case H_FALSE:
4349       case H_REQUESTED:
4350         break;
4351       case H_GOT_REQ_HEADER:
4352       case H_GOT_UNREQ_HEADER:
4353         /* This is the initial position of the current game */
4354         gamenum = ics_gamenum;
4355         moveNum = 0;            /* old ICS bug workaround */
4356         if (to_play == 'B') {
4357           startedFromSetupPosition = TRUE;
4358           blackPlaysFirst = TRUE;
4359           moveNum = 1;
4360           if (forwardMostMove == 0) forwardMostMove = 1;
4361           if (backwardMostMove == 0) backwardMostMove = 1;
4362           if (currentMove == 0) currentMove = 1;
4363         }
4364         newGameMode = gameMode;
4365         relation = RELATION_STARTING_POSITION; /* ICC needs this */
4366         break;
4367       case H_GOT_UNWANTED_HEADER:
4368         /* This is an initial board that we don't want */
4369         return;
4370       case H_GETTING_MOVES:
4371         /* Should not happen */
4372         DisplayError(_("Error gathering move list: extra board"), 0);
4373         ics_getting_history = H_FALSE;
4374         return;
4375     }
4376
4377    if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4378                                         move_str[1] == '@' && !gameInfo.holdingsWidth ||
4379                                         weird && (int)gameInfo.variant < (int)VariantShogi) {
4380      /* [HGM] We seem to have switched variant unexpectedly
4381       * Try to guess new variant from board size
4382       */
4383           VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4384           if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4385           if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4386           if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4387           if(ranks == 9 && files == 9)  newVariant = VariantShogi; else
4388           if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4389           if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4390           VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4391           /* Get a move list just to see the header, which
4392              will tell us whether this is really bug or zh */
4393           if (ics_getting_history == H_FALSE) {
4394             ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4395             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4396             SendToICS(str);
4397           }
4398     }
4399
4400     /* Take action if this is the first board of a new game, or of a
4401        different game than is currently being displayed.  */
4402     if (gamenum != ics_gamenum || newGameMode != gameMode ||
4403         relation == RELATION_ISOLATED_BOARD) {
4404
4405         /* Forget the old game and get the history (if any) of the new one */
4406         if (gameMode != BeginningOfGame) {
4407           Reset(TRUE, TRUE);
4408         }
4409         newGame = TRUE;
4410         if (appData.autoRaiseBoard) BoardToTop();
4411         prevMove = -3;
4412         if (gamenum == -1) {
4413             newGameMode = IcsIdle;
4414         } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4415                    appData.getMoveList && !reqFlag) {
4416             /* Need to get game history */
4417             ics_getting_history = H_REQUESTED;
4418             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4419             SendToICS(str);
4420         }
4421
4422         /* Initially flip the board to have black on the bottom if playing
4423            black or if the ICS flip flag is set, but let the user change
4424            it with the Flip View button. */
4425         flipView = appData.autoFlipView ?
4426           (newGameMode == IcsPlayingBlack) || ics_flip :
4427           appData.flipView;
4428
4429         /* Done with values from previous mode; copy in new ones */
4430         gameMode = newGameMode;
4431         ModeHighlight();
4432         ics_gamenum = gamenum;
4433         if (gamenum == gs_gamenum) {
4434             int klen = strlen(gs_kind);
4435             if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4436             snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4437             gameInfo.event = StrSave(str);
4438         } else {
4439             gameInfo.event = StrSave("ICS game");
4440         }
4441         gameInfo.site = StrSave(appData.icsHost);
4442         gameInfo.date = PGNDate();
4443         gameInfo.round = StrSave("-");
4444         gameInfo.white = StrSave(white);
4445         gameInfo.black = StrSave(black);
4446         timeControl = basetime * 60 * 1000;
4447         timeControl_2 = 0;
4448         timeIncrement = increment * 1000;
4449         movesPerSession = 0;
4450         gameInfo.timeControl = TimeControlTagValue();
4451         VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4452   if (appData.debugMode) {
4453     fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4454     fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4455     setbuf(debugFP, NULL);
4456   }
4457
4458         gameInfo.outOfBook = NULL;
4459
4460         /* Do we have the ratings? */
4461         if (strcmp(player1Name, white) == 0 &&
4462             strcmp(player2Name, black) == 0) {
4463             if (appData.debugMode)
4464               fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4465                       player1Rating, player2Rating);
4466             gameInfo.whiteRating = player1Rating;
4467             gameInfo.blackRating = player2Rating;
4468         } else if (strcmp(player2Name, white) == 0 &&
4469                    strcmp(player1Name, black) == 0) {
4470             if (appData.debugMode)
4471               fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4472                       player2Rating, player1Rating);
4473             gameInfo.whiteRating = player2Rating;
4474             gameInfo.blackRating = player1Rating;
4475         }
4476         player1Name[0] = player2Name[0] = NULLCHAR;
4477
4478         /* Silence shouts if requested */
4479         if (appData.quietPlay &&
4480             (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4481             SendToICS(ics_prefix);
4482             SendToICS("set shout 0\n");
4483         }
4484     }
4485
4486     /* Deal with midgame name changes */
4487     if (!newGame) {
4488         if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4489             if (gameInfo.white) free(gameInfo.white);
4490             gameInfo.white = StrSave(white);
4491         }
4492         if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4493             if (gameInfo.black) free(gameInfo.black);
4494             gameInfo.black = StrSave(black);
4495         }
4496     }
4497
4498     /* Throw away game result if anything actually changes in examine mode */
4499     if (gameMode == IcsExamining && !newGame) {
4500         gameInfo.result = GameUnfinished;
4501         if (gameInfo.resultDetails != NULL) {
4502             free(gameInfo.resultDetails);
4503             gameInfo.resultDetails = NULL;
4504         }
4505     }
4506
4507     /* In pausing && IcsExamining mode, we ignore boards coming
4508        in if they are in a different variation than we are. */
4509     if (pauseExamInvalid) return;
4510     if (pausing && gameMode == IcsExamining) {
4511         if (moveNum <= pauseExamForwardMostMove) {
4512             pauseExamInvalid = TRUE;
4513             forwardMostMove = pauseExamForwardMostMove;
4514             return;
4515         }
4516     }
4517
4518   if (appData.debugMode) {
4519     fprintf(debugFP, "load %dx%d board\n", files, ranks);
4520   }
4521     /* Parse the board */
4522     for (k = 0; k < ranks; k++) {
4523       for (j = 0; j < files; j++)
4524         board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4525       if(gameInfo.holdingsWidth > 1) {
4526            board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4527            board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4528       }
4529     }
4530     if(moveNum==0 && gameInfo.variant == VariantSChess) {
4531       board[5][BOARD_RGHT+1] = WhiteAngel;
4532       board[6][BOARD_RGHT+1] = WhiteMarshall;
4533       board[1][0] = BlackMarshall;
4534       board[2][0] = BlackAngel;
4535       board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4536     }
4537     CopyBoard(boards[moveNum], board);
4538     boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4539     if (moveNum == 0) {
4540         startedFromSetupPosition =
4541           !CompareBoards(board, initialPosition);
4542         if(startedFromSetupPosition)
4543             initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4544     }
4545
4546     /* [HGM] Set castling rights. Take the outermost Rooks,
4547        to make it also work for FRC opening positions. Note that board12
4548        is really defective for later FRC positions, as it has no way to
4549        indicate which Rook can castle if they are on the same side of King.
4550        For the initial position we grant rights to the outermost Rooks,
4551        and remember thos rights, and we then copy them on positions
4552        later in an FRC game. This means WB might not recognize castlings with
4553        Rooks that have moved back to their original position as illegal,
4554        but in ICS mode that is not its job anyway.
4555     */
4556     if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4557     { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4558
4559         for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4560             if(board[0][i] == WhiteRook) j = i;
4561         initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4562         for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4563             if(board[0][i] == WhiteRook) j = i;
4564         initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4565         for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4566             if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4567         initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4568         for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4569             if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4570         initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4571
4572         boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4573         if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4574         for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4575             if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4576         for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4577             if(board[BOARD_HEIGHT-1][k] == bKing)
4578                 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4579         if(gameInfo.variant == VariantTwoKings) {
4580             // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4581             if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4582             if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4583         }
4584     } else { int r;
4585         r = boards[moveNum][CASTLING][0] = initialRights[0];
4586         if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4587         r = boards[moveNum][CASTLING][1] = initialRights[1];
4588         if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4589         r = boards[moveNum][CASTLING][3] = initialRights[3];
4590         if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4591         r = boards[moveNum][CASTLING][4] = initialRights[4];
4592         if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4593         /* wildcastle kludge: always assume King has rights */
4594         r = boards[moveNum][CASTLING][2] = initialRights[2];
4595         r = boards[moveNum][CASTLING][5] = initialRights[5];
4596     }
4597     /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4598     boards[moveNum][EP_STATUS] = EP_NONE;
4599     if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4600     if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4601     if(double_push !=  -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4602
4603
4604     if (ics_getting_history == H_GOT_REQ_HEADER ||
4605         ics_getting_history == H_GOT_UNREQ_HEADER) {
4606         /* This was an initial position from a move list, not
4607            the current position */
4608         return;
4609     }
4610
4611     /* Update currentMove and known move number limits */
4612     newMove = newGame || moveNum > forwardMostMove;
4613
4614     if (newGame) {
4615         forwardMostMove = backwardMostMove = currentMove = moveNum;
4616         if (gameMode == IcsExamining && moveNum == 0) {
4617           /* Workaround for ICS limitation: we are not told the wild
4618              type when starting to examine a game.  But if we ask for
4619              the move list, the move list header will tell us */
4620             ics_getting_history = H_REQUESTED;
4621             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4622             SendToICS(str);
4623         }
4624     } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4625                || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4626 #if ZIPPY
4627         /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4628         /* [HGM] applied this also to an engine that is silently watching        */
4629         if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4630             (gameMode == IcsObserving || gameMode == IcsExamining) &&
4631             gameInfo.variant == currentlyInitializedVariant) {
4632           takeback = forwardMostMove - moveNum;
4633           for (i = 0; i < takeback; i++) {
4634             if (appData.debugMode) fprintf(debugFP, "take back move\n");
4635             SendToProgram("undo\n", &first);
4636           }
4637         }
4638 #endif
4639
4640         forwardMostMove = moveNum;
4641         if (!pausing || currentMove > forwardMostMove)
4642           currentMove = forwardMostMove;
4643     } else {
4644         /* New part of history that is not contiguous with old part */
4645         if (pausing && gameMode == IcsExamining) {
4646             pauseExamInvalid = TRUE;
4647             forwardMostMove = pauseExamForwardMostMove;
4648             return;
4649         }
4650         if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4651 #if ZIPPY
4652             if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4653                 // [HGM] when we will receive the move list we now request, it will be
4654                 // fed to the engine from the first move on. So if the engine is not
4655                 // in the initial position now, bring it there.
4656                 InitChessProgram(&first, 0);
4657             }
4658 #endif
4659             ics_getting_history = H_REQUESTED;
4660             snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4661             SendToICS(str);
4662         }
4663         forwardMostMove = backwardMostMove = currentMove = moveNum;
4664     }
4665
4666     /* Update the clocks */
4667     if (strchr(elapsed_time, '.')) {
4668       /* Time is in ms */
4669       timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4670       timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4671     } else {
4672       /* Time is in seconds */
4673       timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4674       timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4675     }
4676
4677
4678 #if ZIPPY
4679     if (appData.zippyPlay && newGame &&
4680         gameMode != IcsObserving && gameMode != IcsIdle &&
4681         gameMode != IcsExamining)
4682       ZippyFirstBoard(moveNum, basetime, increment);
4683 #endif
4684
4685     /* Put the move on the move list, first converting
4686        to canonical algebraic form. */
4687     if (moveNum > 0) {
4688   if (appData.debugMode) {
4689     int f = forwardMostMove;
4690     fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4691             boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4692             boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4693     fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4694     fprintf(debugFP, "moveNum = %d\n", moveNum);
4695     fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4696     setbuf(debugFP, NULL);
4697   }
4698         if (moveNum <= backwardMostMove) {
4699             /* We don't know what the board looked like before
4700                this move.  Punt. */
4701           safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4702             strcat(parseList[moveNum - 1], " ");
4703             strcat(parseList[moveNum - 1], elapsed_time);
4704             moveList[moveNum - 1][0] = NULLCHAR;
4705         } else if (strcmp(move_str, "none") == 0) {
4706             // [HGM] long SAN: swapped order; test for 'none' before parsing move
4707             /* Again, we don't know what the board looked like;
4708                this is really the start of the game. */
4709             parseList[moveNum - 1][0] = NULLCHAR;
4710             moveList[moveNum - 1][0] = NULLCHAR;
4711             backwardMostMove = moveNum;
4712             startedFromSetupPosition = TRUE;
4713             fromX = fromY = toX = toY = -1;
4714         } else {
4715           // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4716           //                 So we parse the long-algebraic move string in stead of the SAN move
4717           int valid; char buf[MSG_SIZ], *prom;
4718
4719           if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4720                 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4721           // str looks something like "Q/a1-a2"; kill the slash
4722           if(str[1] == '/')
4723             snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4724           else  safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4725           if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4726                 strcat(buf, prom); // long move lacks promo specification!
4727           if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4728                 if(appData.debugMode)
4729                         fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4730                 safeStrCpy(move_str, buf, MSG_SIZ);
4731           }
4732           valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4733                                 &fromX, &fromY, &toX, &toY, &promoChar)
4734                || ParseOneMove(buf, moveNum - 1, &moveType,
4735                                 &fromX, &fromY, &toX, &toY, &promoChar);
4736           // end of long SAN patch
4737           if (valid) {
4738             (void) CoordsToAlgebraic(boards[moveNum - 1],
4739                                      PosFlags(moveNum - 1),
4740                                      fromY, fromX, toY, toX, promoChar,
4741                                      parseList[moveNum-1]);
4742             switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4743               case MT_NONE:
4744               case MT_STALEMATE:
4745               default:
4746                 break;
4747               case MT_CHECK:
4748                 if(gameInfo.variant != VariantShogi)
4749                     strcat(parseList[moveNum - 1], "+");
4750                 break;
4751               case MT_CHECKMATE:
4752               case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4753                 strcat(parseList[moveNum - 1], "#");
4754                 break;
4755             }
4756             strcat(parseList[moveNum - 1], " ");
4757             strcat(parseList[moveNum - 1], elapsed_time);
4758             /* currentMoveString is set as a side-effect of ParseOneMove */
4759             if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4760             safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4761             strcat(moveList[moveNum - 1], "\n");
4762
4763             if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4764                && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4765               for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4766                 ChessSquare old, new = boards[moveNum][k][j];
4767                   if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4768                   old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4769                   if(old == new) continue;
4770                   if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4771                   else if(new == WhiteWazir || new == BlackWazir) {
4772                       if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4773                            boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4774                       else boards[moveNum][k][j] = old; // preserve type of Gold
4775                   } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4776                       boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4777               }
4778           } else {
4779             /* Move from ICS was illegal!?  Punt. */
4780             if (appData.debugMode) {
4781               fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4782               fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4783             }
4784             safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4785             strcat(parseList[moveNum - 1], " ");
4786             strcat(parseList[moveNum - 1], elapsed_time);
4787             moveList[moveNum - 1][0] = NULLCHAR;
4788             fromX = fromY = toX = toY = -1;
4789           }
4790         }
4791   if (appData.debugMode) {
4792     fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4793     setbuf(debugFP, NULL);
4794   }
4795
4796 #if ZIPPY
4797         /* Send move to chess program (BEFORE animating it). */
4798         if (appData.zippyPlay && !newGame && newMove &&
4799            (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4800
4801             if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4802                 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4803                 if (moveList[moveNum - 1][0] == NULLCHAR) {
4804                   snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4805                             move_str);
4806                     DisplayError(str, 0);
4807                 } else {
4808                     if (first.sendTime) {
4809                         SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4810                     }
4811                     bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4812                     if (firstMove && !bookHit) {
4813                         firstMove = FALSE;
4814                         if (first.useColors) {
4815                           SendToProgram(gameMode == IcsPlayingWhite ?
4816                                         "white\ngo\n" :
4817                                         "black\ngo\n", &first);
4818                         } else {
4819                           SendToProgram("go\n", &first);
4820                         }
4821                         first.maybeThinking = TRUE;
4822                     }
4823                 }
4824             } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4825               if (moveList[moveNum - 1][0] == NULLCHAR) {
4826                 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4827                 DisplayError(str, 0);
4828               } else {
4829                 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4830                 SendMoveToProgram(moveNum - 1, &first);
4831               }
4832             }
4833         }
4834 #endif
4835     }
4836
4837     if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4838         /* If move comes from a remote source, animate it.  If it
4839            isn't remote, it will have already been animated. */
4840         if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4841             AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4842         }
4843         if (!pausing && appData.highlightLastMove) {
4844             SetHighlights(fromX, fromY, toX, toY);
4845         }
4846     }
4847
4848     /* Start the clocks */
4849     whiteFlag = blackFlag = FALSE;
4850     appData.clockMode = !(basetime == 0 && increment == 0);
4851     if (ticking == 0) {
4852       ics_clock_paused = TRUE;
4853       StopClocks();
4854     } else if (ticking == 1) {
4855       ics_clock_paused = FALSE;
4856     }
4857     if (gameMode == IcsIdle ||
4858         relation == RELATION_OBSERVING_STATIC ||
4859         relation == RELATION_EXAMINING ||
4860         ics_clock_paused)
4861       DisplayBothClocks();
4862     else
4863       StartClocks();
4864
4865     /* Display opponents and material strengths */
4866     if (gameInfo.variant != VariantBughouse &&
4867         gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4868         if (tinyLayout || smallLayout) {
4869             if(gameInfo.variant == VariantNormal)
4870               snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4871                     gameInfo.white, white_stren, gameInfo.black, black_stren,
4872                     basetime, increment);
4873             else
4874               snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4875                     gameInfo.white, white_stren, gameInfo.black, black_stren,
4876                     basetime, increment, (int) gameInfo.variant);
4877         } else {
4878             if(gameInfo.variant == VariantNormal)
4879               snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
4880                     gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4881                     basetime, increment);
4882             else
4883               snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
4884                     gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4885                     basetime, increment, VariantName(gameInfo.variant));
4886         }
4887         DisplayTitle(str);
4888   if (appData.debugMode) {
4889     fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4890   }
4891     }
4892
4893
4894     /* Display the board */
4895     if (!pausing && !appData.noGUI) {
4896
4897       if (appData.premove)
4898           if (!gotPremove ||
4899              ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4900              ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4901               ClearPremoveHighlights();
4902
4903       j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4904         if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4905       DrawPosition(j, boards[currentMove]);
4906
4907       DisplayMove(moveNum - 1);
4908       if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4909             !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4910               (gameMode == IcsPlayingBlack) &&  (WhiteOnMove(moveNum))   ) ) {
4911         if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4912       }
4913     }
4914
4915     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4916 #if ZIPPY
4917     if(bookHit) { // [HGM] book: simulate book reply
4918         static char bookMove[MSG_SIZ]; // a bit generous?
4919
4920         programStats.nodes = programStats.depth = programStats.time =
4921         programStats.score = programStats.got_only_move = 0;
4922         sprintf(programStats.movelist, "%s (xbook)", bookHit);
4923
4924         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4925         strcat(bookMove, bookHit);
4926         HandleMachineMove(bookMove, &first);
4927     }
4928 #endif
4929 }
4930
4931 void
4932 GetMoveListEvent ()
4933 {
4934     char buf[MSG_SIZ];
4935     if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4936         ics_getting_history = H_REQUESTED;
4937         snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4938         SendToICS(buf);
4939     }
4940 }
4941
4942 void
4943 SendToBoth (char *msg)
4944 {   // to make it easy to keep two engines in step in dual analysis
4945     SendToProgram(msg, &first);
4946     if(second.analyzing) SendToProgram(msg, &second);
4947 }
4948
4949 void
4950 AnalysisPeriodicEvent (int force)
4951 {
4952     if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4953          && !force) || !appData.periodicUpdates)
4954       return;
4955
4956     /* Send . command to Crafty to collect stats */
4957     SendToBoth(".\n");
4958
4959     /* Don't send another until we get a response (this makes
4960        us stop sending to old Crafty's which don't understand
4961        the "." command (sending illegal cmds resets node count & time,
4962        which looks bad)) */
4963     programStats.ok_to_send = 0;
4964 }
4965
4966 void
4967 ics_update_width (int new_width)
4968 {
4969         ics_printf("set width %d\n", new_width);
4970 }
4971
4972 void
4973 SendMoveToProgram (int moveNum, ChessProgramState *cps)
4974 {
4975     char buf[MSG_SIZ];
4976
4977     if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
4978         // null move in variant where engine does not understand it (for analysis purposes)
4979         SendBoard(cps, moveNum + 1); // send position after move in stead.
4980         return;
4981     }
4982     if (cps->useUsermove) {
4983       SendToProgram("usermove ", cps);
4984     }
4985     if (cps->useSAN) {
4986       char *space;
4987       if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4988         int len = space - parseList[moveNum];
4989         memcpy(buf, parseList[moveNum], len);
4990         buf[len++] = '\n';
4991         buf[len] = NULLCHAR;
4992       } else {
4993         snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4994       }
4995       SendToProgram(buf, cps);
4996     } else {
4997       if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4998         AlphaRank(moveList[moveNum], 4);
4999         SendToProgram(moveList[moveNum], cps);
5000         AlphaRank(moveList[moveNum], 4); // and back
5001       } else
5002       /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
5003        * the engine. It would be nice to have a better way to identify castle
5004        * moves here. */
5005       if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
5006                                                                          && cps->useOOCastle) {
5007         int fromX = moveList[moveNum][0] - AAA;
5008         int fromY = moveList[moveNum][1] - ONE;
5009         int toX = moveList[moveNum][2] - AAA;
5010         int toY = moveList[moveNum][3] - ONE;
5011         if((boards[moveNum][fromY][fromX] == WhiteKing
5012             && boards[moveNum][toY][toX] == WhiteRook)
5013            || (boards[moveNum][fromY][fromX] == BlackKing
5014                && boards[moveNum][toY][toX] == BlackRook)) {
5015           if(toX > fromX) SendToProgram("O-O\n", cps);
5016           else SendToProgram("O-O-O\n", cps);
5017         }
5018         else SendToProgram(moveList[moveNum], cps);
5019       } else
5020       if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
5021         if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
5022           if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
5023           snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
5024                                               moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5025         } else
5026           snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
5027                                                moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5028         SendToProgram(buf, cps);
5029       }
5030       else SendToProgram(moveList[moveNum], cps);
5031       /* End of additions by Tord */
5032     }
5033
5034     /* [HGM] setting up the opening has brought engine in force mode! */
5035     /*       Send 'go' if we are in a mode where machine should play. */
5036     if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
5037         (gameMode == TwoMachinesPlay   ||
5038 #if ZIPPY
5039          gameMode == IcsPlayingBlack     || gameMode == IcsPlayingWhite ||
5040 #endif
5041          gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5042         SendToProgram("go\n", cps);
5043   if (appData.debugMode) {
5044     fprintf(debugFP, "(extra)\n");
5045   }
5046     }
5047     setboardSpoiledMachineBlack = 0;
5048 }
5049
5050 void
5051 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5052 {
5053     char user_move[MSG_SIZ];
5054     char suffix[4];
5055
5056     if(gameInfo.variant == VariantSChess && promoChar) {
5057         snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5058         if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5059     } else suffix[0] = NULLCHAR;
5060
5061     switch (moveType) {
5062       default:
5063         snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5064                 (int)moveType, fromX, fromY, toX, toY);
5065         DisplayError(user_move + strlen("say "), 0);
5066         break;
5067       case WhiteKingSideCastle:
5068       case BlackKingSideCastle:
5069       case WhiteQueenSideCastleWild:
5070       case BlackQueenSideCastleWild:
5071       /* PUSH Fabien */
5072       case WhiteHSideCastleFR:
5073       case BlackHSideCastleFR:
5074       /* POP Fabien */
5075         snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5076         break;
5077       case WhiteQueenSideCastle:
5078       case BlackQueenSideCastle:
5079       case WhiteKingSideCastleWild:
5080       case BlackKingSideCastleWild:
5081       /* PUSH Fabien */
5082       case WhiteASideCastleFR:
5083       case BlackASideCastleFR:
5084       /* POP Fabien */
5085         snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5086         break;
5087       case WhiteNonPromotion:
5088       case BlackNonPromotion:
5089         sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5090         break;
5091       case WhitePromotion:
5092       case BlackPromotion:
5093         if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5094           snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5095                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5096                 PieceToChar(WhiteFerz));
5097         else if(gameInfo.variant == VariantGreat)
5098           snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5099                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5100                 PieceToChar(WhiteMan));
5101         else
5102           snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5103                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5104                 promoChar);
5105         break;
5106       case WhiteDrop:
5107       case BlackDrop:
5108       drop:
5109         snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5110                  ToUpper(PieceToChar((ChessSquare) fromX)),
5111                  AAA + toX, ONE + toY);
5112         break;
5113       case IllegalMove:  /* could be a variant we don't quite understand */
5114         if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5115       case NormalMove:
5116       case WhiteCapturesEnPassant:
5117       case BlackCapturesEnPassant:
5118         snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5119                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5120         break;
5121     }
5122     SendToICS(user_move);
5123     if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5124         ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5125 }
5126
5127 void
5128 UploadGameEvent ()
5129 {   // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5130     int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5131     static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5132     if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5133       DisplayError(_("You cannot do this while you are playing or observing"), 0);
5134       return;
5135     }
5136     if(gameMode != IcsExamining) { // is this ever not the case?
5137         char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5138
5139         if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5140           snprintf(command,MSG_SIZ, "match %s", ics_handle);
5141         } else { // on FICS we must first go to general examine mode
5142           safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5143         }
5144         if(gameInfo.variant != VariantNormal) {
5145             // try figure out wild number, as xboard names are not always valid on ICS
5146             for(i=1; i<=36; i++) {
5147               snprintf(buf, MSG_SIZ, "wild/%d", i);
5148                 if(StringToVariant(buf) == gameInfo.variant) break;
5149             }
5150             if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5151             else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5152             else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5153         } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5154         SendToICS(ics_prefix);
5155         SendToICS(buf);
5156         if(startedFromSetupPosition || backwardMostMove != 0) {
5157           fen = PositionToFEN(backwardMostMove, NULL);
5158           if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5159             snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5160             SendToICS(buf);
5161           } else { // FICS: everything has to set by separate bsetup commands
5162             p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5163             snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5164             SendToICS(buf);
5165             if(!WhiteOnMove(backwardMostMove)) {
5166                 SendToICS("bsetup tomove black\n");
5167             }
5168             i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5169             snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5170             SendToICS(buf);
5171             i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5172             snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5173             SendToICS(buf);
5174             i = boards[backwardMostMove][EP_STATUS];
5175             if(i >= 0) { // set e.p.
5176               snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5177                 SendToICS(buf);
5178             }
5179             bsetup++;
5180           }
5181         }
5182       if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5183             SendToICS("bsetup done\n"); // switch to normal examining.
5184     }
5185     for(i = backwardMostMove; i<last; i++) {
5186         char buf[20];
5187         snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5188         if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5189             int len = strlen(moveList[i]);
5190             snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5191             if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5192         }
5193         SendToICS(buf);
5194     }
5195     SendToICS(ics_prefix);
5196     SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5197 }
5198
5199 void
5200 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[7])
5201 {
5202     if (rf == DROP_RANK) {
5203       if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5204       sprintf(move, "%c@%c%c\n",
5205                 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5206     } else {
5207         if (promoChar == 'x' || promoChar == NULLCHAR) {
5208           sprintf(move, "%c%c%c%c\n",
5209                     AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5210         } else {
5211             sprintf(move, "%c%c%c%c%c\n",
5212                     AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5213         }
5214     }
5215 }
5216
5217 void
5218 ProcessICSInitScript (FILE *f)
5219 {
5220     char buf[MSG_SIZ];
5221
5222     while (fgets(buf, MSG_SIZ, f)) {
5223         SendToICSDelayed(buf,(long)appData.msLoginDelay);
5224     }
5225
5226     fclose(f);
5227 }
5228
5229
5230 static int lastX, lastY, selectFlag, dragging;
5231
5232 void
5233 Sweep (int step)
5234 {
5235     ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5236     if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5237     if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5238     if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5239     if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5240     if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
5241     do {
5242         promoSweep -= step;
5243         if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5244         else if((int)promoSweep == -1) promoSweep = WhiteKing;
5245         else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5246         else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5247         if(!step) step = -1;
5248     } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5249             appData.testLegality && (promoSweep == king ||
5250             gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
5251     if(toX >= 0) {
5252         int victim = boards[currentMove][toY][toX];
5253         boards[currentMove][toY][toX] = promoSweep;
5254         DrawPosition(FALSE, boards[currentMove]);
5255         boards[currentMove][toY][toX] = victim;
5256     } else
5257     ChangeDragPiece(promoSweep);
5258 }
5259
5260 int
5261 PromoScroll (int x, int y)
5262 {
5263   int step = 0;
5264
5265   if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5266   if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5267   if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5268   if(!step) return FALSE;
5269   lastX = x; lastY = y;
5270   if((promoSweep < BlackPawn) == flipView) step = -step;
5271   if(step > 0) selectFlag = 1;
5272   if(!selectFlag) Sweep(step);
5273   return FALSE;
5274 }
5275
5276 void
5277 NextPiece (int step)
5278 {
5279     ChessSquare piece = boards[currentMove][toY][toX];
5280     do {
5281         pieceSweep -= step;
5282         if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5283         if((int)pieceSweep == -1) pieceSweep = BlackKing;
5284         if(!step) step = -1;
5285     } while(PieceToChar(pieceSweep) == '.');
5286     boards[currentMove][toY][toX] = pieceSweep;
5287     DrawPosition(FALSE, boards[currentMove]);
5288     boards[currentMove][toY][toX] = piece;
5289 }
5290 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5291 void
5292 AlphaRank (char *move, int n)
5293 {
5294 //    char *p = move, c; int x, y;
5295
5296     if (appData.debugMode) {
5297         fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5298     }
5299
5300     if(move[1]=='*' &&
5301        move[2]>='0' && move[2]<='9' &&
5302        move[3]>='a' && move[3]<='x'    ) {
5303         move[1] = '@';
5304         move[2] = BOARD_RGHT  -1 - (move[2]-'1') + AAA;
5305         move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5306     } else
5307     if(move[0]>='0' && move[0]<='9' &&
5308        move[1]>='a' && move[1]<='x' &&
5309        move[2]>='0' && move[2]<='9' &&
5310        move[3]>='a' && move[3]<='x'    ) {
5311         /* input move, Shogi -> normal */
5312         move[0] = BOARD_RGHT  -1 - (move[0]-'1') + AAA;
5313         move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5314         move[2] = BOARD_RGHT  -1 - (move[2]-'1') + AAA;
5315         move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5316     } else
5317     if(move[1]=='@' &&
5318        move[3]>='0' && move[3]<='9' &&
5319        move[2]>='a' && move[2]<='x'    ) {
5320         move[1] = '*';
5321         move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5322         move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5323     } else
5324     if(
5325        move[0]>='a' && move[0]<='x' &&
5326        move[3]>='0' && move[3]<='9' &&
5327        move[2]>='a' && move[2]<='x'    ) {
5328          /* output move, normal -> Shogi */
5329         move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5330         move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5331         move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5332         move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5333         if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5334     }
5335     if (appData.debugMode) {
5336         fprintf(debugFP, "   out = '%s'\n", move);
5337     }
5338 }
5339
5340 char yy_textstr[8000];
5341
5342 /* Parser for moves from gnuchess, ICS, or user typein box */
5343 Boolean
5344 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5345 {
5346     *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5347
5348     switch (*moveType) {
5349       case WhitePromotion:
5350       case BlackPromotion:
5351       case WhiteNonPromotion:
5352       case BlackNonPromotion:
5353       case NormalMove:
5354       case WhiteCapturesEnPassant:
5355       case BlackCapturesEnPassant:
5356       case WhiteKingSideCastle:
5357       case WhiteQueenSideCastle:
5358       case BlackKingSideCastle:
5359       case BlackQueenSideCastle:
5360       case WhiteKingSideCastleWild:
5361       case WhiteQueenSideCastleWild:
5362       case BlackKingSideCastleWild:
5363       case BlackQueenSideCastleWild:
5364       /* Code added by Tord: */
5365       case WhiteHSideCastleFR:
5366       case WhiteASideCastleFR:
5367       case BlackHSideCastleFR:
5368       case BlackASideCastleFR:
5369       /* End of code added by Tord */
5370       case IllegalMove:         /* bug or odd chess variant */
5371         *fromX = currentMoveString[0] - AAA;
5372         *fromY = currentMoveString[1] - ONE;
5373         *toX = currentMoveString[2] - AAA;
5374         *toY = currentMoveString[3] - ONE;
5375         *promoChar = currentMoveString[4];
5376         if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5377             *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5378     if (appData.debugMode) {
5379         fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5380     }
5381             *fromX = *fromY = *toX = *toY = 0;
5382             return FALSE;
5383         }
5384         if (appData.testLegality) {
5385           return (*moveType != IllegalMove);
5386         } else {
5387           return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5388                         WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5389         }
5390
5391       case WhiteDrop:
5392       case BlackDrop:
5393         *fromX = *moveType == WhiteDrop ?
5394           (int) CharToPiece(ToUpper(currentMoveString[0])) :
5395           (int) CharToPiece(ToLower(currentMoveString[0]));
5396         *fromY = DROP_RANK;
5397         *toX = currentMoveString[2] - AAA;
5398         *toY = currentMoveString[3] - ONE;
5399         *promoChar = NULLCHAR;
5400         return TRUE;
5401
5402       case AmbiguousMove:
5403       case ImpossibleMove:
5404       case EndOfFile:
5405       case ElapsedTime:
5406       case Comment:
5407       case PGNTag:
5408       case NAG:
5409       case WhiteWins:
5410       case BlackWins:
5411       case GameIsDrawn:
5412       default:
5413     if (appData.debugMode) {
5414         fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5415     }
5416         /* bug? */
5417         *fromX = *fromY = *toX = *toY = 0;
5418         *promoChar = NULLCHAR;
5419         return FALSE;
5420     }
5421 }
5422
5423 Boolean pushed = FALSE;
5424 char *lastParseAttempt;
5425
5426 void
5427 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5428 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5429   int fromX, fromY, toX, toY; char promoChar;
5430   ChessMove moveType;
5431   Boolean valid;
5432   int nr = 0;
5433
5434   lastParseAttempt = pv; if(!*pv) return;    // turns out we crash when we parse an empty PV
5435   if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
5436     PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5437     pushed = TRUE;
5438   }
5439   endPV = forwardMostMove;
5440   do {
5441     while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5442     if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5443     lastParseAttempt = pv;
5444     valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5445     if(!valid && nr == 0 &&
5446        ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5447         nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5448         // Hande case where played move is different from leading PV move
5449         CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5450         CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5451         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5452         if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5453           endPV += 2; // if position different, keep this
5454           moveList[endPV-1][0] = fromX + AAA;
5455           moveList[endPV-1][1] = fromY + ONE;
5456           moveList[endPV-1][2] = toX + AAA;
5457           moveList[endPV-1][3] = toY + ONE;
5458           parseList[endPV-1][0] = NULLCHAR;
5459           safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5460         }
5461       }
5462     pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5463     if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5464     if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5465     if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5466         valid++; // allow comments in PV
5467         continue;
5468     }
5469     nr++;
5470     if(endPV+1 > framePtr) break; // no space, truncate
5471     if(!valid) break;
5472     endPV++;
5473     CopyBoard(boards[endPV], boards[endPV-1]);
5474     ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5475     CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5476     strncat(moveList[endPV-1], "\n", MOVE_LEN);
5477     CoordsToAlgebraic(boards[endPV - 1],
5478                              PosFlags(endPV - 1),
5479                              fromY, fromX, toY, toX, promoChar,
5480                              parseList[endPV - 1]);
5481   } while(valid);
5482   if(atEnd == 2) return; // used hidden, for PV conversion
5483   currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5484   if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5485   SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5486                        moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5487   DrawPosition(TRUE, boards[currentMove]);
5488 }
5489
5490 int
5491 MultiPV (ChessProgramState *cps)
5492 {       // check if engine supports MultiPV, and if so, return the number of the option that sets it
5493         int i;
5494         for(i=0; i<cps->nrOptions; i++)
5495             if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5496                 return i;
5497         return -1;
5498 }
5499
5500 Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
5501
5502 Boolean
5503 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5504 {
5505         int startPV, multi, lineStart, origIndex = index;
5506         char *p, buf2[MSG_SIZ];
5507         ChessProgramState *cps = (pane ? &second : &first);
5508
5509         if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5510         lastX = x; lastY = y;
5511         while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5512         lineStart = startPV = index;
5513         while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5514         if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5515         index = startPV;
5516         do{ while(buf[index] && buf[index] != '\n') index++;
5517         } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5518         buf[index] = 0;
5519         if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(cps)) >= 0) {
5520                 int n = cps->option[multi].value;
5521                 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5522                 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5523                 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5524                 cps->option[multi].value = n;
5525                 *start = *end = 0;
5526                 return FALSE;
5527         } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5528                 ExcludeClick(origIndex - lineStart);
5529                 return FALSE;
5530         }
5531         ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5532         *start = startPV; *end = index-1;
5533         extendGame = (gameMode == AnalyzeMode && appData.autoExtend);
5534         return TRUE;
5535 }
5536
5537 char *
5538 PvToSAN (char *pv)
5539 {
5540         static char buf[10*MSG_SIZ];
5541         int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5542         *buf = NULLCHAR;
5543         if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
5544         ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5545         for(i = forwardMostMove; i<endPV; i++){
5546             if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5547             else    snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5548             k += strlen(buf+k);
5549         }
5550         snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5551         if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
5552         if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5553         endPV = savedEnd;
5554         return buf;
5555 }
5556
5557 Boolean
5558 LoadPV (int x, int y)
5559 { // called on right mouse click to load PV
5560   int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5561   lastX = x; lastY = y;
5562   ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5563   extendGame = FALSE;
5564   return TRUE;
5565 }
5566
5567 void
5568 UnLoadPV ()
5569 {
5570   int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5571   if(endPV < 0) return;
5572   if(appData.autoCopyPV) CopyFENToClipboard();
5573   endPV = -1;
5574   if(extendGame && currentMove > forwardMostMove) {
5575         Boolean saveAnimate = appData.animate;
5576         if(pushed) {
5577             if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5578                 if(storedGames == 1) GreyRevert(FALSE);      // we already pushed the tail, so just make it official
5579             } else storedGames--; // abandon shelved tail of original game
5580         }
5581         pushed = FALSE;
5582         forwardMostMove = currentMove;
5583         currentMove = oldFMM;
5584         appData.animate = FALSE;
5585         ToNrEvent(forwardMostMove);
5586         appData.animate = saveAnimate;
5587   }
5588   currentMove = forwardMostMove;
5589   if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5590   ClearPremoveHighlights();
5591   DrawPosition(TRUE, boards[currentMove]);
5592 }
5593
5594 void
5595 MovePV (int x, int y, int h)
5596 { // step through PV based on mouse coordinates (called on mouse move)
5597   int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5598
5599   // we must somehow check if right button is still down (might be released off board!)
5600   if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5601   if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5602   if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5603   if(!step) return;
5604   lastX = x; lastY = y;
5605
5606   if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5607   if(endPV < 0) return;
5608   if(y < margin) step = 1; else
5609   if(y > h - margin) step = -1;
5610   if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5611   currentMove += step;
5612   if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5613   SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5614                        moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5615   DrawPosition(FALSE, boards[currentMove]);
5616 }
5617
5618
5619 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5620 // All positions will have equal probability, but the current method will not provide a unique
5621 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5622 #define DARK 1
5623 #define LITE 2
5624 #define ANY 3
5625
5626 int squaresLeft[4];
5627 int piecesLeft[(int)BlackPawn];
5628 int seed, nrOfShuffles;
5629
5630 void
5631 GetPositionNumber ()
5632 {       // sets global variable seed
5633         int i;
5634
5635         seed = appData.defaultFrcPosition;
5636         if(seed < 0) { // randomize based on time for negative FRC position numbers
5637                 for(i=0; i<50; i++) seed += random();
5638                 seed = random() ^ random() >> 8 ^ random() << 8;
5639                 if(seed<0) seed = -seed;
5640         }
5641 }
5642
5643 int
5644 put (Board board, int pieceType, int rank, int n, int shade)
5645 // put the piece on the (n-1)-th empty squares of the given shade
5646 {
5647         int i;
5648
5649         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5650                 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5651                         board[rank][i] = (ChessSquare) pieceType;
5652                         squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5653                         squaresLeft[ANY]--;
5654                         piecesLeft[pieceType]--;
5655                         return i;
5656                 }
5657         }
5658         return -1;
5659 }
5660
5661
5662 void
5663 AddOnePiece (Board board, int pieceType, int rank, int shade)
5664 // calculate where the next piece goes, (any empty square), and put it there
5665 {
5666         int i;
5667
5668         i = seed % squaresLeft[shade];
5669         nrOfShuffles *= squaresLeft[shade];
5670         seed /= squaresLeft[shade];
5671         put(board, pieceType, rank, i, shade);
5672 }
5673
5674 void
5675 AddTwoPieces (Board board, int pieceType, int rank)
5676 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5677 {
5678         int i, n=squaresLeft[ANY], j=n-1, k;
5679
5680         k = n*(n-1)/2; // nr of possibilities, not counting permutations
5681         i = seed % k;  // pick one
5682         nrOfShuffles *= k;
5683         seed /= k;
5684         while(i >= j) i -= j--;
5685         j = n - 1 - j; i += j;
5686         put(board, pieceType, rank, j, ANY);
5687         put(board, pieceType, rank, i, ANY);
5688 }
5689
5690 void
5691 SetUpShuffle (Board board, int number)
5692 {
5693         int i, p, first=1;
5694
5695         GetPositionNumber(); nrOfShuffles = 1;
5696
5697         squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5698         squaresLeft[ANY]  = BOARD_RGHT - BOARD_LEFT;
5699         squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5700
5701         for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5702
5703         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5704             p = (int) board[0][i];
5705             if(p < (int) BlackPawn) piecesLeft[p] ++;
5706             board[0][i] = EmptySquare;
5707         }
5708
5709         if(PosFlags(0) & F_ALL_CASTLE_OK) {
5710             // shuffles restricted to allow normal castling put KRR first
5711             if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5712                 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5713             else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5714                 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5715             if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5716                 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5717             if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5718                 put(board, WhiteRook, 0, 0, ANY);
5719             // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5720         }
5721
5722         if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5723             // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5724             for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5725                 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5726                 while(piecesLeft[p] >= 2) {
5727                     AddOnePiece(board, p, 0, LITE);
5728                     AddOnePiece(board, p, 0, DARK);
5729                 }
5730                 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5731             }
5732
5733         for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5734             // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5735             // but we leave King and Rooks for last, to possibly obey FRC restriction
5736             if(p == (int)WhiteRook) continue;
5737             while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5738             if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY);     // add the odd piece
5739         }
5740
5741         // now everything is placed, except perhaps King (Unicorn) and Rooks
5742
5743         if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5744             // Last King gets castling rights
5745             while(piecesLeft[(int)WhiteUnicorn]) {
5746                 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5747                 initialRights[2]  = initialRights[5]  = board[CASTLING][2] = board[CASTLING][5] = i;
5748             }
5749
5750             while(piecesLeft[(int)WhiteKing]) {
5751                 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5752                 initialRights[2]  = initialRights[5]  = board[CASTLING][2] = board[CASTLING][5] = i;
5753             }
5754
5755
5756         } else {
5757             while(piecesLeft[(int)WhiteKing])    AddOnePiece(board, WhiteKing, 0, ANY);
5758             while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5759         }
5760
5761         // Only Rooks can be left; simply place them all
5762         while(piecesLeft[(int)WhiteRook]) {
5763                 i = put(board, WhiteRook, 0, 0, ANY);
5764                 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5765                         if(first) {
5766                                 first=0;
5767                                 initialRights[1]  = initialRights[4]  = board[CASTLING][1] = board[CASTLING][4] = i;
5768                         }
5769                         initialRights[0]  = initialRights[3]  = board[CASTLING][0] = board[CASTLING][3] = i;
5770                 }
5771         }
5772         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5773             board[BOARD_HEIGHT-1][i] =  (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5774         }
5775
5776         if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5777 }
5778
5779 int
5780 SetCharTable (char *table, const char * map)
5781 /* [HGM] moved here from winboard.c because of its general usefulness */
5782 /*       Basically a safe strcpy that uses the last character as King */
5783 {
5784     int result = FALSE; int NrPieces;
5785
5786     if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5787                     && NrPieces >= 12 && !(NrPieces&1)) {
5788         int i; /* [HGM] Accept even length from 12 to 34 */
5789
5790         for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5791         for( i=0; i<NrPieces/2-1; i++ ) {
5792             table[i] = map[i];
5793             table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5794         }
5795         table[(int) WhiteKing]  = map[NrPieces/2-1];
5796         table[(int) BlackKing]  = map[NrPieces-1];
5797
5798         result = TRUE;
5799     }
5800
5801     return result;
5802 }
5803
5804 void
5805 Prelude (Board board)
5806 {       // [HGM] superchess: random selection of exo-pieces
5807         int i, j, k; ChessSquare p;
5808         static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5809
5810         GetPositionNumber(); // use FRC position number
5811
5812         if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5813             SetCharTable(pieceToChar, appData.pieceToCharTable);
5814             for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5815                 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5816         }
5817
5818         j = seed%4;                 seed /= 4;
5819         p = board[0][BOARD_LEFT+j];   board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5820         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
5821         board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p;  board[BOARD_HEIGHT-1-k][1]++;
5822         j = seed%3 + (seed%3 >= j); seed /= 3;
5823         p = board[0][BOARD_LEFT+j];   board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5824         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
5825         board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p;  board[BOARD_HEIGHT-1-k][1]++;
5826         j = seed%3;                 seed /= 3;
5827         p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5828         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
5829         board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p;  board[BOARD_HEIGHT-1-k][1]++;
5830         j = seed%2 + (seed%2 >= j); seed /= 2;
5831         p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5832         board[k][BOARD_WIDTH-1] = p;  board[k][BOARD_WIDTH-2]++;
5833         board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p;  board[BOARD_HEIGHT-1-k][1]++;
5834         j = seed%4; seed /= 4; put(board, exoPieces[3],    0, j, ANY);
5835         j = seed%3; seed /= 3; put(board, exoPieces[2],   0, j, ANY);
5836         j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5837         put(board, exoPieces[0],    0, 0, ANY);
5838         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5839 }
5840
5841 void
5842 InitPosition (int redraw)
5843 {
5844     ChessSquare (* pieces)[BOARD_FILES];
5845     int i, j, pawnRow, overrule,
5846     oldx = gameInfo.boardWidth,
5847     oldy = gameInfo.boardHeight,
5848     oldh = gameInfo.holdingsWidth;
5849     static int oldv;
5850
5851     if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5852
5853     /* [AS] Initialize pv info list [HGM] and game status */
5854     {
5855         for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5856             pvInfoList[i].depth = 0;
5857             boards[i][EP_STATUS] = EP_NONE;
5858             for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5859         }
5860
5861         initialRulePlies = 0; /* 50-move counter start */
5862
5863         castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5864         castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5865     }
5866
5867
5868     /* [HGM] logic here is completely changed. In stead of full positions */
5869     /* the initialized data only consist of the two backranks. The switch */
5870     /* selects which one we will use, which is than copied to the Board   */
5871     /* initialPosition, which for the rest is initialized by Pawns and    */
5872     /* empty squares. This initial position is then copied to boards[0],  */
5873     /* possibly after shuffling, so that it remains available.            */
5874
5875     gameInfo.holdingsWidth = 0; /* default board sizes */
5876     gameInfo.boardWidth    = 8;
5877     gameInfo.boardHeight   = 8;
5878     gameInfo.holdingsSize  = 0;
5879     nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5880     for(i=0; i<BOARD_FILES-2; i++)
5881       initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5882     initialPosition[EP_STATUS] = EP_NONE;
5883     SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5884     if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5885          SetCharTable(pieceNickName, appData.pieceNickNames);
5886     else SetCharTable(pieceNickName, "............");
5887     pieces = FIDEArray;
5888
5889     switch (gameInfo.variant) {
5890     case VariantFischeRandom:
5891       shuffleOpenings = TRUE;
5892     default:
5893       break;
5894     case VariantShatranj:
5895       pieces = ShatranjArray;
5896       nrCastlingRights = 0;
5897       SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5898       break;
5899     case VariantMakruk:
5900       pieces = makrukArray;
5901       nrCastlingRights = 0;
5902       startedFromSetupPosition = TRUE;
5903       SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5904       break;
5905     case VariantTwoKings:
5906       pieces = twoKingsArray;
5907       break;
5908     case VariantGrand:
5909       pieces = GrandArray;
5910       nrCastlingRights = 0;
5911       SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5912       gameInfo.boardWidth = 10;
5913       gameInfo.boardHeight = 10;
5914       gameInfo.holdingsSize = 7;
5915       break;
5916     case VariantCapaRandom:
5917       shuffleOpenings = TRUE;
5918     case VariantCapablanca:
5919       pieces = CapablancaArray;
5920       gameInfo.boardWidth = 10;
5921       SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5922       break;
5923     case VariantGothic:
5924       pieces = GothicArray;
5925       gameInfo.boardWidth = 10;
5926       SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5927       break;
5928     case VariantSChess:
5929       SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5930       gameInfo.holdingsSize = 7;
5931       for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
5932       break;
5933     case VariantJanus:
5934       pieces = JanusArray;
5935       gameInfo.boardWidth = 10;
5936       SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5937       nrCastlingRights = 6;
5938         initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5939         initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5940         initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5941         initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5942         initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5943         initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5944       break;
5945     case VariantFalcon:
5946       pieces = FalconArray;
5947       gameInfo.boardWidth = 10;
5948       SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5949       break;
5950     case VariantXiangqi:
5951       pieces = XiangqiArray;
5952       gameInfo.boardWidth  = 9;
5953       gameInfo.boardHeight = 10;
5954       nrCastlingRights = 0;
5955       SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5956       break;
5957     case VariantShogi:
5958       pieces = ShogiArray;
5959       gameInfo.boardWidth  = 9;
5960       gameInfo.boardHeight = 9;
5961       gameInfo.holdingsSize = 7;
5962       nrCastlingRights = 0;
5963       SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5964       break;
5965     case VariantCourier:
5966       pieces = CourierArray;
5967       gameInfo.boardWidth  = 12;
5968       nrCastlingRights = 0;
5969       SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5970       break;
5971     case VariantKnightmate:
5972       pieces = KnightmateArray;
5973       SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5974       break;
5975     case VariantSpartan:
5976       pieces = SpartanArray;
5977       SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5978       break;
5979     case VariantFairy:
5980       pieces = fairyArray;
5981       SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5982       break;
5983     case VariantGreat:
5984       pieces = GreatArray;
5985       gameInfo.boardWidth = 10;
5986       SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5987       gameInfo.holdingsSize = 8;
5988       break;
5989     case VariantSuper:
5990       pieces = FIDEArray;
5991       SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5992       gameInfo.holdingsSize = 8;
5993       startedFromSetupPosition = TRUE;
5994       break;
5995     case VariantCrazyhouse:
5996     case VariantBughouse:
5997       pieces = FIDEArray;
5998       SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5999       gameInfo.holdingsSize = 5;
6000       break;
6001     case VariantWildCastle:
6002       pieces = FIDEArray;
6003       /* !!?shuffle with kings guaranteed to be on d or e file */
6004       shuffleOpenings = 1;
6005       break;
6006     case VariantNoCastle:
6007       pieces = FIDEArray;
6008       nrCastlingRights = 0;
6009       /* !!?unconstrained back-rank shuffle */
6010       shuffleOpenings = 1;
6011       break;
6012     }
6013
6014     overrule = 0;
6015     if(appData.NrFiles >= 0) {
6016         if(gameInfo.boardWidth != appData.NrFiles) overrule++;
6017         gameInfo.boardWidth = appData.NrFiles;
6018     }
6019     if(appData.NrRanks >= 0) {
6020         gameInfo.boardHeight = appData.NrRanks;
6021     }
6022     if(appData.holdingsSize >= 0) {
6023         i = appData.holdingsSize;
6024         if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
6025         gameInfo.holdingsSize = i;
6026     }
6027     if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
6028     if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
6029         DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
6030
6031     pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
6032     if(pawnRow < 1) pawnRow = 1;
6033     if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) pawnRow = 2;
6034
6035     /* User pieceToChar list overrules defaults */
6036     if(appData.pieceToCharTable != NULL)
6037         SetCharTable(pieceToChar, appData.pieceToCharTable);
6038
6039     for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
6040
6041         if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
6042             s = (ChessSquare) 0; /* account holding counts in guard band */
6043         for( i=0; i<BOARD_HEIGHT; i++ )
6044             initialPosition[i][j] = s;
6045
6046         if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6047         initialPosition[gameInfo.variant == VariantGrand][j] = pieces[0][j-gameInfo.holdingsWidth];
6048         initialPosition[pawnRow][j] = WhitePawn;
6049         initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6050         if(gameInfo.variant == VariantXiangqi) {
6051             if(j&1) {
6052                 initialPosition[pawnRow][j] =
6053                 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6054                 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6055                    initialPosition[2][j] = WhiteCannon;
6056                    initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6057                 }
6058             }
6059         }
6060         if(gameInfo.variant == VariantGrand) {
6061             if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6062                initialPosition[0][j] = WhiteRook;
6063                initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6064             }
6065         }
6066         initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand)][j] =  pieces[1][j-gameInfo.holdingsWidth];
6067     }
6068     if( (gameInfo.variant == VariantShogi) && !overrule ) {
6069
6070             j=BOARD_LEFT+1;
6071             initialPosition[1][j] = WhiteBishop;
6072             initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6073             j=BOARD_RGHT-2;
6074             initialPosition[1][j] = WhiteRook;
6075             initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6076     }
6077
6078     if( nrCastlingRights == -1) {
6079         /* [HGM] Build normal castling rights (must be done after board sizing!) */
6080         /*       This sets default castling rights from none to normal corners   */
6081         /* Variants with other castling rights must set them themselves above    */
6082         nrCastlingRights = 6;
6083
6084         initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6085         initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6086         initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6087         initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6088         initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6089         initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6090      }
6091
6092      if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6093      if(gameInfo.variant == VariantGreat) { // promotion commoners
6094         initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6095         initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6096         initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6097         initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
6098      }
6099      if( gameInfo.variant == VariantSChess ) {
6100       initialPosition[1][0] = BlackMarshall;
6101       initialPosition[2][0] = BlackAngel;
6102       initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6103       initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6104       initialPosition[1][1] = initialPosition[2][1] =
6105       initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6106      }
6107   if (appData.debugMode) {
6108     fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6109   }
6110     if(shuffleOpenings) {
6111         SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6112         startedFromSetupPosition = TRUE;
6113     }
6114     if(startedFromPositionFile) {
6115       /* [HGM] loadPos: use PositionFile for every new game */
6116       CopyBoard(initialPosition, filePosition);
6117       for(i=0; i<nrCastlingRights; i++)
6118           initialRights[i] = filePosition[CASTLING][i];
6119       startedFromSetupPosition = TRUE;
6120     }
6121
6122     CopyBoard(boards[0], initialPosition);
6123
6124     if(oldx != gameInfo.boardWidth ||
6125        oldy != gameInfo.boardHeight ||
6126        oldv != gameInfo.variant ||
6127        oldh != gameInfo.holdingsWidth
6128                                          )
6129             InitDrawingSizes(-2 ,0);
6130
6131     oldv = gameInfo.variant;
6132     if (redraw)
6133       DrawPosition(TRUE, boards[currentMove]);
6134 }
6135
6136 void
6137 SendBoard (ChessProgramState *cps, int moveNum)
6138 {
6139     char message[MSG_SIZ];
6140
6141     if (cps->useSetboard) {
6142       char* fen = PositionToFEN(moveNum, cps->fenOverride);
6143       snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6144       SendToProgram(message, cps);
6145       free(fen);
6146
6147     } else {
6148       ChessSquare *bp;
6149       int i, j, left=0, right=BOARD_WIDTH;
6150       /* Kludge to set black to move, avoiding the troublesome and now
6151        * deprecated "black" command.
6152        */
6153       if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6154         SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6155
6156       if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6157
6158       SendToProgram("edit\n", cps);
6159       SendToProgram("#\n", cps);
6160       for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6161         bp = &boards[moveNum][i][left];
6162         for (j = left; j < right; j++, bp++) {
6163           if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6164           if ((int) *bp < (int) BlackPawn) {
6165             if(j == BOARD_RGHT+1)
6166                  snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6167             else snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i);
6168             if(message[0] == '+' || message[0] == '~') {
6169               snprintf(message, MSG_SIZ,"%c%c%c+\n",
6170                         PieceToChar((ChessSquare)(DEMOTED *bp)),
6171                         AAA + j, ONE + i);
6172             }
6173             if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6174                 message[1] = BOARD_RGHT   - 1 - j + '1';
6175                 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6176             }
6177             SendToProgram(message, cps);
6178           }
6179         }
6180       }
6181
6182       SendToProgram("c\n", cps);
6183       for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6184         bp = &boards[moveNum][i][left];
6185         for (j = left; j < right; j++, bp++) {
6186           if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6187           if (((int) *bp != (int) EmptySquare)
6188               && ((int) *bp >= (int) BlackPawn)) {
6189             if(j == BOARD_LEFT-2)
6190                  snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6191             else snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6192                     AAA + j, ONE + i);
6193             if(message[0] == '+' || message[0] == '~') {
6194               snprintf(message, MSG_SIZ,"%c%c%c+\n",
6195                         PieceToChar((ChessSquare)(DEMOTED *bp)),
6196                         AAA + j, ONE + i);
6197             }
6198             if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6199                 message[1] = BOARD_RGHT   - 1 - j + '1';
6200                 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6201             }
6202             SendToProgram(message, cps);
6203           }
6204         }
6205       }
6206
6207       SendToProgram(".\n", cps);
6208     }
6209     setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6210 }
6211
6212 char exclusionHeader[MSG_SIZ];
6213 int exCnt, excludePtr;
6214 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6215 static Exclusion excluTab[200];
6216 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6217
6218 static void
6219 WriteMap (int s)
6220 {
6221     int j;
6222     for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6223     exclusionHeader[19] = s ? '-' : '+'; // update tail state
6224 }
6225
6226 static void
6227 ClearMap ()
6228 {
6229     safeStrCpy(exclusionHeader, "exclude: none best +tail                                          \n", MSG_SIZ);
6230     excludePtr = 24; exCnt = 0;
6231     WriteMap(0);
6232 }
6233
6234 static void
6235 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6236 {   // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6237     char buf[2*MOVE_LEN], *p;
6238     Exclusion *e = excluTab;
6239     int i;
6240     for(i=0; i<exCnt; i++)
6241         if(e[i].ff == fromX && e[i].fr == fromY &&
6242            e[i].tf == toX   && e[i].tr == toY && e[i].pc == promoChar) break;
6243     if(i == exCnt) { // was not in exclude list; add it
6244         CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6245         if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6246             if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6247             return; // abort
6248         }
6249         e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6250         excludePtr++; e[i].mark = excludePtr++;
6251         for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6252         exCnt++;
6253     }
6254     exclusionHeader[e[i].mark] = state;
6255 }
6256
6257 static int
6258 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6259 {   // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6260     char buf[MSG_SIZ];
6261     int j, k;
6262     ChessMove moveType;
6263     if((signed char)promoChar == -1) { // kludge to indicate best move
6264         if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6265             return 1; // if unparsable, abort
6266     }
6267     // update exclusion map (resolving toggle by consulting existing state)
6268     k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6269     j = k%8; k >>= 3;
6270     if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6271     if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6272          excludeMap[k] |=   1<<j;
6273     else excludeMap[k] &= ~(1<<j);
6274     // update header
6275     UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6276     // inform engine
6277     snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6278     CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6279     SendToBoth(buf);
6280     return (state == '+');
6281 }
6282
6283 static void
6284 ExcludeClick (int index)
6285 {
6286     int i, j;
6287     Exclusion *e = excluTab;
6288     if(index < 25) { // none, best or tail clicked
6289         if(index < 13) { // none: include all
6290             WriteMap(0); // clear map
6291             for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6292             SendToBoth("include all\n"); // and inform engine
6293         } else if(index > 18) { // tail
6294             if(exclusionHeader[19] == '-') { // tail was excluded
6295                 SendToBoth("include all\n");
6296                 WriteMap(0); // clear map completely
6297                 // now re-exclude selected moves
6298                 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6299                     ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6300             } else { // tail was included or in mixed state
6301                 SendToBoth("exclude all\n");
6302                 WriteMap(0xFF); // fill map completely
6303                 // now re-include selected moves
6304                 j = 0; // count them
6305                 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6306                     ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6307                 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6308             }
6309         } else { // best
6310             ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6311         }
6312     } else {
6313         for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6314             char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6315             ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6316             break;
6317         }
6318     }
6319 }
6320
6321 ChessSquare
6322 DefaultPromoChoice (int white)
6323 {
6324     ChessSquare result;
6325     if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
6326         result = WhiteFerz; // no choice
6327     else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6328         result= WhiteKing; // in Suicide Q is the last thing we want
6329     else if(gameInfo.variant == VariantSpartan)
6330         result = white ? WhiteQueen : WhiteAngel;
6331     else result = WhiteQueen;
6332     if(!white) result = WHITE_TO_BLACK result;
6333     return result;
6334 }
6335
6336 static int autoQueen; // [HGM] oneclick
6337
6338 int
6339 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6340 {
6341     /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6342     /* [HGM] add Shogi promotions */
6343     int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6344     ChessSquare piece;
6345     ChessMove moveType;
6346     Boolean premove;
6347
6348     if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6349     if(toX   < BOARD_LEFT || toX   >= BOARD_RGHT) return FALSE; // move into holdings
6350
6351     if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6352       !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6353         return FALSE;
6354
6355     piece = boards[currentMove][fromY][fromX];
6356     if(gameInfo.variant == VariantShogi) {
6357         promotionZoneSize = BOARD_HEIGHT/3;
6358         highestPromotingPiece = (int)WhiteFerz;
6359     } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) {
6360         promotionZoneSize = 3;
6361     }
6362
6363     // Treat Lance as Pawn when it is not representing Amazon
6364     if(gameInfo.variant != VariantSuper) {
6365         if(piece == WhiteLance) piece = WhitePawn; else
6366         if(piece == BlackLance) piece = BlackPawn;
6367     }
6368
6369     // next weed out all moves that do not touch the promotion zone at all
6370     if((int)piece >= BlackPawn) {
6371         if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6372              return FALSE;
6373         highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6374     } else {
6375         if(  toY < BOARD_HEIGHT - promotionZoneSize &&
6376            fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6377     }
6378
6379     if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6380
6381     // weed out mandatory Shogi promotions
6382     if(gameInfo.variant == VariantShogi) {
6383         if(piece >= BlackPawn) {
6384             if(toY == 0 && piece == BlackPawn ||
6385                toY == 0 && piece == BlackQueen ||
6386                toY <= 1 && piece == BlackKnight) {
6387                 *promoChoice = '+';
6388                 return FALSE;
6389             }
6390         } else {
6391             if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6392                toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6393                toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6394                 *promoChoice = '+';
6395                 return FALSE;
6396             }
6397         }
6398     }
6399
6400     // weed out obviously illegal Pawn moves
6401     if(appData.testLegality  && (piece == WhitePawn || piece == BlackPawn) ) {
6402         if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6403         if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6404         if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6405         if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6406         // note we are not allowed to test for valid (non-)capture, due to premove
6407     }
6408
6409     // we either have a choice what to promote to, or (in Shogi) whether to promote
6410     if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
6411         *promoChoice = PieceToChar(BlackFerz);  // no choice
6412         return FALSE;
6413     }
6414     // no sense asking what we must promote to if it is going to explode...
6415     if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6416         *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6417         return FALSE;
6418     }
6419     // give caller the default choice even if we will not make it
6420     *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6421     if(gameInfo.variant == VariantShogi) *promoChoice = (defaultPromoChoice == piece ? '=' : '+');
6422     if(        sweepSelect && gameInfo.variant != VariantGreat
6423                            && gameInfo.variant != VariantGrand
6424                            && gameInfo.variant != VariantSuper) return FALSE;
6425     if(autoQueen) return FALSE; // predetermined
6426
6427     // suppress promotion popup on illegal moves that are not premoves
6428     premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6429               gameMode == IcsPlayingBlack &&  WhiteOnMove(currentMove);
6430     if(appData.testLegality && !premove) {
6431         moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6432                         fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
6433         if(moveType != WhitePromotion && moveType  != BlackPromotion)
6434             return FALSE;
6435     }
6436
6437     return TRUE;
6438 }
6439
6440 int
6441 InPalace (int row, int column)
6442 {   /* [HGM] for Xiangqi */
6443     if( (row < 3 || row > BOARD_HEIGHT-4) &&
6444          column < (BOARD_WIDTH + 4)/2 &&
6445          column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6446     return FALSE;
6447 }
6448
6449 int
6450 PieceForSquare (int x, int y)
6451 {
6452   if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6453      return -1;
6454   else
6455      return boards[currentMove][y][x];
6456 }
6457
6458 int
6459 OKToStartUserMove (int x, int y)
6460 {
6461     ChessSquare from_piece;
6462     int white_piece;
6463
6464     if (matchMode) return FALSE;
6465     if (gameMode == EditPosition) return TRUE;
6466
6467     if (x >= 0 && y >= 0)
6468       from_piece = boards[currentMove][y][x];
6469     else
6470       from_piece = EmptySquare;
6471
6472     if (from_piece == EmptySquare) return FALSE;
6473
6474     white_piece = (int)from_piece >= (int)WhitePawn &&
6475       (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6476
6477     switch (gameMode) {
6478       case AnalyzeFile:
6479       case TwoMachinesPlay:
6480       case EndOfGame:
6481         return FALSE;
6482
6483       case IcsObserving:
6484       case IcsIdle:
6485         return FALSE;
6486
6487       case MachinePlaysWhite:
6488       case IcsPlayingBlack:
6489         if (appData.zippyPlay) return FALSE;
6490         if (white_piece) {
6491             DisplayMoveError(_("You are playing Black"));
6492             return FALSE;
6493         }
6494         break;
6495
6496       case MachinePlaysBlack:
6497       case IcsPlayingWhite:
6498         if (appData.zippyPlay) return FALSE;
6499         if (!white_piece) {
6500             DisplayMoveError(_("You are playing White"));
6501             return FALSE;
6502         }
6503         break;
6504
6505       case PlayFromGameFile:
6506             if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6507       case EditGame:
6508         if (!white_piece && WhiteOnMove(currentMove)) {
6509             DisplayMoveError(_("It is White's turn"));
6510             return FALSE;
6511         }
6512         if (white_piece && !WhiteOnMove(currentMove)) {
6513             DisplayMoveError(_("It is Black's turn"));
6514             return FALSE;
6515         }
6516         if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6517             /* Editing correspondence game history */
6518             /* Could disallow this or prompt for confirmation */
6519             cmailOldMove = -1;
6520         }
6521         break;
6522
6523       case BeginningOfGame:
6524         if (appData.icsActive) return FALSE;
6525         if (!appData.noChessProgram) {
6526             if (!white_piece) {
6527                 DisplayMoveError(_("You are playing White"));
6528                 return FALSE;
6529             }
6530         }
6531         break;
6532
6533       case Training:
6534         if (!white_piece && WhiteOnMove(currentMove)) {
6535             DisplayMoveError(_("It is White's turn"));
6536             return FALSE;
6537         }
6538         if (white_piece && !WhiteOnMove(currentMove)) {
6539             DisplayMoveError(_("It is Black's turn"));
6540             return FALSE;
6541         }
6542         break;
6543
6544       default:
6545       case IcsExamining:
6546         break;
6547     }
6548     if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6549         && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6550         && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6551         && gameMode != AnalyzeFile && gameMode != Training) {
6552         DisplayMoveError(_("Displayed position is not current"));
6553         return FALSE;
6554     }
6555     return TRUE;
6556 }
6557
6558 Boolean
6559 OnlyMove (int *x, int *y, Boolean captures)
6560 {
6561     DisambiguateClosure cl;
6562     if (appData.zippyPlay || !appData.testLegality) return FALSE;
6563     switch(gameMode) {
6564       case MachinePlaysBlack:
6565       case IcsPlayingWhite:
6566       case BeginningOfGame:
6567         if(!WhiteOnMove(currentMove)) return FALSE;
6568         break;
6569       case MachinePlaysWhite:
6570       case IcsPlayingBlack:
6571         if(WhiteOnMove(currentMove)) return FALSE;
6572         break;
6573       case EditGame:
6574         break;
6575       default:
6576         return FALSE;
6577     }
6578     cl.pieceIn = EmptySquare;
6579     cl.rfIn = *y;
6580     cl.ffIn = *x;
6581     cl.rtIn = -1;
6582     cl.ftIn = -1;
6583     cl.promoCharIn = NULLCHAR;
6584     Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6585     if( cl.kind == NormalMove ||
6586         cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6587         cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6588         cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6589       fromX = cl.ff;
6590       fromY = cl.rf;
6591       *x = cl.ft;
6592       *y = cl.rt;
6593       return TRUE;
6594     }
6595     if(cl.kind != ImpossibleMove) return FALSE;
6596     cl.pieceIn = EmptySquare;
6597     cl.rfIn = -1;
6598     cl.ffIn = -1;
6599     cl.rtIn = *y;
6600     cl.ftIn = *x;
6601     cl.promoCharIn = NULLCHAR;
6602     Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6603     if( cl.kind == NormalMove ||
6604         cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6605         cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6606         cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6607       fromX = cl.ff;
6608       fromY = cl.rf;
6609       *x = cl.ft;
6610       *y = cl.rt;
6611       autoQueen = TRUE; // act as if autoQueen on when we click to-square
6612       return TRUE;
6613     }
6614     return FALSE;
6615 }
6616
6617 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6618 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6619 int lastLoadGameUseList = FALSE;
6620 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6621 ChessMove lastLoadGameStart = EndOfFile;
6622 int doubleClick;
6623
6624 void
6625 UserMoveEvent(int fromX, int fromY, int toX, int toY, int promoChar)
6626 {
6627     ChessMove moveType;
6628     ChessSquare pup;
6629     int ff=fromX, rf=fromY, ft=toX, rt=toY;
6630
6631     /* Check if the user is playing in turn.  This is complicated because we
6632        let the user "pick up" a piece before it is his turn.  So the piece he
6633        tried to pick up may have been captured by the time he puts it down!
6634        Therefore we use the color the user is supposed to be playing in this
6635        test, not the color of the piece that is currently on the starting
6636        square---except in EditGame mode, where the user is playing both
6637        sides; fortunately there the capture race can't happen.  (It can
6638        now happen in IcsExamining mode, but that's just too bad.  The user
6639        will get a somewhat confusing message in that case.)
6640        */
6641
6642     switch (gameMode) {
6643       case AnalyzeFile:
6644       case TwoMachinesPlay:
6645       case EndOfGame:
6646       case IcsObserving:
6647       case IcsIdle:
6648         /* We switched into a game mode where moves are not accepted,
6649            perhaps while the mouse button was down. */
6650         return;
6651
6652       case MachinePlaysWhite:
6653         /* User is moving for Black */
6654         if (WhiteOnMove(currentMove)) {
6655             DisplayMoveError(_("It is White's turn"));
6656             return;
6657         }
6658         break;
6659
6660       case MachinePlaysBlack:
6661         /* User is moving for White */
6662         if (!WhiteOnMove(currentMove)) {
6663             DisplayMoveError(_("It is Black's turn"));
6664             return;
6665         }
6666         break;
6667
6668       case PlayFromGameFile:
6669             if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6670       case EditGame:
6671       case IcsExamining:
6672       case BeginningOfGame:
6673       case AnalyzeMode:
6674       case Training:
6675         if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6676         if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6677             (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6678             /* User is moving for Black */
6679             if (WhiteOnMove(currentMove)) {
6680                 DisplayMoveError(_("It is White's turn"));
6681                 return;
6682             }
6683         } else {
6684             /* User is moving for White */
6685             if (!WhiteOnMove(currentMove)) {
6686                 DisplayMoveError(_("It is Black's turn"));
6687                 return;
6688             }
6689         }
6690         break;
6691
6692       case IcsPlayingBlack:
6693         /* User is moving for Black */
6694         if (WhiteOnMove(currentMove)) {
6695             if (!appData.premove) {
6696                 DisplayMoveError(_("It is White's turn"));
6697             } else if (toX >= 0 && toY >= 0) {
6698                 premoveToX = toX;
6699                 premoveToY = toY;
6700                 premoveFromX = fromX;
6701                 premoveFromY = fromY;
6702                 premovePromoChar = promoChar;
6703                 gotPremove = 1;
6704                 if (appData.debugMode)
6705                     fprintf(debugFP, "Got premove: fromX %d,"
6706                             "fromY %d, toX %d, toY %d\n",
6707                             fromX, fromY, toX, toY);
6708             }
6709             return;
6710         }
6711         break;
6712
6713       case IcsPlayingWhite:
6714         /* User is moving for White */
6715         if (!WhiteOnMove(currentMove)) {
6716             if (!appData.premove) {
6717                 DisplayMoveError(_("It is Black's turn"));
6718             } else if (toX >= 0 && toY >= 0) {
6719                 premoveToX = toX;
6720                 premoveToY = toY;
6721                 premoveFromX = fromX;
6722                 premoveFromY = fromY;
6723                 premovePromoChar = promoChar;
6724                 gotPremove = 1;
6725                 if (appData.debugMode)
6726                     fprintf(debugFP, "Got premove: fromX %d,"
6727                             "fromY %d, toX %d, toY %d\n",
6728                             fromX, fromY, toX, toY);
6729             }
6730             return;
6731         }
6732         break;
6733
6734       default:
6735         break;
6736
6737       case EditPosition:
6738         /* EditPosition, empty square, or different color piece;
6739            click-click move is possible */
6740         if (toX == -2 || toY == -2) {
6741             boards[0][fromY][fromX] = EmptySquare;
6742             DrawPosition(FALSE, boards[currentMove]);
6743             return;
6744         } else if (toX >= 0 && toY >= 0) {
6745             boards[0][toY][toX] = boards[0][fromY][fromX];
6746             if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6747                 if(boards[0][fromY][0] != EmptySquare) {
6748                     if(boards[0][fromY][1]) boards[0][fromY][1]--;
6749                     if(boards[0][fromY][1] == 0)  boards[0][fromY][0] = EmptySquare;
6750                 }
6751             } else
6752             if(fromX == BOARD_RGHT+1) {
6753                 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6754                     if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6755                     if(boards[0][fromY][BOARD_WIDTH-2] == 0)  boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6756                 }
6757             } else
6758             boards[0][fromY][fromX] = gatingPiece;
6759             DrawPosition(FALSE, boards[currentMove]);
6760             return;
6761         }
6762         return;
6763     }
6764
6765     if(toX < 0 || toY < 0) return;
6766     pup = boards[currentMove][toY][toX];
6767
6768     /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6769     if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6770          if( pup != EmptySquare ) return;
6771          moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6772            if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6773                 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6774            // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6775            if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6776            fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6777            while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6778          fromY = DROP_RANK;
6779     }
6780
6781     /* [HGM] always test for legality, to get promotion info */
6782     moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6783                                          fromY, fromX, toY, toX, promoChar);
6784
6785     if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame)) moveType = NormalMove;
6786
6787     /* [HGM] but possibly ignore an IllegalMove result */
6788     if (appData.testLegality) {
6789         if (moveType == IllegalMove || moveType == ImpossibleMove) {
6790             DisplayMoveError(_("Illegal move"));
6791             return;
6792         }
6793     }
6794
6795     if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
6796         if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
6797              ClearPremoveHighlights(); // was included
6798         else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated  by premove highlights
6799         return;
6800     }
6801
6802     FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6803 }
6804
6805 /* Common tail of UserMoveEvent and DropMenuEvent */
6806 int
6807 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
6808 {
6809     char *bookHit = 0;
6810
6811     if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
6812         // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
6813         int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6814         if(WhiteOnMove(currentMove)) {
6815             if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6816         } else {
6817             if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6818         }
6819     }
6820
6821     /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6822        move type in caller when we know the move is a legal promotion */
6823     if(moveType == NormalMove && promoChar)
6824         moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6825
6826     /* [HGM] <popupFix> The following if has been moved here from
6827        UserMoveEvent(). Because it seemed to belong here (why not allow
6828        piece drops in training games?), and because it can only be
6829        performed after it is known to what we promote. */
6830     if (gameMode == Training) {
6831       /* compare the move played on the board to the next move in the
6832        * game. If they match, display the move and the opponent's response.
6833        * If they don't match, display an error message.
6834        */
6835       int saveAnimate;
6836       Board testBoard;
6837       CopyBoard(testBoard, boards[currentMove]);
6838       ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6839
6840       if (CompareBoards(testBoard, boards[currentMove+1])) {
6841         ForwardInner(currentMove+1);
6842
6843         /* Autoplay the opponent's response.
6844          * if appData.animate was TRUE when Training mode was entered,
6845          * the response will be animated.
6846          */
6847         saveAnimate = appData.animate;
6848         appData.animate = animateTraining;
6849         ForwardInner(currentMove+1);
6850         appData.animate = saveAnimate;
6851
6852         /* check for the end of the game */
6853         if (currentMove >= forwardMostMove) {
6854           gameMode = PlayFromGameFile;
6855           ModeHighlight();
6856           SetTrainingModeOff();
6857           DisplayInformation(_("End of game"));
6858         }
6859       } else {
6860         DisplayError(_("Incorrect move"), 0);
6861       }
6862       return 1;
6863     }
6864
6865   /* Ok, now we know that the move is good, so we can kill
6866      the previous line in Analysis Mode */
6867   if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
6868                                 && currentMove < forwardMostMove) {
6869     if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6870     else forwardMostMove = currentMove;
6871   }
6872
6873   ClearMap();
6874
6875   /* If we need the chess program but it's dead, restart it */
6876   ResurrectChessProgram();
6877
6878   /* A user move restarts a paused game*/
6879   if (pausing)
6880     PauseEvent();
6881
6882   thinkOutput[0] = NULLCHAR;
6883
6884   MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6885
6886   if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6887     ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6888     return 1;
6889   }
6890
6891   if (gameMode == BeginningOfGame) {
6892     if (appData.noChessProgram) {
6893       gameMode = EditGame;
6894       SetGameInfo();
6895     } else {
6896       char buf[MSG_SIZ];
6897       gameMode = MachinePlaysBlack;
6898       StartClocks();
6899       SetGameInfo();
6900       snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
6901       DisplayTitle(buf);
6902       if (first.sendName) {
6903         snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6904         SendToProgram(buf, &first);
6905       }
6906       StartClocks();
6907     }
6908     ModeHighlight();
6909   }
6910
6911   /* Relay move to ICS or chess engine */
6912   if (appData.icsActive) {
6913     if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6914         gameMode == IcsExamining) {
6915       if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6916         SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6917         SendToICS("draw ");
6918         SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6919       }
6920       // also send plain move, in case ICS does not understand atomic claims
6921       SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6922       ics_user_moved = 1;
6923     }
6924   } else {
6925     if (first.sendTime && (gameMode == BeginningOfGame ||
6926                            gameMode == MachinePlaysWhite ||
6927                            gameMode == MachinePlaysBlack)) {
6928       SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6929     }
6930     if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
6931          // [HGM] book: if program might be playing, let it use book
6932         bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6933         first.maybeThinking = TRUE;
6934     } else if(fromY == DROP_RANK && fromX == EmptySquare) {
6935         if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
6936         SendBoard(&first, currentMove+1);
6937         if(second.analyzing) {
6938             if(!second.useSetboard) SendToProgram("undo\n", &second);
6939             SendBoard(&second, currentMove+1);
6940         }
6941     } else {
6942         SendMoveToProgram(forwardMostMove-1, &first);
6943         if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
6944     }
6945     if (currentMove == cmailOldMove + 1) {
6946       cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6947     }
6948   }
6949
6950   ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6951
6952   switch (gameMode) {
6953   case EditGame:
6954     if(appData.testLegality)
6955     switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6956     case MT_NONE:
6957     case MT_CHECK:
6958       break;
6959     case MT_CHECKMATE:
6960     case MT_STAINMATE:
6961       if (WhiteOnMove(currentMove)) {
6962         GameEnds(BlackWins, "Black mates", GE_PLAYER);
6963       } else {
6964         GameEnds(WhiteWins, "White mates", GE_PLAYER);
6965       }
6966       break;
6967     case MT_STALEMATE:
6968       GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6969       break;
6970     }
6971     break;
6972
6973   case MachinePlaysBlack:
6974   case MachinePlaysWhite:
6975     /* disable certain menu options while machine is thinking */
6976     SetMachineThinkingEnables();
6977     break;
6978
6979   default:
6980     break;
6981   }
6982
6983   userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6984   promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6985
6986   if(bookHit) { // [HGM] book: simulate book reply
6987         static char bookMove[MSG_SIZ]; // a bit generous?
6988
6989         programStats.nodes = programStats.depth = programStats.time =
6990         programStats.score = programStats.got_only_move = 0;
6991         sprintf(programStats.movelist, "%s (xbook)", bookHit);
6992
6993         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6994         strcat(bookMove, bookHit);
6995         HandleMachineMove(bookMove, &first);
6996   }
6997   return 1;
6998 }
6999
7000 void
7001 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
7002 {
7003     typedef char Markers[BOARD_RANKS][BOARD_FILES];
7004     Markers *m = (Markers *) closure;
7005     if(rf == fromY && ff == fromX)
7006         (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
7007                          || kind == WhiteCapturesEnPassant
7008                          || kind == BlackCapturesEnPassant);
7009     else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
7010 }
7011
7012 void
7013 MarkTargetSquares (int clear)
7014 {
7015   int x, y;
7016   if(clear) // no reason to ever suppress clearing
7017     for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
7018   if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
7019      !appData.testLegality || gameMode == EditPosition) return;
7020   if(!clear) {
7021     int capt = 0;
7022     GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
7023     if(PosFlags(0) & F_MANDATORY_CAPTURE) {
7024       for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
7025       if(capt)
7026       for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
7027     }
7028   }
7029   DrawPosition(FALSE, NULL);
7030 }
7031
7032 int
7033 Explode (Board board, int fromX, int fromY, int toX, int toY)
7034 {
7035     if(gameInfo.variant == VariantAtomic &&
7036        (board[toY][toX] != EmptySquare ||                     // capture?
7037         toX != fromX && (board[fromY][fromX] == WhitePawn ||  // e.p. ?
7038                          board[fromY][fromX] == BlackPawn   )
7039       )) {
7040         AnimateAtomicCapture(board, fromX, fromY, toX, toY);
7041         return TRUE;
7042     }
7043     return FALSE;
7044 }
7045
7046 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7047
7048 int
7049 CanPromote (ChessSquare piece, int y)
7050 {
7051         if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7052         // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7053         if(gameInfo.variant == VariantShogi    || gameInfo.variant == VariantXiangqi ||
7054            gameInfo.variant == VariantSuper    || gameInfo.variant == VariantGreat   ||
7055            gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7056                                                   gameInfo.variant == VariantMakruk) return FALSE;
7057         return (piece == BlackPawn && y == 1 ||
7058                 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
7059                 piece == BlackLance && y == 1 ||
7060                 piece == WhiteLance && y == BOARD_HEIGHT-2 );
7061 }
7062
7063 void
7064 LeftClick (ClickType clickType, int xPix, int yPix)
7065 {
7066     int x, y;
7067     Boolean saveAnimate;
7068     static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0;
7069     char promoChoice = NULLCHAR;
7070     ChessSquare piece;
7071     static TimeMark lastClickTime, prevClickTime;
7072
7073     if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7074
7075     prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7076
7077     if (clickType == Press) ErrorPopDown();
7078
7079     x = EventToSquare(xPix, BOARD_WIDTH);
7080     y = EventToSquare(yPix, BOARD_HEIGHT);
7081     if (!flipView && y >= 0) {
7082         y = BOARD_HEIGHT - 1 - y;
7083     }
7084     if (flipView && x >= 0) {
7085         x = BOARD_WIDTH - 1 - x;
7086     }
7087
7088     if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7089         defaultPromoChoice = promoSweep;
7090         promoSweep = EmptySquare;   // terminate sweep
7091         promoDefaultAltered = TRUE;
7092         if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7093     }
7094
7095     if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7096         if(clickType == Release) return; // ignore upclick of click-click destination
7097         promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7098         if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7099         if(gameInfo.holdingsWidth &&
7100                 (WhiteOnMove(currentMove)
7101                         ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7102                         : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7103             // click in right holdings, for determining promotion piece
7104             ChessSquare p = boards[currentMove][y][x];
7105             if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7106             if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7107             if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7108                 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7109                 fromX = fromY = -1;
7110                 return;
7111             }
7112         }
7113         DrawPosition(FALSE, boards[currentMove]);
7114         return;
7115     }
7116
7117     /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7118     if(clickType == Press
7119             && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7120               || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7121               || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7122         return;
7123
7124     if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7125         // could be static click on premove from-square: abort premove
7126         gotPremove = 0;
7127         ClearPremoveHighlights();
7128     }
7129
7130     if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7131         fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7132
7133     if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7134         int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7135                     gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7136         defaultPromoChoice = DefaultPromoChoice(side);
7137     }
7138
7139     autoQueen = appData.alwaysPromoteToQueen;
7140
7141     if (fromX == -1) {
7142       int originalY = y;
7143       gatingPiece = EmptySquare;
7144       if (clickType != Press) {
7145         if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7146             DragPieceEnd(xPix, yPix); dragging = 0;
7147             DrawPosition(FALSE, NULL);
7148         }
7149         return;
7150       }
7151       doubleClick = FALSE;
7152       if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
7153         doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
7154       }
7155       fromX = x; fromY = y; toX = toY = -1;
7156       if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7157          // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7158          appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7159             /* First square */
7160             if (OKToStartUserMove(fromX, fromY)) {
7161                 second = 0;
7162                 MarkTargetSquares(0);
7163                 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7164                 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7165                 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7166                     promoSweep = defaultPromoChoice;
7167                     selectFlag = 0; lastX = xPix; lastY = yPix;
7168                     Sweep(0); // Pawn that is going to promote: preview promotion piece
7169                     DisplayMessage("", _("Pull pawn backwards to under-promote"));
7170                 }
7171                 if (appData.highlightDragging) {
7172                     SetHighlights(fromX, fromY, -1, -1);
7173                 } else {
7174                     ClearHighlights();
7175                 }
7176             } else fromX = fromY = -1;
7177             return;
7178         }
7179     }
7180
7181     /* fromX != -1 */
7182     if (clickType == Press && gameMode != EditPosition) {
7183         ChessSquare fromP;
7184         ChessSquare toP;
7185         int frc;
7186
7187         // ignore off-board to clicks
7188         if(y < 0 || x < 0) return;
7189
7190         /* Check if clicking again on the same color piece */
7191         fromP = boards[currentMove][fromY][fromX];
7192         toP = boards[currentMove][y][x];
7193         frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
7194         if ((WhitePawn <= fromP && fromP <= WhiteKing &&
7195              WhitePawn <= toP && toP <= WhiteKing &&
7196              !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7197              !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7198             (BlackPawn <= fromP && fromP <= BlackKing &&
7199              BlackPawn <= toP && toP <= BlackKing &&
7200              !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7201              !(fromP == BlackKing && toP == BlackRook && frc))) {
7202             /* Clicked again on same color piece -- changed his mind */
7203             second = (x == fromX && y == fromY);
7204             if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7205                 second = FALSE; // first double-click rather than scond click
7206                 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7207             }
7208             promoDefaultAltered = FALSE;
7209             MarkTargetSquares(1);
7210            if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
7211             if (appData.highlightDragging) {
7212                 SetHighlights(x, y, -1, -1);
7213             } else {
7214                 ClearHighlights();
7215             }
7216             if (OKToStartUserMove(x, y)) {
7217                 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7218                   (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7219                y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7220                  gatingPiece = boards[currentMove][fromY][fromX];
7221                 else gatingPiece = doubleClick ? fromP : EmptySquare;
7222                 fromX = x;
7223                 fromY = y; dragging = 1;
7224                 MarkTargetSquares(0);
7225                 DragPieceBegin(xPix, yPix, FALSE);
7226                 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7227                     promoSweep = defaultPromoChoice;
7228                     selectFlag = 0; lastX = xPix; lastY = yPix;
7229                     Sweep(0); // Pawn that is going to promote: preview promotion piece
7230                 }
7231             }
7232            }
7233            if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7234            second = FALSE;
7235         }
7236         // ignore clicks on holdings
7237         if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7238     }
7239
7240     if (clickType == Release && x == fromX && y == fromY) {
7241         DragPieceEnd(xPix, yPix); dragging = 0;
7242         if(clearFlag) {
7243             // a deferred attempt to click-click move an empty square on top of a piece
7244             boards[currentMove][y][x] = EmptySquare;
7245             ClearHighlights();
7246             DrawPosition(FALSE, boards[currentMove]);
7247             fromX = fromY = -1; clearFlag = 0;
7248             return;
7249         }
7250         if (appData.animateDragging) {
7251             /* Undo animation damage if any */
7252             DrawPosition(FALSE, NULL);
7253         }
7254         if (second || sweepSelecting) {
7255             /* Second up/down in same square; just abort move */
7256             if(sweepSelecting) DrawPosition(FALSE, boards[currentMove]);
7257             second = sweepSelecting = 0;
7258             fromX = fromY = -1;
7259             gatingPiece = EmptySquare;
7260             ClearHighlights();
7261             gotPremove = 0;
7262             ClearPremoveHighlights();
7263         } else {
7264             /* First upclick in same square; start click-click mode */
7265             SetHighlights(x, y, -1, -1);
7266         }
7267         return;
7268     }
7269
7270     clearFlag = 0;
7271
7272     /* we now have a different from- and (possibly off-board) to-square */
7273     /* Completed move */
7274     if(!sweepSelecting) {
7275         toX = x;
7276         toY = y;
7277     } else sweepSelecting = 0; // this must be the up-click corresponding to the down-click that started the sweep
7278
7279     saveAnimate = appData.animate;
7280     if (clickType == Press) {
7281         if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7282             // must be Edit Position mode with empty-square selected
7283             fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7284             if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7285             return;
7286         }
7287         if(HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7288           if(appData.sweepSelect) {
7289             ChessSquare piece = boards[currentMove][fromY][fromX];
7290             promoSweep = defaultPromoChoice;
7291             if(PieceToChar(PROMOTED piece) == '+') promoSweep = PROMOTED piece;
7292             selectFlag = 0; lastX = xPix; lastY = yPix;
7293             Sweep(0); // Pawn that is going to promote: preview promotion piece
7294             sweepSelecting = 1;
7295             DisplayMessage("", _("Pull pawn backwards to under-promote"));
7296             MarkTargetSquares(1);
7297           }
7298           return; // promo popup appears on up-click
7299         }
7300         /* Finish clickclick move */
7301         if (appData.animate || appData.highlightLastMove) {
7302             SetHighlights(fromX, fromY, toX, toY);
7303         } else {
7304             ClearHighlights();
7305         }
7306     } else {
7307 #if 0
7308 // [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
7309         /* Finish drag move */
7310         if (appData.highlightLastMove) {
7311             SetHighlights(fromX, fromY, toX, toY);
7312         } else {
7313             ClearHighlights();
7314         }
7315 #endif
7316         DragPieceEnd(xPix, yPix); dragging = 0;
7317         /* Don't animate move and drag both */
7318         appData.animate = FALSE;
7319     }
7320
7321     // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7322     if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7323         ChessSquare piece = boards[currentMove][fromY][fromX];
7324         if(gameMode == EditPosition && piece != EmptySquare &&
7325            fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7326             int n;
7327
7328             if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7329                 n = PieceToNumber(piece - (int)BlackPawn);
7330                 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7331                 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7332                 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7333             } else
7334             if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7335                 n = PieceToNumber(piece);
7336                 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7337                 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7338                 boards[currentMove][n][BOARD_WIDTH-2]++;
7339             }
7340             boards[currentMove][fromY][fromX] = EmptySquare;
7341         }
7342         ClearHighlights();
7343         fromX = fromY = -1;
7344         MarkTargetSquares(1);
7345         DrawPosition(TRUE, boards[currentMove]);
7346         return;
7347     }
7348
7349     // off-board moves should not be highlighted
7350     if(x < 0 || y < 0) ClearHighlights();
7351
7352     if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7353
7354     if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7355         SetHighlights(fromX, fromY, toX, toY);
7356         MarkTargetSquares(1);
7357         if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7358             // [HGM] super: promotion to captured piece selected from holdings
7359             ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7360             promotionChoice = TRUE;
7361             // kludge follows to temporarily execute move on display, without promoting yet
7362             boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7363             boards[currentMove][toY][toX] = p;
7364             DrawPosition(FALSE, boards[currentMove]);
7365             boards[currentMove][fromY][fromX] = p; // take back, but display stays
7366             boards[currentMove][toY][toX] = q;
7367             DisplayMessage("Click in holdings to choose piece", "");
7368             return;
7369         }
7370         PromotionPopUp();
7371     } else {
7372         int oldMove = currentMove;
7373         UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7374         if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7375         if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7376         if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7377            Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7378             DrawPosition(TRUE, boards[currentMove]);
7379         MarkTargetSquares(1);
7380         fromX = fromY = -1;
7381     }
7382     appData.animate = saveAnimate;
7383     if (appData.animate || appData.animateDragging) {
7384         /* Undo animation damage if needed */
7385         DrawPosition(FALSE, NULL);
7386     }
7387 }
7388
7389 int
7390 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
7391 {   // front-end-free part taken out of PieceMenuPopup
7392     int whichMenu; int xSqr, ySqr;
7393
7394     if(seekGraphUp) { // [HGM] seekgraph
7395         if(action == Press)   SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7396         if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7397         return -2;
7398     }
7399
7400     if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7401          && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7402         if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7403         if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7404         if(action == Press)   {
7405             originalFlip = flipView;
7406             flipView = !flipView; // temporarily flip board to see game from partners perspective
7407             DrawPosition(TRUE, partnerBoard);
7408             DisplayMessage(partnerStatus, "");
7409             partnerUp = TRUE;
7410         } else if(action == Release) {
7411             flipView = originalFlip;
7412             DrawPosition(TRUE, boards[currentMove]);
7413             partnerUp = FALSE;
7414         }
7415         return -2;
7416     }
7417
7418     xSqr = EventToSquare(x, BOARD_WIDTH);
7419     ySqr = EventToSquare(y, BOARD_HEIGHT);
7420     if (action == Release) {
7421         if(pieceSweep != EmptySquare) {
7422             EditPositionMenuEvent(pieceSweep, toX, toY);
7423             pieceSweep = EmptySquare;
7424         } else UnLoadPV(); // [HGM] pv
7425     }
7426     if (action != Press) return -2; // return code to be ignored
7427     switch (gameMode) {
7428       case IcsExamining:
7429         if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7430       case EditPosition:
7431         if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7432         if (xSqr < 0 || ySqr < 0) return -1;
7433         if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7434         pieceSweep = shiftKey ? BlackPawn : WhitePawn;  // [HGM] sweep: prepare selecting piece by mouse sweep
7435         toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7436         if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7437         NextPiece(0);
7438         return 2; // grab
7439       case IcsObserving:
7440         if(!appData.icsEngineAnalyze) return -1;
7441       case IcsPlayingWhite:
7442       case IcsPlayingBlack:
7443         if(!appData.zippyPlay) goto noZip;
7444       case AnalyzeMode:
7445       case AnalyzeFile:
7446       case MachinePlaysWhite:
7447       case MachinePlaysBlack:
7448       case TwoMachinesPlay: // [HGM] pv: use for showing PV
7449         if (!appData.dropMenu) {
7450           LoadPV(x, y);
7451           return 2; // flag front-end to grab mouse events
7452         }
7453         if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7454            gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7455       case EditGame:
7456       noZip:
7457         if (xSqr < 0 || ySqr < 0) return -1;
7458         if (!appData.dropMenu || appData.testLegality &&
7459             gameInfo.variant != VariantBughouse &&
7460             gameInfo.variant != VariantCrazyhouse) return -1;
7461         whichMenu = 1; // drop menu
7462         break;
7463       default:
7464         return -1;
7465     }
7466
7467     if (((*fromX = xSqr) < 0) ||
7468         ((*fromY = ySqr) < 0)) {
7469         *fromX = *fromY = -1;
7470         return -1;
7471     }
7472     if (flipView)
7473       *fromX = BOARD_WIDTH - 1 - *fromX;
7474     else
7475       *fromY = BOARD_HEIGHT - 1 - *fromY;
7476
7477     return whichMenu;
7478 }
7479
7480 void
7481 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
7482 {
7483 //    char * hint = lastHint;
7484     FrontEndProgramStats stats;
7485
7486     stats.which = cps == &first ? 0 : 1;
7487     stats.depth = cpstats->depth;
7488     stats.nodes = cpstats->nodes;
7489     stats.score = cpstats->score;
7490     stats.time = cpstats->time;
7491     stats.pv = cpstats->movelist;
7492     stats.hint = lastHint;
7493     stats.an_move_index = 0;
7494     stats.an_move_count = 0;
7495
7496     if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7497         stats.hint = cpstats->move_name;
7498         stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7499         stats.an_move_count = cpstats->nr_moves;
7500     }
7501
7502     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
7503
7504     SetProgramStats( &stats );
7505 }
7506
7507 void
7508 ClearEngineOutputPane (int which)
7509 {
7510     static FrontEndProgramStats dummyStats;
7511     dummyStats.which = which;
7512     dummyStats.pv = "#";
7513     SetProgramStats( &dummyStats );
7514 }
7515
7516 #define MAXPLAYERS 500
7517
7518 char *
7519 TourneyStandings (int display)
7520 {
7521     int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7522     int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7523     char result, *p, *names[MAXPLAYERS];
7524
7525     if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7526         return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7527     names[0] = p = strdup(appData.participants);
7528     while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7529
7530     for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7531
7532     while(result = appData.results[nr]) {
7533         color = Pairing(nr, nPlayers, &w, &b, &dummy);
7534         if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7535         wScore = bScore = 0;
7536         switch(result) {
7537           case '+': wScore = 2; break;
7538           case '-': bScore = 2; break;
7539           case '=': wScore = bScore = 1; break;
7540           case ' ':
7541           case '*': return strdup("busy"); // tourney not finished
7542         }
7543         score[w] += wScore;
7544         score[b] += bScore;
7545         games[w]++;
7546         games[b]++;
7547         nr++;
7548     }
7549     if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7550     for(w=0; w<nPlayers; w++) {
7551         bScore = -1;
7552         for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7553         ranking[w] = b; points[w] = bScore; score[b] = -2;
7554     }
7555     p = malloc(nPlayers*34+1);
7556     for(w=0; w<nPlayers && w<display; w++)
7557         sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7558     free(names[0]);
7559     return p;
7560 }
7561
7562 void
7563 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7564 {       // count all piece types
7565         int p, f, r;
7566         *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7567         for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7568         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7569                 p = board[r][f];
7570                 pCnt[p]++;
7571                 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7572                 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7573                 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7574                 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7575                    p == BlackBishop || p == BlackFerz || p == BlackAlfil   )
7576                         *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7577         }
7578 }
7579
7580 int
7581 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
7582 {
7583         int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7584         int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7585
7586         nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7587         if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7588         if(myPawns == 2 && nMine == 3) // KPP
7589             return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7590         if(myPawns == 1 && nMine == 2) // KP
7591             return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]  + pCnt[BlackPawn-side] >= 1;
7592         if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7593             return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7594         if(myPawns) return FALSE;
7595         if(pCnt[WhiteRook+side])
7596             return pCnt[BlackRook-side] ||
7597                    pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7598                    pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7599                    pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7600         if(pCnt[WhiteCannon+side]) {
7601             if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7602             return majorDefense || pCnt[BlackAlfil-side] >= 2;
7603         }
7604         if(pCnt[WhiteKnight+side])
7605             return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7606         return FALSE;
7607 }
7608
7609 int
7610 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7611 {
7612         VariantClass v = gameInfo.variant;
7613
7614         if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7615         if(v == VariantShatranj) return TRUE; // always winnable through baring
7616         if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7617         if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7618
7619         if(v == VariantXiangqi) {
7620                 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7621
7622                 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7623                 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7624                 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7625                 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7626                 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7627                 if(stale) // we have at least one last-rank P plus perhaps C
7628                     return majors // KPKX
7629                         || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7630                 else // KCA*E*
7631                     return pCnt[WhiteFerz+side] // KCAK
7632                         || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7633                         || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
7634                 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
7635
7636         } else if(v == VariantKnightmate) {
7637                 if(nMine == 1) return FALSE;
7638                 if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
7639         } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
7640                 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7641
7642                 if(nMine == 1) return FALSE; // bare King
7643                 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
7644                 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7645                 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7646                 // by now we have King + 1 piece (or multiple Bishops on the same color)
7647                 if(pCnt[WhiteKnight+side])
7648                         return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7649                                 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7650                              || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7651                 if(nBishops)
7652                         return (pCnt[BlackKnight-side]); // KBKN, KFKN
7653                 if(pCnt[WhiteAlfil+side])
7654                         return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
7655                 if(pCnt[WhiteWazir+side])
7656                         return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7657         }
7658
7659         return TRUE;
7660 }
7661
7662 int
7663 CompareWithRights (Board b1, Board b2)
7664 {
7665     int rights = 0;
7666     if(!CompareBoards(b1, b2)) return FALSE;
7667     if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
7668     /* compare castling rights */
7669     if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
7670            rights++; /* King lost rights, while rook still had them */
7671     if( b1[CASTLING][2] != NoRights ) { /* king has rights */
7672         if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
7673            rights++; /* but at least one rook lost them */
7674     }
7675     if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
7676            rights++;
7677     if( b1[CASTLING][5] != NoRights ) {
7678         if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
7679            rights++;
7680     }
7681     return rights == 0;
7682 }
7683
7684 int
7685 Adjudicate (ChessProgramState *cps)
7686 {       // [HGM] some adjudications useful with buggy engines
7687         // [HGM] adjudicate: made into separate routine, which now can be called after every move
7688         //       In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7689         //       Actually ending the game is now based on the additional internal condition canAdjudicate.
7690         //       Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7691         int k, drop, count = 0; static int bare = 1;
7692         ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7693         Boolean canAdjudicate = !appData.icsActive;
7694
7695         // most tests only when we understand the game, i.e. legality-checking on
7696             if( appData.testLegality )
7697             {   /* [HGM] Some more adjudications for obstinate engines */
7698                 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7699                 static int moveCount = 6;
7700                 ChessMove result;
7701                 char *reason = NULL;
7702
7703                 /* Count what is on board. */
7704                 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7705
7706                 /* Some material-based adjudications that have to be made before stalemate test */
7707                 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7708                     // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7709                      boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7710                      if(canAdjudicate && appData.checkMates) {
7711                          if(engineOpponent)
7712                            SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7713                          GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7714                                                         "Xboard adjudication: King destroyed", GE_XBOARD );
7715                          return 1;
7716                      }
7717                 }
7718
7719                 /* Bare King in Shatranj (loses) or Losers (wins) */
7720                 if( nrW == 1 || nrB == 1) {
7721                   if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7722                      boards[forwardMostMove][EP_STATUS] = EP_WINS;  // mark as win, so it becomes claimable
7723                      if(canAdjudicate && appData.checkMates) {
7724                          if(engineOpponent)
7725                            SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7726                          GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7727                                                         "Xboard adjudication: Bare king", GE_XBOARD );
7728                          return 1;
7729                      }
7730                   } else
7731                   if( gameInfo.variant == VariantShatranj && --bare < 0)
7732                   {    /* bare King */
7733                         boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7734                         if(canAdjudicate && appData.checkMates) {
7735                             /* but only adjudicate if adjudication enabled */
7736                             if(engineOpponent)
7737                               SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7738                             GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7739                                                         "Xboard adjudication: Bare king", GE_XBOARD );
7740                             return 1;
7741                         }
7742                   }
7743                 } else bare = 1;
7744
7745
7746             // don't wait for engine to announce game end if we can judge ourselves
7747             switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7748               case MT_CHECK:
7749                 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7750                     int i, checkCnt = 0;    // (should really be done by making nr of checks part of game state)
7751                     for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7752                         if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7753                             checkCnt++;
7754                         if(checkCnt >= 2) {
7755                             reason = "Xboard adjudication: 3rd check";
7756                             boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7757                             break;
7758                         }
7759                     }
7760                 }
7761               case MT_NONE:
7762               default:
7763                 break;
7764               case MT_STALEMATE:
7765               case MT_STAINMATE:
7766                 reason = "Xboard adjudication: Stalemate";
7767                 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7768                     boards[forwardMostMove][EP_STATUS] = EP_STALEMATE;   // default result for stalemate is draw
7769                     if(gameInfo.variant == VariantLosers  || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7770                         boards[forwardMostMove][EP_STATUS] = EP_WINS;    // in these variants stalemated is always a win
7771                     else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7772                         boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7773                                                    ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7774                                                                         EP_CHECKMATE : EP_WINS);
7775                     else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
7776                         boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7777                 }
7778                 break;
7779               case MT_CHECKMATE:
7780                 reason = "Xboard adjudication: Checkmate";
7781                 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7782                 if(gameInfo.variant == VariantShogi) {
7783                     if(forwardMostMove > backwardMostMove
7784                        && moveList[forwardMostMove-1][1] == '@'
7785                        && CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
7786                         reason = "XBoard adjudication: pawn-drop mate";
7787                         boards[forwardMostMove][EP_STATUS] = EP_WINS;
7788                     }
7789                 }
7790                 break;
7791             }
7792
7793                 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7794                     case EP_STALEMATE:
7795                         result = GameIsDrawn; break;
7796                     case EP_CHECKMATE:
7797                         result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7798                     case EP_WINS:
7799                         result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7800                     default:
7801                         result = EndOfFile;
7802                 }
7803                 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7804                     if(engineOpponent)
7805                       SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7806                     GameEnds( result, reason, GE_XBOARD );
7807                     return 1;
7808                 }
7809
7810                 /* Next absolutely insufficient mating material. */
7811                 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7812                    !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7813                 {    /* includes KBK, KNK, KK of KBKB with like Bishops */
7814
7815                      /* always flag draws, for judging claims */
7816                      boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7817
7818                      if(canAdjudicate && appData.materialDraws) {
7819                          /* but only adjudicate them if adjudication enabled */
7820                          if(engineOpponent) {
7821                            SendToProgram("force\n", engineOpponent); // suppress reply
7822                            SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7823                          }
7824                          GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7825                          return 1;
7826                      }
7827                 }
7828
7829                 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7830                 if(gameInfo.variant == VariantXiangqi ?
7831                        SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7832                  : nrW + nrB == 4 &&
7833                    (   nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7834                    || nr[WhiteQueen] && nr[BlackQueen]==1     /* KQKQ */
7835                    || nr[WhiteKnight]==2 || nr[BlackKnight]==2     /* KNNK */
7836                    || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7837                    ) ) {
7838                      if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7839                      {    /* if the first 3 moves do not show a tactical win, declare draw */
7840                           if(engineOpponent) {
7841                             SendToProgram("force\n", engineOpponent); // suppress reply
7842                             SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7843                           }
7844                           GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7845                           return 1;
7846                      }
7847                 } else moveCount = 6;
7848             }
7849
7850         // Repetition draws and 50-move rule can be applied independently of legality testing
7851
7852                 /* Check for rep-draws */
7853                 count = 0;
7854                 drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
7855                                               && gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
7856                 for(k = forwardMostMove-2;
7857                     k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
7858                         (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7859                         (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
7860                     k-=2)
7861                 {   int rights=0;
7862                     if(CompareBoards(boards[k], boards[forwardMostMove])) {
7863                         /* compare castling rights */
7864                         if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7865                              (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7866                                 rights++; /* King lost rights, while rook still had them */
7867                         if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7868                             if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7869                                 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7870                                    rights++; /* but at least one rook lost them */
7871                         }
7872                         if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7873                              (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7874                                 rights++;
7875                         if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7876                             if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7877                                 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7878                                    rights++;
7879                         }
7880                         if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7881                             && appData.drawRepeats > 1) {
7882                              /* adjudicate after user-specified nr of repeats */
7883                              int result = GameIsDrawn;
7884                              char *details = "XBoard adjudication: repetition draw";
7885                              if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
7886                                 // [HGM] xiangqi: check for forbidden perpetuals
7887                                 int m, ourPerpetual = 1, hisPerpetual = 1;
7888                                 for(m=forwardMostMove; m>k; m-=2) {
7889                                     if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7890                                         ourPerpetual = 0; // the current mover did not always check
7891                                     if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7892                                         hisPerpetual = 0; // the opponent did not always check
7893                                 }
7894                                 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7895                                                                         ourPerpetual, hisPerpetual);
7896                                 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7897                                     result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7898                                     details = "Xboard adjudication: perpetual checking";
7899                                 } else
7900                                 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7901                                     break; // (or we would have caught him before). Abort repetition-checking loop.
7902                                 } else
7903                                 if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
7904                                     if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
7905                                         result = BlackWins;
7906                                         details = "Xboard adjudication: repetition";
7907                                     }
7908                                 } else // it must be XQ
7909                                 // Now check for perpetual chases
7910                                 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7911                                     hisPerpetual = PerpetualChase(k, forwardMostMove);
7912                                     ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7913                                     if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7914                                         static char resdet[MSG_SIZ];
7915                                         result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7916                                         details = resdet;
7917                                         snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
7918                                     } else
7919                                     if(hisPerpetual && !ourPerpetual)   // he is chasing us, but did not repeat yet
7920                                         break; // Abort repetition-checking loop.
7921                                 }
7922                                 // if neither of us is checking or chasing all the time, or both are, it is draw
7923                              }
7924                              if(engineOpponent) {
7925                                SendToProgram("force\n", engineOpponent); // suppress reply
7926                                SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7927                              }
7928                              GameEnds( result, details, GE_XBOARD );
7929                              return 1;
7930                         }
7931                         if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7932                              boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7933                     }
7934                 }
7935
7936                 /* Now we test for 50-move draws. Determine ply count */
7937                 count = forwardMostMove;
7938                 /* look for last irreversble move */
7939                 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7940                     count--;
7941                 /* if we hit starting position, add initial plies */
7942                 if( count == backwardMostMove )
7943                     count -= initialRulePlies;
7944                 count = forwardMostMove - count;
7945                 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7946                         // adjust reversible move counter for checks in Xiangqi
7947                         int i = forwardMostMove - count, inCheck = 0, lastCheck;
7948                         if(i < backwardMostMove) i = backwardMostMove;
7949                         while(i <= forwardMostMove) {
7950                                 lastCheck = inCheck; // check evasion does not count
7951                                 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7952                                 if(inCheck || lastCheck) count--; // check does not count
7953                                 i++;
7954                         }
7955                 }
7956                 if( count >= 100)
7957                          boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7958                          /* this is used to judge if draw claims are legal */
7959                 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7960                          if(engineOpponent) {
7961                            SendToProgram("force\n", engineOpponent); // suppress reply
7962                            SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7963                          }
7964                          GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7965                          return 1;
7966                 }
7967
7968                 /* if draw offer is pending, treat it as a draw claim
7969                  * when draw condition present, to allow engines a way to
7970                  * claim draws before making their move to avoid a race
7971                  * condition occurring after their move
7972                  */
7973                 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7974                          char *p = NULL;
7975                          if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7976                              p = "Draw claim: 50-move rule";
7977                          if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7978                              p = "Draw claim: 3-fold repetition";
7979                          if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7980                              p = "Draw claim: insufficient mating material";
7981                          if( p != NULL && canAdjudicate) {
7982                              if(engineOpponent) {
7983                                SendToProgram("force\n", engineOpponent); // suppress reply
7984                                SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7985                              }
7986                              GameEnds( GameIsDrawn, p, GE_XBOARD );
7987                              return 1;
7988                          }
7989                 }
7990
7991                 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7992                     if(engineOpponent) {
7993                       SendToProgram("force\n", engineOpponent); // suppress reply
7994                       SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7995                     }
7996                     GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7997                     return 1;
7998                 }
7999         return 0;
8000 }
8001
8002 char *
8003 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
8004 {   // [HGM] book: this routine intercepts moves to simulate book replies
8005     char *bookHit = NULL;
8006
8007     //first determine if the incoming move brings opponent into his book
8008     if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
8009         bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
8010     if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
8011     if(bookHit != NULL && !cps->bookSuspend) {
8012         // make sure opponent is not going to reply after receiving move to book position
8013         SendToProgram("force\n", cps);
8014         cps->bookSuspend = TRUE; // flag indicating it has to be restarted
8015     }
8016     if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
8017     // now arrange restart after book miss
8018     if(bookHit) {
8019         // after a book hit we never send 'go', and the code after the call to this routine
8020         // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
8021         char buf[MSG_SIZ], *move = bookHit;
8022         if(cps->useSAN) {
8023             int fromX, fromY, toX, toY;
8024             char promoChar;
8025             ChessMove moveType;
8026             move = buf + 30;
8027             if (ParseOneMove(bookHit, forwardMostMove, &moveType,
8028                                  &fromX, &fromY, &toX, &toY, &promoChar)) {
8029                 (void) CoordsToAlgebraic(boards[forwardMostMove],
8030                                     PosFlags(forwardMostMove),
8031                                     fromY, fromX, toY, toX, promoChar, move);
8032             } else {
8033                 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
8034                 bookHit = NULL;
8035             }
8036         }
8037         snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
8038         SendToProgram(buf, cps);
8039         if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
8040     } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
8041         SendToProgram("go\n", cps);
8042         cps->bookSuspend = FALSE; // after a 'go' we are never suspended
8043     } else { // 'go' might be sent based on 'firstMove' after this routine returns
8044         if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
8045             SendToProgram("go\n", cps);
8046         cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
8047     }
8048     return bookHit; // notify caller of hit, so it can take action to send move to opponent
8049 }
8050
8051 int
8052 LoadError (char *errmess, ChessProgramState *cps)
8053 {   // unloads engine and switches back to -ncp mode if it was first
8054     if(cps->initDone) return FALSE;
8055     cps->isr = NULL; // this should suppress further error popups from breaking pipes
8056     DestroyChildProcess(cps->pr, 9 ); // just to be sure
8057     cps->pr = NoProc;
8058     if(cps == &first) {
8059         appData.noChessProgram = TRUE;
8060         gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
8061         gameMode = BeginningOfGame; ModeHighlight();
8062         SetNCPMode();
8063     }
8064     if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
8065     DisplayMessage("", ""); // erase waiting message
8066     if(errmess) DisplayError(errmess, 0); // announce reason, if given
8067     return TRUE;
8068 }
8069
8070 char *savedMessage;
8071 ChessProgramState *savedState;
8072 void
8073 DeferredBookMove (void)
8074 {
8075         if(savedState->lastPing != savedState->lastPong)
8076                     ScheduleDelayedEvent(DeferredBookMove, 10);
8077         else
8078         HandleMachineMove(savedMessage, savedState);
8079 }
8080
8081 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8082 static ChessProgramState *stalledEngine;
8083 static char stashedInputMove[MSG_SIZ];
8084
8085 void
8086 HandleMachineMove (char *message, ChessProgramState *cps)
8087 {
8088     char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8089     char realname[MSG_SIZ];
8090     int fromX, fromY, toX, toY;
8091     ChessMove moveType;
8092     char promoChar;
8093     char *p, *pv=buf1;
8094     int machineWhite, oldError;
8095     char *bookHit;
8096
8097     if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8098         // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8099         if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8100             DisplayError(_("Invalid pairing from pairing engine"), 0);
8101             return;
8102         }
8103         pairingReceived = 1;
8104         NextMatchGame();
8105         return; // Skim the pairing messages here.
8106     }
8107
8108     oldError = cps->userError; cps->userError = 0;
8109
8110 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8111     /*
8112      * Kludge to ignore BEL characters
8113      */
8114     while (*message == '\007') message++;
8115
8116     /*
8117      * [HGM] engine debug message: ignore lines starting with '#' character
8118      */
8119     if(cps->debug && *message == '#') return;
8120
8121     /*
8122      * Look for book output
8123      */
8124     if (cps == &first && bookRequested) {
8125         if (message[0] == '\t' || message[0] == ' ') {
8126             /* Part of the book output is here; append it */
8127             strcat(bookOutput, message);
8128             strcat(bookOutput, "  \n");
8129             return;
8130         } else if (bookOutput[0] != NULLCHAR) {
8131             /* All of book output has arrived; display it */
8132             char *p = bookOutput;
8133             while (*p != NULLCHAR) {
8134                 if (*p == '\t') *p = ' ';
8135                 p++;
8136             }
8137             DisplayInformation(bookOutput);
8138             bookRequested = FALSE;
8139             /* Fall through to parse the current output */
8140         }
8141     }
8142
8143     /*
8144      * Look for machine move.
8145      */
8146     if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8147         (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8148     {
8149         if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
8150             if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
8151             safeStrCpy(stashedInputMove, message, MSG_SIZ);
8152             stalledEngine = cps;
8153             if(appData.ponderNextMove) { // bring opponent out of ponder
8154                 if(gameMode == TwoMachinesPlay) {
8155                     if(cps->other->pause)
8156                         PauseEngine(cps->other);
8157                     else
8158                         SendToProgram("easy\n", cps->other);
8159                 }
8160             }
8161             StopClocks();
8162             return;
8163         }
8164
8165         /* This method is only useful on engines that support ping */
8166         if (cps->lastPing != cps->lastPong) {
8167           if (gameMode == BeginningOfGame) {
8168             /* Extra move from before last new; ignore */
8169             if (appData.debugMode) {
8170                 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8171             }
8172           } else {
8173             if (appData.debugMode) {
8174                 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8175                         cps->which, gameMode);
8176             }
8177
8178             SendToProgram("undo\n", cps);
8179           }
8180           return;
8181         }
8182
8183         switch (gameMode) {
8184           case BeginningOfGame:
8185             /* Extra move from before last reset; ignore */
8186             if (appData.debugMode) {
8187                 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8188             }
8189             return;
8190
8191           case EndOfGame:
8192           case IcsIdle:
8193           default:
8194             /* Extra move after we tried to stop.  The mode test is
8195                not a reliable way of detecting this problem, but it's
8196                the best we can do on engines that don't support ping.
8197             */
8198             if (appData.debugMode) {
8199                 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8200                         cps->which, gameMode);
8201             }
8202             SendToProgram("undo\n", cps);
8203             return;
8204
8205           case MachinePlaysWhite:
8206           case IcsPlayingWhite:
8207             machineWhite = TRUE;
8208             break;
8209
8210           case MachinePlaysBlack:
8211           case IcsPlayingBlack:
8212             machineWhite = FALSE;
8213             break;
8214
8215           case TwoMachinesPlay:
8216             machineWhite = (cps->twoMachinesColor[0] == 'w');
8217             break;
8218         }
8219         if (WhiteOnMove(forwardMostMove) != machineWhite) {
8220             if (appData.debugMode) {
8221                 fprintf(debugFP,
8222                         "Ignoring move out of turn by %s, gameMode %d"
8223                         ", forwardMost %d\n",
8224                         cps->which, gameMode, forwardMostMove);
8225             }
8226             return;
8227         }
8228
8229         if(cps->alphaRank) AlphaRank(machineMove, 4);
8230         if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
8231                               &fromX, &fromY, &toX, &toY, &promoChar)) {
8232             /* Machine move could not be parsed; ignore it. */
8233           snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
8234                     machineMove, _(cps->which));
8235             DisplayMoveError(buf1);
8236             snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
8237                     machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
8238             if (gameMode == TwoMachinesPlay) {
8239               GameEnds(machineWhite ? BlackWins : WhiteWins,
8240                        buf1, GE_XBOARD);
8241             }
8242             return;
8243         }
8244
8245         /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
8246         /* So we have to redo legality test with true e.p. status here,  */
8247         /* to make sure an illegal e.p. capture does not slip through,   */
8248         /* to cause a forfeit on a justified illegal-move complaint      */
8249         /* of the opponent.                                              */
8250         if( gameMode==TwoMachinesPlay && appData.testLegality ) {
8251            ChessMove moveType;
8252            moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
8253                              fromY, fromX, toY, toX, promoChar);
8254             if(moveType == IllegalMove) {
8255               snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
8256                         machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
8257                 GameEnds(machineWhite ? BlackWins : WhiteWins,
8258                            buf1, GE_XBOARD);
8259                 return;
8260            } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
8261            /* [HGM] Kludge to handle engines that send FRC-style castling
8262               when they shouldn't (like TSCP-Gothic) */
8263            switch(moveType) {
8264              case WhiteASideCastleFR:
8265              case BlackASideCastleFR:
8266                toX+=2;
8267                currentMoveString[2]++;
8268                break;
8269              case WhiteHSideCastleFR:
8270              case BlackHSideCastleFR:
8271                toX--;
8272                currentMoveString[2]--;
8273                break;
8274              default: ; // nothing to do, but suppresses warning of pedantic compilers
8275            }
8276         }
8277         hintRequested = FALSE;
8278         lastHint[0] = NULLCHAR;
8279         bookRequested = FALSE;
8280         /* Program may be pondering now */
8281         cps->maybeThinking = TRUE;
8282         if (cps->sendTime == 2) cps->sendTime = 1;
8283         if (cps->offeredDraw) cps->offeredDraw--;
8284
8285         /* [AS] Save move info*/
8286         pvInfoList[ forwardMostMove ].score = programStats.score;
8287         pvInfoList[ forwardMostMove ].depth = programStats.depth;
8288         pvInfoList[ forwardMostMove ].time =  programStats.time; // [HGM] PGNtime: take time from engine stats
8289
8290         MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
8291
8292         /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
8293         if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
8294             int count = 0;
8295
8296             while( count < adjudicateLossPlies ) {
8297                 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
8298
8299                 if( count & 1 ) {
8300                     score = -score; /* Flip score for winning side */
8301                 }
8302
8303                 if( score > adjudicateLossThreshold ) {
8304                     break;
8305                 }
8306
8307                 count++;
8308             }
8309
8310             if( count >= adjudicateLossPlies ) {
8311                 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8312
8313                 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8314                     "Xboard adjudication",
8315                     GE_XBOARD );
8316
8317                 return;
8318             }
8319         }
8320
8321         if(Adjudicate(cps)) {
8322             ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8323             return; // [HGM] adjudicate: for all automatic game ends
8324         }
8325
8326 #if ZIPPY
8327         if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8328             first.initDone) {
8329           if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8330                 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8331                 SendToICS("draw ");
8332                 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8333           }
8334           SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8335           ics_user_moved = 1;
8336           if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8337                 char buf[3*MSG_SIZ];
8338
8339                 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8340                         programStats.score / 100.,
8341                         programStats.depth,
8342                         programStats.time / 100.,
8343                         (unsigned int)programStats.nodes,
8344                         (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8345                         programStats.movelist);
8346                 SendToICS(buf);
8347 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
8348           }
8349         }
8350 #endif
8351
8352         /* [AS] Clear stats for next move */
8353         ClearProgramStats();
8354         thinkOutput[0] = NULLCHAR;
8355         hiddenThinkOutputState = 0;
8356
8357         bookHit = NULL;
8358         if (gameMode == TwoMachinesPlay) {
8359             /* [HGM] relaying draw offers moved to after reception of move */
8360             /* and interpreting offer as claim if it brings draw condition */
8361             if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8362                 SendToProgram("draw\n", cps->other);
8363             }
8364             if (cps->other->sendTime) {
8365                 SendTimeRemaining(cps->other,
8366                                   cps->other->twoMachinesColor[0] == 'w');
8367             }
8368             bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8369             if (firstMove && !bookHit) {
8370                 firstMove = FALSE;
8371                 if (cps->other->useColors) {
8372                   SendToProgram(cps->other->twoMachinesColor, cps->other);
8373                 }
8374                 SendToProgram("go\n", cps->other);
8375             }
8376             cps->other->maybeThinking = TRUE;
8377         }
8378
8379         ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8380
8381         if (!pausing && appData.ringBellAfterMoves) {
8382             RingBell();
8383         }
8384
8385         /*
8386          * Reenable menu items that were disabled while
8387          * machine was thinking
8388          */
8389         if (gameMode != TwoMachinesPlay)
8390             SetUserThinkingEnables();
8391
8392         // [HGM] book: after book hit opponent has received move and is now in force mode
8393         // force the book reply into it, and then fake that it outputted this move by jumping
8394         // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8395         if(bookHit) {
8396                 static char bookMove[MSG_SIZ]; // a bit generous?
8397
8398                 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8399                 strcat(bookMove, bookHit);
8400                 message = bookMove;
8401                 cps = cps->other;
8402                 programStats.nodes = programStats.depth = programStats.time =
8403                 programStats.score = programStats.got_only_move = 0;
8404                 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8405
8406                 if(cps->lastPing != cps->lastPong) {
8407                     savedMessage = message; // args for deferred call
8408                     savedState = cps;
8409                     ScheduleDelayedEvent(DeferredBookMove, 10);
8410                     return;
8411                 }
8412                 goto FakeBookMove;
8413         }
8414
8415         return;
8416     }
8417
8418     /* Set special modes for chess engines.  Later something general
8419      *  could be added here; for now there is just one kludge feature,
8420      *  needed because Crafty 15.10 and earlier don't ignore SIGINT
8421      *  when "xboard" is given as an interactive command.
8422      */
8423     if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8424         cps->useSigint = FALSE;
8425         cps->useSigterm = FALSE;
8426     }
8427     if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8428       ParseFeatures(message+8, cps);
8429       return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8430     }
8431
8432     if (!strncmp(message, "setup ", 6) && 
8433         (!appData.testLegality || gameInfo.variant == VariantFairy || NonStandardBoardSize())
8434                                         ) { // [HGM] allow first engine to define opening position
8435       int dummy, s=6; char buf[MSG_SIZ];
8436       if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
8437       if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
8438       if(startedFromSetupPosition) return;
8439       if(sscanf(message+s, "%dx%d+%d", &dummy, &dummy, &dummy) == 3) while(message[s] && message[s++] != ' '); // for compatibility with Alien Edition
8440       ParseFEN(boards[0], &dummy, message+s);
8441       DrawPosition(TRUE, boards[0]);
8442       startedFromSetupPosition = TRUE;
8443       return;
8444     }
8445     /* [HGM] Allow engine to set up a position. Don't ask me why one would
8446      * want this, I was asked to put it in, and obliged.
8447      */
8448     if (!strncmp(message, "setboard ", 9)) {
8449         Board initial_position;
8450
8451         GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
8452
8453         if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
8454             DisplayError(_("Bad FEN received from engine"), 0);
8455             return ;
8456         } else {
8457            Reset(TRUE, FALSE);
8458            CopyBoard(boards[0], initial_position);
8459            initialRulePlies = FENrulePlies;
8460            if(blackPlaysFirst) gameMode = MachinePlaysWhite;
8461            else gameMode = MachinePlaysBlack;
8462            DrawPosition(FALSE, boards[currentMove]);
8463         }
8464         return;
8465     }
8466
8467     /*
8468      * Look for communication commands
8469      */
8470     if (!strncmp(message, "telluser ", 9)) {
8471         if(message[9] == '\\' && message[10] == '\\')
8472             EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
8473         PlayTellSound();
8474         DisplayNote(message + 9);
8475         return;
8476     }
8477     if (!strncmp(message, "tellusererror ", 14)) {
8478         cps->userError = 1;
8479         if(message[14] == '\\' && message[15] == '\\')
8480             EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
8481         PlayTellSound();
8482         DisplayError(message + 14, 0);
8483         return;
8484     }
8485     if (!strncmp(message, "tellopponent ", 13)) {
8486       if (appData.icsActive) {
8487         if (loggedOn) {
8488           snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
8489           SendToICS(buf1);
8490         }
8491       } else {
8492         DisplayNote(message + 13);
8493       }
8494       return;
8495     }
8496     if (!strncmp(message, "tellothers ", 11)) {
8497       if (appData.icsActive) {
8498         if (loggedOn) {
8499           snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
8500           SendToICS(buf1);
8501         }
8502       } else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
8503       return;
8504     }
8505     if (!strncmp(message, "tellall ", 8)) {
8506       if (appData.icsActive) {
8507         if (loggedOn) {
8508           snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
8509           SendToICS(buf1);
8510         }
8511       } else {
8512         DisplayNote(message + 8);
8513       }
8514       return;
8515     }
8516     if (strncmp(message, "warning", 7) == 0) {
8517         /* Undocumented feature, use tellusererror in new code */
8518         DisplayError(message, 0);
8519         return;
8520     }
8521     if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
8522         safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
8523         strcat(realname, " query");
8524         AskQuestion(realname, buf2, buf1, cps->pr);
8525         return;
8526     }
8527     /* Commands from the engine directly to ICS.  We don't allow these to be
8528      *  sent until we are logged on. Crafty kibitzes have been known to
8529      *  interfere with the login process.
8530      */
8531     if (loggedOn) {
8532         if (!strncmp(message, "tellics ", 8)) {
8533             SendToICS(message + 8);
8534             SendToICS("\n");
8535             return;
8536         }
8537         if (!strncmp(message, "tellicsnoalias ", 15)) {
8538             SendToICS(ics_prefix);
8539             SendToICS(message + 15);
8540             SendToICS("\n");
8541             return;
8542         }
8543         /* The following are for backward compatibility only */
8544         if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
8545             !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
8546             SendToICS(ics_prefix);
8547             SendToICS(message);
8548             SendToICS("\n");
8549             return;
8550         }
8551     }
8552     if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
8553         return;
8554     }
8555     /*
8556      * If the move is illegal, cancel it and redraw the board.
8557      * Also deal with other error cases.  Matching is rather loose
8558      * here to accommodate engines written before the spec.
8559      */
8560     if (strncmp(message + 1, "llegal move", 11) == 0 ||
8561         strncmp(message, "Error", 5) == 0) {
8562         if (StrStr(message, "name") ||
8563             StrStr(message, "rating") || StrStr(message, "?") ||
8564             StrStr(message, "result") || StrStr(message, "board") ||
8565             StrStr(message, "bk") || StrStr(message, "computer") ||
8566             StrStr(message, "variant") || StrStr(message, "hint") ||
8567             StrStr(message, "random") || StrStr(message, "depth") ||
8568             StrStr(message, "accepted")) {
8569             return;
8570         }
8571         if (StrStr(message, "protover")) {
8572           /* Program is responding to input, so it's apparently done
8573              initializing, and this error message indicates it is
8574              protocol version 1.  So we don't need to wait any longer
8575              for it to initialize and send feature commands. */
8576           FeatureDone(cps, 1);
8577           cps->protocolVersion = 1;
8578           return;
8579         }
8580         cps->maybeThinking = FALSE;
8581
8582         if (StrStr(message, "draw")) {
8583             /* Program doesn't have "draw" command */
8584             cps->sendDrawOffers = 0;
8585             return;
8586         }
8587         if (cps->sendTime != 1 &&
8588             (StrStr(message, "time") || StrStr(message, "otim"))) {
8589           /* Program apparently doesn't have "time" or "otim" command */
8590           cps->sendTime = 0;
8591           return;
8592         }
8593         if (StrStr(message, "analyze")) {
8594             cps->analysisSupport = FALSE;
8595             cps->analyzing = FALSE;
8596 //          Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
8597             EditGameEvent(); // [HGM] try to preserve loaded game
8598             snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
8599             DisplayError(buf2, 0);
8600             return;
8601         }
8602         if (StrStr(message, "(no matching move)st")) {
8603           /* Special kludge for GNU Chess 4 only */
8604           cps->stKludge = TRUE;
8605           SendTimeControl(cps, movesPerSession, timeControl,
8606                           timeIncrement, appData.searchDepth,
8607                           searchTime);
8608           return;
8609         }
8610         if (StrStr(message, "(no matching move)sd")) {
8611           /* Special kludge for GNU Chess 4 only */
8612           cps->sdKludge = TRUE;
8613           SendTimeControl(cps, movesPerSession, timeControl,
8614                           timeIncrement, appData.searchDepth,
8615                           searchTime);
8616           return;
8617         }
8618         if (!StrStr(message, "llegal")) {
8619             return;
8620         }
8621         if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8622             gameMode == IcsIdle) return;
8623         if (forwardMostMove <= backwardMostMove) return;
8624         if (pausing) PauseEvent();
8625       if(appData.forceIllegal) {
8626             // [HGM] illegal: machine refused move; force position after move into it
8627           SendToProgram("force\n", cps);
8628           if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
8629                 // we have a real problem now, as SendBoard will use the a2a3 kludge
8630                 // when black is to move, while there might be nothing on a2 or black
8631                 // might already have the move. So send the board as if white has the move.
8632                 // But first we must change the stm of the engine, as it refused the last move
8633                 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
8634                 if(WhiteOnMove(forwardMostMove)) {
8635                     SendToProgram("a7a6\n", cps); // for the engine black still had the move
8636                     SendBoard(cps, forwardMostMove); // kludgeless board
8637                 } else {
8638                     SendToProgram("a2a3\n", cps); // for the engine white still had the move
8639                     CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8640                     SendBoard(cps, forwardMostMove+1); // kludgeless board
8641                 }
8642           } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
8643             if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
8644                  gameMode == TwoMachinesPlay)
8645               SendToProgram("go\n", cps);
8646             return;
8647       } else
8648         if (gameMode == PlayFromGameFile) {
8649             /* Stop reading this game file */
8650             gameMode = EditGame;
8651             ModeHighlight();
8652         }
8653         /* [HGM] illegal-move claim should forfeit game when Xboard */
8654         /* only passes fully legal moves                            */
8655         if( appData.testLegality && gameMode == TwoMachinesPlay ) {
8656             GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
8657                                 "False illegal-move claim", GE_XBOARD );
8658             return; // do not take back move we tested as valid
8659         }
8660         currentMove = forwardMostMove-1;
8661         DisplayMove(currentMove-1); /* before DisplayMoveError */
8662         SwitchClocks(forwardMostMove-1); // [HGM] race
8663         DisplayBothClocks();
8664         snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
8665                 parseList[currentMove], _(cps->which));
8666         DisplayMoveError(buf1);
8667         DrawPosition(FALSE, boards[currentMove]);
8668
8669         SetUserThinkingEnables();
8670         return;
8671     }
8672     if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
8673         /* Program has a broken "time" command that
8674            outputs a string not ending in newline.
8675            Don't use it. */
8676         cps->sendTime = 0;
8677     }
8678
8679     /*
8680      * If chess program startup fails, exit with an error message.
8681      * Attempts to recover here are futile. [HGM] Well, we try anyway
8682      */
8683     if ((StrStr(message, "unknown host") != NULL)
8684         || (StrStr(message, "No remote directory") != NULL)
8685         || (StrStr(message, "not found") != NULL)
8686         || (StrStr(message, "No such file") != NULL)
8687         || (StrStr(message, "can't alloc") != NULL)
8688         || (StrStr(message, "Permission denied") != NULL)) {
8689
8690         cps->maybeThinking = FALSE;
8691         snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
8692                 _(cps->which), cps->program, cps->host, message);
8693         RemoveInputSource(cps->isr);
8694         if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
8695             if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
8696             if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
8697         }
8698         return;
8699     }
8700
8701     /*
8702      * Look for hint output
8703      */
8704     if (sscanf(message, "Hint: %s", buf1) == 1) {
8705         if (cps == &first && hintRequested) {
8706             hintRequested = FALSE;
8707             if (ParseOneMove(buf1, forwardMostMove, &moveType,
8708                                  &fromX, &fromY, &toX, &toY, &promoChar)) {
8709                 (void) CoordsToAlgebraic(boards[forwardMostMove],
8710                                     PosFlags(forwardMostMove),
8711                                     fromY, fromX, toY, toX, promoChar, buf1);
8712                 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
8713                 DisplayInformation(buf2);
8714             } else {
8715                 /* Hint move could not be parsed!? */
8716               snprintf(buf2, sizeof(buf2),
8717                         _("Illegal hint move \"%s\"\nfrom %s chess program"),
8718                         buf1, _(cps->which));
8719                 DisplayError(buf2, 0);
8720             }
8721         } else {
8722           safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
8723         }
8724         return;
8725     }
8726
8727     /*
8728      * Ignore other messages if game is not in progress
8729      */
8730     if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8731         gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
8732
8733     /*
8734      * look for win, lose, draw, or draw offer
8735      */
8736     if (strncmp(message, "1-0", 3) == 0) {
8737         char *p, *q, *r = "";
8738         p = strchr(message, '{');
8739         if (p) {
8740             q = strchr(p, '}');
8741             if (q) {
8742                 *q = NULLCHAR;
8743                 r = p + 1;
8744             }
8745         }
8746         GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
8747         return;
8748     } else if (strncmp(message, "0-1", 3) == 0) {
8749         char *p, *q, *r = "";
8750         p = strchr(message, '{');
8751         if (p) {
8752             q = strchr(p, '}');
8753             if (q) {
8754                 *q = NULLCHAR;
8755                 r = p + 1;
8756             }
8757         }
8758         /* Kludge for Arasan 4.1 bug */
8759         if (strcmp(r, "Black resigns") == 0) {
8760             GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8761             return;
8762         }
8763         GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8764         return;
8765     } else if (strncmp(message, "1/2", 3) == 0) {
8766         char *p, *q, *r = "";
8767         p = strchr(message, '{');
8768         if (p) {
8769             q = strchr(p, '}');
8770             if (q) {
8771                 *q = NULLCHAR;
8772                 r = p + 1;
8773             }
8774         }
8775
8776         GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8777         return;
8778
8779     } else if (strncmp(message, "White resign", 12) == 0) {
8780         GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8781         return;
8782     } else if (strncmp(message, "Black resign", 12) == 0) {
8783         GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8784         return;
8785     } else if (strncmp(message, "White matches", 13) == 0 ||
8786                strncmp(message, "Black matches", 13) == 0   ) {
8787         /* [HGM] ignore GNUShogi noises */
8788         return;
8789     } else if (strncmp(message, "White", 5) == 0 &&
8790                message[5] != '(' &&
8791                StrStr(message, "Black") == NULL) {
8792         GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8793         return;
8794     } else if (strncmp(message, "Black", 5) == 0 &&
8795                message[5] != '(') {
8796         GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8797         return;
8798     } else if (strcmp(message, "resign") == 0 ||
8799                strcmp(message, "computer resigns") == 0) {
8800         switch (gameMode) {
8801           case MachinePlaysBlack:
8802           case IcsPlayingBlack:
8803             GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8804             break;
8805           case MachinePlaysWhite:
8806           case IcsPlayingWhite:
8807             GameEnds(BlackWins, "White resigns", GE_ENGINE);
8808             break;
8809           case TwoMachinesPlay:
8810             if (cps->twoMachinesColor[0] == 'w')
8811               GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8812             else
8813               GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8814             break;
8815           default:
8816             /* can't happen */
8817             break;
8818         }
8819         return;
8820     } else if (strncmp(message, "opponent mates", 14) == 0) {
8821         switch (gameMode) {
8822           case MachinePlaysBlack:
8823           case IcsPlayingBlack:
8824             GameEnds(WhiteWins, "White mates", GE_ENGINE);
8825             break;
8826           case MachinePlaysWhite:
8827           case IcsPlayingWhite:
8828             GameEnds(BlackWins, "Black mates", GE_ENGINE);
8829             break;
8830           case TwoMachinesPlay:
8831             if (cps->twoMachinesColor[0] == 'w')
8832               GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8833             else
8834               GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8835             break;
8836           default:
8837             /* can't happen */
8838             break;
8839         }
8840         return;
8841     } else if (strncmp(message, "computer mates", 14) == 0) {
8842         switch (gameMode) {
8843           case MachinePlaysBlack:
8844           case IcsPlayingBlack:
8845             GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8846             break;
8847           case MachinePlaysWhite:
8848           case IcsPlayingWhite:
8849             GameEnds(WhiteWins, "White mates", GE_ENGINE);
8850             break;
8851           case TwoMachinesPlay:
8852             if (cps->twoMachinesColor[0] == 'w')
8853               GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8854             else
8855               GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8856             break;
8857           default:
8858             /* can't happen */
8859             break;
8860         }
8861         return;
8862     } else if (strncmp(message, "checkmate", 9) == 0) {
8863         if (WhiteOnMove(forwardMostMove)) {
8864             GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8865         } else {
8866             GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8867         }
8868         return;
8869     } else if (strstr(message, "Draw") != NULL ||
8870                strstr(message, "game is a draw") != NULL) {
8871         GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8872         return;
8873     } else if (strstr(message, "offer") != NULL &&
8874                strstr(message, "draw") != NULL) {
8875 #if ZIPPY
8876         if (appData.zippyPlay && first.initDone) {
8877             /* Relay offer to ICS */
8878             SendToICS(ics_prefix);
8879             SendToICS("draw\n");
8880         }
8881 #endif
8882         cps->offeredDraw = 2; /* valid until this engine moves twice */
8883         if (gameMode == TwoMachinesPlay) {
8884             if (cps->other->offeredDraw) {
8885                 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8886             /* [HGM] in two-machine mode we delay relaying draw offer      */
8887             /* until after we also have move, to see if it is really claim */
8888             }
8889         } else if (gameMode == MachinePlaysWhite ||
8890                    gameMode == MachinePlaysBlack) {
8891           if (userOfferedDraw) {
8892             DisplayInformation(_("Machine accepts your draw offer"));
8893             GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8894           } else {
8895             DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8896           }
8897         }
8898     }
8899
8900
8901     /*
8902      * Look for thinking output
8903      */
8904     if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8905           || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8906                                 ) {
8907         int plylev, mvleft, mvtot, curscore, time;
8908         char mvname[MOVE_LEN];
8909         u64 nodes; // [DM]
8910         char plyext;
8911         int ignore = FALSE;
8912         int prefixHint = FALSE;
8913         mvname[0] = NULLCHAR;
8914
8915         switch (gameMode) {
8916           case MachinePlaysBlack:
8917           case IcsPlayingBlack:
8918             if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8919             break;
8920           case MachinePlaysWhite:
8921           case IcsPlayingWhite:
8922             if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8923             break;
8924           case AnalyzeMode:
8925           case AnalyzeFile:
8926             break;
8927           case IcsObserving: /* [DM] icsEngineAnalyze */
8928             if (!appData.icsEngineAnalyze) ignore = TRUE;
8929             break;
8930           case TwoMachinesPlay:
8931             if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8932                 ignore = TRUE;
8933             }
8934             break;
8935           default:
8936             ignore = TRUE;
8937             break;
8938         }
8939
8940         if (!ignore) {
8941             ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8942             buf1[0] = NULLCHAR;
8943             if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8944                        &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8945
8946                 if (plyext != ' ' && plyext != '\t') {
8947                     time *= 100;
8948                 }
8949
8950                 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8951                 if( cps->scoreIsAbsolute &&
8952                     ( gameMode == MachinePlaysBlack ||
8953                       gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8954                       gameMode == IcsPlayingBlack ||     // [HGM] also add other situations where engine should report black POV
8955                      (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8956                      !WhiteOnMove(currentMove)
8957                     ) )
8958                 {
8959                     curscore = -curscore;
8960                 }
8961
8962                 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
8963
8964                 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
8965                         char buf[MSG_SIZ];
8966                         FILE *f;
8967                         snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
8968                         buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
8969                                              gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
8970                         if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
8971                         if(f = fopen(buf, "w")) { // export PV to applicable PV file
8972                                 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
8973                                 fclose(f);
8974                         } else DisplayError(_("failed writing PV"), 0);
8975                 }
8976
8977                 tempStats.depth = plylev;
8978                 tempStats.nodes = nodes;
8979                 tempStats.time = time;
8980                 tempStats.score = curscore;
8981                 tempStats.got_only_move = 0;
8982
8983                 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8984                         int ticklen;
8985
8986                         if(cps->nps == 0) ticklen = 10*time;                    // use engine reported time
8987                         else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8988                         if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8989                                                 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8990                              whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8991                         if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8992                                                 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8993                              blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8994                 }
8995
8996                 /* Buffer overflow protection */
8997                 if (pv[0] != NULLCHAR) {
8998                     if (strlen(pv) >= sizeof(tempStats.movelist)
8999                         && appData.debugMode) {
9000                         fprintf(debugFP,
9001                                 "PV is too long; using the first %u bytes.\n",
9002                                 (unsigned) sizeof(tempStats.movelist) - 1);
9003                     }
9004
9005                     safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
9006                 } else {
9007                     sprintf(tempStats.movelist, " no PV\n");
9008                 }
9009
9010                 if (tempStats.seen_stat) {
9011                     tempStats.ok_to_send = 1;
9012                 }
9013
9014                 if (strchr(tempStats.movelist, '(') != NULL) {
9015                     tempStats.line_is_book = 1;
9016                     tempStats.nr_moves = 0;
9017                     tempStats.moves_left = 0;
9018                 } else {
9019                     tempStats.line_is_book = 0;
9020                 }
9021
9022                     if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
9023                         programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
9024
9025                 SendProgramStatsToFrontend( cps, &tempStats );
9026
9027                 /*
9028                     [AS] Protect the thinkOutput buffer from overflow... this
9029                     is only useful if buf1 hasn't overflowed first!
9030                 */
9031                 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
9032                          plylev,
9033                          (gameMode == TwoMachinesPlay ?
9034                           ToUpper(cps->twoMachinesColor[0]) : ' '),
9035                          ((double) curscore) / 100.0,
9036                          prefixHint ? lastHint : "",
9037                          prefixHint ? " " : "" );
9038
9039                 if( buf1[0] != NULLCHAR ) {
9040                     unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
9041
9042                     if( strlen(pv) > max_len ) {
9043                         if( appData.debugMode) {
9044                             fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
9045                         }
9046                         pv[max_len+1] = '\0';
9047                     }
9048
9049                     strcat( thinkOutput, pv);
9050                 }
9051
9052                 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
9053                         || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9054                     DisplayMove(currentMove - 1);
9055                 }
9056                 return;
9057
9058             } else if ((p=StrStr(message, "(only move)")) != NULL) {
9059                 /* crafty (9.25+) says "(only move) <move>"
9060                  * if there is only 1 legal move
9061                  */
9062                 sscanf(p, "(only move) %s", buf1);
9063                 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
9064                 sprintf(programStats.movelist, "%s (only move)", buf1);
9065                 programStats.depth = 1;
9066                 programStats.nr_moves = 1;
9067                 programStats.moves_left = 1;
9068                 programStats.nodes = 1;
9069                 programStats.time = 1;
9070                 programStats.got_only_move = 1;
9071
9072                 /* Not really, but we also use this member to
9073                    mean "line isn't going to change" (Crafty
9074                    isn't searching, so stats won't change) */
9075                 programStats.line_is_book = 1;
9076
9077                 SendProgramStatsToFrontend( cps, &programStats );
9078
9079                 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9080                            gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9081                     DisplayMove(currentMove - 1);
9082                 }
9083                 return;
9084             } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
9085                               &time, &nodes, &plylev, &mvleft,
9086                               &mvtot, mvname) >= 5) {
9087                 /* The stat01: line is from Crafty (9.29+) in response
9088                    to the "." command */
9089                 programStats.seen_stat = 1;
9090                 cps->maybeThinking = TRUE;
9091
9092                 if (programStats.got_only_move || !appData.periodicUpdates)
9093                   return;
9094
9095                 programStats.depth = plylev;
9096                 programStats.time = time;
9097                 programStats.nodes = nodes;
9098                 programStats.moves_left = mvleft;
9099                 programStats.nr_moves = mvtot;
9100                 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
9101                 programStats.ok_to_send = 1;
9102                 programStats.movelist[0] = '\0';
9103
9104                 SendProgramStatsToFrontend( cps, &programStats );
9105
9106                 return;
9107
9108             } else if (strncmp(message,"++",2) == 0) {
9109                 /* Crafty 9.29+ outputs this */
9110                 programStats.got_fail = 2;
9111                 return;
9112
9113             } else if (strncmp(message,"--",2) == 0) {
9114                 /* Crafty 9.29+ outputs this */
9115                 programStats.got_fail = 1;
9116                 return;
9117
9118             } else if (thinkOutput[0] != NULLCHAR &&
9119                        strncmp(message, "    ", 4) == 0) {
9120                 unsigned message_len;
9121
9122                 p = message;
9123                 while (*p && *p == ' ') p++;
9124
9125                 message_len = strlen( p );
9126
9127                 /* [AS] Avoid buffer overflow */
9128                 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
9129                     strcat(thinkOutput, " ");
9130                     strcat(thinkOutput, p);
9131                 }
9132
9133                 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
9134                     strcat(programStats.movelist, " ");
9135                     strcat(programStats.movelist, p);
9136                 }
9137
9138                 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9139                            gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9140                     DisplayMove(currentMove - 1);
9141                 }
9142                 return;
9143             }
9144         }
9145         else {
9146             buf1[0] = NULLCHAR;
9147
9148             if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9149                        &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
9150             {
9151                 ChessProgramStats cpstats;
9152
9153                 if (plyext != ' ' && plyext != '\t') {
9154                     time *= 100;
9155                 }
9156
9157                 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9158                 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
9159                     curscore = -curscore;
9160                 }
9161
9162                 cpstats.depth = plylev;
9163                 cpstats.nodes = nodes;
9164                 cpstats.time = time;
9165                 cpstats.score = curscore;
9166                 cpstats.got_only_move = 0;
9167                 cpstats.movelist[0] = '\0';
9168
9169                 if (buf1[0] != NULLCHAR) {
9170                     safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
9171                 }
9172
9173                 cpstats.ok_to_send = 0;
9174                 cpstats.line_is_book = 0;
9175                 cpstats.nr_moves = 0;
9176                 cpstats.moves_left = 0;
9177
9178                 SendProgramStatsToFrontend( cps, &cpstats );
9179             }
9180         }
9181     }
9182 }
9183
9184
9185 /* Parse a game score from the character string "game", and
9186    record it as the history of the current game.  The game
9187    score is NOT assumed to start from the standard position.
9188    The display is not updated in any way.
9189    */
9190 void
9191 ParseGameHistory (char *game)
9192 {
9193     ChessMove moveType;
9194     int fromX, fromY, toX, toY, boardIndex;
9195     char promoChar;
9196     char *p, *q;
9197     char buf[MSG_SIZ];
9198
9199     if (appData.debugMode)
9200       fprintf(debugFP, "Parsing game history: %s\n", game);
9201
9202     if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
9203     gameInfo.site = StrSave(appData.icsHost);
9204     gameInfo.date = PGNDate();
9205     gameInfo.round = StrSave("-");
9206
9207     /* Parse out names of players */
9208     while (*game == ' ') game++;
9209     p = buf;
9210     while (*game != ' ') *p++ = *game++;
9211     *p = NULLCHAR;
9212     gameInfo.white = StrSave(buf);
9213     while (*game == ' ') game++;
9214     p = buf;
9215     while (*game != ' ' && *game != '\n') *p++ = *game++;
9216     *p = NULLCHAR;
9217     gameInfo.black = StrSave(buf);
9218
9219     /* Parse moves */
9220     boardIndex = blackPlaysFirst ? 1 : 0;
9221     yynewstr(game);
9222     for (;;) {
9223         yyboardindex = boardIndex;
9224         moveType = (ChessMove) Myylex();
9225         switch (moveType) {
9226           case IllegalMove:             /* maybe suicide chess, etc. */
9227   if (appData.debugMode) {
9228     fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
9229     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9230     setbuf(debugFP, NULL);
9231   }
9232           case WhitePromotion:
9233           case BlackPromotion:
9234           case WhiteNonPromotion:
9235           case BlackNonPromotion:
9236           case NormalMove:
9237           case WhiteCapturesEnPassant:
9238           case BlackCapturesEnPassant:
9239           case WhiteKingSideCastle:
9240           case WhiteQueenSideCastle:
9241           case BlackKingSideCastle:
9242           case BlackQueenSideCastle:
9243           case WhiteKingSideCastleWild:
9244           case WhiteQueenSideCastleWild:
9245           case BlackKingSideCastleWild:
9246           case BlackQueenSideCastleWild:
9247           /* PUSH Fabien */
9248           case WhiteHSideCastleFR:
9249           case WhiteASideCastleFR:
9250           case BlackHSideCastleFR:
9251           case BlackASideCastleFR:
9252           /* POP Fabien */
9253             fromX = currentMoveString[0] - AAA;
9254             fromY = currentMoveString[1] - ONE;
9255             toX = currentMoveString[2] - AAA;
9256             toY = currentMoveString[3] - ONE;
9257             promoChar = currentMoveString[4];
9258             break;
9259           case WhiteDrop:
9260           case BlackDrop:
9261             if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
9262             fromX = moveType == WhiteDrop ?
9263               (int) CharToPiece(ToUpper(currentMoveString[0])) :
9264             (int) CharToPiece(ToLower(currentMoveString[0]));
9265             fromY = DROP_RANK;
9266             toX = currentMoveString[2] - AAA;
9267             toY = currentMoveString[3] - ONE;
9268             promoChar = NULLCHAR;
9269             break;
9270           case AmbiguousMove:
9271             /* bug? */
9272             snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
9273   if (appData.debugMode) {
9274     fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
9275     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9276     setbuf(debugFP, NULL);
9277   }
9278             DisplayError(buf, 0);
9279             return;
9280           case ImpossibleMove:
9281             /* bug? */
9282             snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
9283   if (appData.debugMode) {
9284     fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
9285     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9286     setbuf(debugFP, NULL);
9287   }
9288             DisplayError(buf, 0);
9289             return;
9290           case EndOfFile:
9291             if (boardIndex < backwardMostMove) {
9292                 /* Oops, gap.  How did that happen? */
9293                 DisplayError(_("Gap in move list"), 0);
9294                 return;
9295             }
9296             backwardMostMove =  blackPlaysFirst ? 1 : 0;
9297             if (boardIndex > forwardMostMove) {
9298                 forwardMostMove = boardIndex;
9299             }
9300             return;
9301           case ElapsedTime:
9302             if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
9303                 strcat(parseList[boardIndex-1], " ");
9304                 strcat(parseList[boardIndex-1], yy_text);
9305             }
9306             continue;
9307           case Comment:
9308           case PGNTag:
9309           case NAG:
9310           default:
9311             /* ignore */
9312             continue;
9313           case WhiteWins:
9314           case BlackWins:
9315           case GameIsDrawn:
9316           case GameUnfinished:
9317             if (gameMode == IcsExamining) {
9318                 if (boardIndex < backwardMostMove) {
9319                     /* Oops, gap.  How did that happen? */
9320                     return;
9321                 }
9322                 backwardMostMove = blackPlaysFirst ? 1 : 0;
9323                 return;
9324             }
9325             gameInfo.result = moveType;
9326             p = strchr(yy_text, '{');
9327             if (p == NULL) p = strchr(yy_text, '(');
9328             if (p == NULL) {
9329                 p = yy_text;
9330                 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9331             } else {
9332                 q = strchr(p, *p == '{' ? '}' : ')');
9333                 if (q != NULL) *q = NULLCHAR;
9334                 p++;
9335             }
9336             while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9337             gameInfo.resultDetails = StrSave(p);
9338             continue;
9339         }
9340         if (boardIndex >= forwardMostMove &&
9341             !(gameMode == IcsObserving && ics_gamenum == -1)) {
9342             backwardMostMove = blackPlaysFirst ? 1 : 0;
9343             return;
9344         }
9345         (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9346                                  fromY, fromX, toY, toX, promoChar,
9347                                  parseList[boardIndex]);
9348         CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9349         /* currentMoveString is set as a side-effect of yylex */
9350         safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9351         strcat(moveList[boardIndex], "\n");
9352         boardIndex++;
9353         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9354         switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9355           case MT_NONE:
9356           case MT_STALEMATE:
9357           default:
9358             break;
9359           case MT_CHECK:
9360             if(gameInfo.variant != VariantShogi)
9361                 strcat(parseList[boardIndex - 1], "+");
9362             break;
9363           case MT_CHECKMATE:
9364           case MT_STAINMATE:
9365             strcat(parseList[boardIndex - 1], "#");
9366             break;
9367         }
9368     }
9369 }
9370
9371
9372 /* Apply a move to the given board  */
9373 void
9374 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
9375 {
9376   ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
9377   int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand ? 3 : 1;
9378
9379     /* [HGM] compute & store e.p. status and castling rights for new position */
9380     /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9381
9382       if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9383       oldEP = (signed char)board[EP_STATUS];
9384       board[EP_STATUS] = EP_NONE;
9385
9386   if (fromY == DROP_RANK) {
9387         /* must be first */
9388         if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9389             board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9390             return;
9391         }
9392         piece = board[toY][toX] = (ChessSquare) fromX;
9393   } else {
9394       int i;
9395
9396       if( board[toY][toX] != EmptySquare )
9397            board[EP_STATUS] = EP_CAPTURE;
9398
9399       if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
9400            if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
9401                board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
9402       } else
9403       if( board[fromY][fromX] == WhitePawn ) {
9404            if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9405                board[EP_STATUS] = EP_PAWN_MOVE;
9406            if( toY-fromY==2) {
9407                if(toX>BOARD_LEFT   && board[toY][toX-1] == BlackPawn &&
9408                         gameInfo.variant != VariantBerolina || toX < fromX)
9409                       board[EP_STATUS] = toX | berolina;
9410                if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9411                         gameInfo.variant != VariantBerolina || toX > fromX)
9412                       board[EP_STATUS] = toX;
9413            }
9414       } else
9415       if( board[fromY][fromX] == BlackPawn ) {
9416            if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9417                board[EP_STATUS] = EP_PAWN_MOVE;
9418            if( toY-fromY== -2) {
9419                if(toX>BOARD_LEFT   && board[toY][toX-1] == WhitePawn &&
9420                         gameInfo.variant != VariantBerolina || toX < fromX)
9421                       board[EP_STATUS] = toX | berolina;
9422                if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9423                         gameInfo.variant != VariantBerolina || toX > fromX)
9424                       board[EP_STATUS] = toX;
9425            }
9426        }
9427
9428        for(i=0; i<nrCastlingRights; i++) {
9429            if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9430               board[CASTLING][i] == toX   && castlingRank[i] == toY
9431              ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9432        }
9433
9434        if(gameInfo.variant == VariantSChess) { // update virginity
9435            if(fromY == 0)              board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
9436            if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
9437            if(toY == 0)                board[VIRGIN][toX]   &= ~VIRGIN_W; // loss by capture
9438            if(toY == BOARD_HEIGHT-1)   board[VIRGIN][toX]   &= ~VIRGIN_B;
9439        }
9440
9441      if (fromX == toX && fromY == toY) return;
9442
9443      piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
9444      king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
9445      if(gameInfo.variant == VariantKnightmate)
9446          king += (int) WhiteUnicorn - (int) WhiteKing;
9447
9448     /* Code added by Tord: */
9449     /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
9450     if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
9451         board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
9452       board[fromY][fromX] = EmptySquare;
9453       board[toY][toX] = EmptySquare;
9454       if((toX > fromX) != (piece == WhiteRook)) {
9455         board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
9456       } else {
9457         board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
9458       }
9459     } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
9460                board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
9461       board[fromY][fromX] = EmptySquare;
9462       board[toY][toX] = EmptySquare;
9463       if((toX > fromX) != (piece == BlackRook)) {
9464         board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
9465       } else {
9466         board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
9467       }
9468     /* End of code added by Tord */
9469
9470     } else if (board[fromY][fromX] == king
9471         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9472         && toY == fromY && toX > fromX+1) {
9473         board[fromY][fromX] = EmptySquare;
9474         board[toY][toX] = king;
9475         board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9476         board[fromY][BOARD_RGHT-1] = EmptySquare;
9477     } else if (board[fromY][fromX] == king
9478         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9479                && toY == fromY && toX < fromX-1) {
9480         board[fromY][fromX] = EmptySquare;
9481         board[toY][toX] = king;
9482         board[toY][toX+1] = board[fromY][BOARD_LEFT];
9483         board[fromY][BOARD_LEFT] = EmptySquare;
9484     } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
9485                 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9486                && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
9487                ) {
9488         /* white pawn promotion */
9489         board[toY][toX] = CharToPiece(ToUpper(promoChar));
9490         if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
9491             board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9492         board[fromY][fromX] = EmptySquare;
9493     } else if ((fromY >= BOARD_HEIGHT>>1)
9494                && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality)
9495                && (toX != fromX)
9496                && gameInfo.variant != VariantXiangqi
9497                && gameInfo.variant != VariantBerolina
9498                && (board[fromY][fromX] == WhitePawn)
9499                && (board[toY][toX] == EmptySquare)) {
9500         board[fromY][fromX] = EmptySquare;
9501         board[toY][toX] = WhitePawn;
9502         captured = board[toY - 1][toX];
9503         board[toY - 1][toX] = EmptySquare;
9504     } else if ((fromY == BOARD_HEIGHT-4)
9505                && (toX == fromX)
9506                && gameInfo.variant == VariantBerolina
9507                && (board[fromY][fromX] == WhitePawn)
9508                && (board[toY][toX] == EmptySquare)) {
9509         board[fromY][fromX] = EmptySquare;
9510         board[toY][toX] = WhitePawn;
9511         if(oldEP & EP_BEROLIN_A) {
9512                 captured = board[fromY][fromX-1];
9513                 board[fromY][fromX-1] = EmptySquare;
9514         }else{  captured = board[fromY][fromX+1];
9515                 board[fromY][fromX+1] = EmptySquare;
9516         }
9517     } else if (board[fromY][fromX] == king
9518         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9519                && toY == fromY && toX > fromX+1) {
9520         board[fromY][fromX] = EmptySquare;
9521         board[toY][toX] = king;
9522         board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9523         board[fromY][BOARD_RGHT-1] = EmptySquare;
9524     } else if (board[fromY][fromX] == king
9525         && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9526                && toY == fromY && toX < fromX-1) {
9527         board[fromY][fromX] = EmptySquare;
9528         board[toY][toX] = king;
9529         board[toY][toX+1] = board[fromY][BOARD_LEFT];
9530         board[fromY][BOARD_LEFT] = EmptySquare;
9531     } else if (fromY == 7 && fromX == 3
9532                && board[fromY][fromX] == BlackKing
9533                && toY == 7 && toX == 5) {
9534         board[fromY][fromX] = EmptySquare;
9535         board[toY][toX] = BlackKing;
9536         board[fromY][7] = EmptySquare;
9537         board[toY][4] = BlackRook;
9538     } else if (fromY == 7 && fromX == 3
9539                && board[fromY][fromX] == BlackKing
9540                && toY == 7 && toX == 1) {
9541         board[fromY][fromX] = EmptySquare;
9542         board[toY][toX] = BlackKing;
9543         board[fromY][0] = EmptySquare;
9544         board[toY][2] = BlackRook;
9545     } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
9546                 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9547                && toY < promoRank && promoChar
9548                ) {
9549         /* black pawn promotion */
9550         board[toY][toX] = CharToPiece(ToLower(promoChar));
9551         if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
9552             board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9553         board[fromY][fromX] = EmptySquare;
9554     } else if ((fromY < BOARD_HEIGHT>>1)
9555                && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality)
9556                && (toX != fromX)
9557                && gameInfo.variant != VariantXiangqi
9558                && gameInfo.variant != VariantBerolina
9559                && (board[fromY][fromX] == BlackPawn)
9560                && (board[toY][toX] == EmptySquare)) {
9561         board[fromY][fromX] = EmptySquare;
9562         board[toY][toX] = BlackPawn;
9563         captured = board[toY + 1][toX];
9564         board[toY + 1][toX] = EmptySquare;
9565     } else if ((fromY == 3)
9566                && (toX == fromX)
9567                && gameInfo.variant == VariantBerolina
9568                && (board[fromY][fromX] == BlackPawn)
9569                && (board[toY][toX] == EmptySquare)) {
9570         board[fromY][fromX] = EmptySquare;
9571         board[toY][toX] = BlackPawn;
9572         if(oldEP & EP_BEROLIN_A) {
9573                 captured = board[fromY][fromX-1];
9574                 board[fromY][fromX-1] = EmptySquare;
9575         }else{  captured = board[fromY][fromX+1];
9576                 board[fromY][fromX+1] = EmptySquare;
9577         }
9578     } else {
9579         board[toY][toX] = board[fromY][fromX];
9580         board[fromY][fromX] = EmptySquare;
9581     }
9582   }
9583
9584     if (gameInfo.holdingsWidth != 0) {
9585
9586       /* !!A lot more code needs to be written to support holdings  */
9587       /* [HGM] OK, so I have written it. Holdings are stored in the */
9588       /* penultimate board files, so they are automaticlly stored   */
9589       /* in the game history.                                       */
9590       if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
9591                                 && promoChar && piece != WhitePawn && piece != BlackPawn) {
9592         /* Delete from holdings, by decreasing count */
9593         /* and erasing image if necessary            */
9594         p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
9595         if(p < (int) BlackPawn) { /* white drop */
9596              p -= (int)WhitePawn;
9597                  p = PieceToNumber((ChessSquare)p);
9598              if(p >= gameInfo.holdingsSize) p = 0;
9599              if(--board[p][BOARD_WIDTH-2] <= 0)
9600                   board[p][BOARD_WIDTH-1] = EmptySquare;
9601              if((int)board[p][BOARD_WIDTH-2] < 0)
9602                         board[p][BOARD_WIDTH-2] = 0;
9603         } else {                  /* black drop */
9604              p -= (int)BlackPawn;
9605                  p = PieceToNumber((ChessSquare)p);
9606              if(p >= gameInfo.holdingsSize) p = 0;
9607              if(--board[BOARD_HEIGHT-1-p][1] <= 0)
9608                   board[BOARD_HEIGHT-1-p][0] = EmptySquare;
9609              if((int)board[BOARD_HEIGHT-1-p][1] < 0)
9610                         board[BOARD_HEIGHT-1-p][1] = 0;
9611         }
9612       }
9613       if (captured != EmptySquare && gameInfo.holdingsSize > 0
9614           && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess        ) {
9615         /* [HGM] holdings: Add to holdings, if holdings exist */
9616         if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
9617                 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
9618                 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
9619         }
9620         p = (int) captured;
9621         if (p >= (int) BlackPawn) {
9622           p -= (int)BlackPawn;
9623           if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9624                   /* in Shogi restore piece to its original  first */
9625                   captured = (ChessSquare) (DEMOTED captured);
9626                   p = DEMOTED p;
9627           }
9628           p = PieceToNumber((ChessSquare)p);
9629           if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
9630           board[p][BOARD_WIDTH-2]++;
9631           board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
9632         } else {
9633           p -= (int)WhitePawn;
9634           if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9635                   captured = (ChessSquare) (DEMOTED captured);
9636                   p = DEMOTED p;
9637           }
9638           p = PieceToNumber((ChessSquare)p);
9639           if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
9640           board[BOARD_HEIGHT-1-p][1]++;
9641           board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
9642         }
9643       }
9644     } else if (gameInfo.variant == VariantAtomic) {
9645       if (captured != EmptySquare) {
9646         int y, x;
9647         for (y = toY-1; y <= toY+1; y++) {
9648           for (x = toX-1; x <= toX+1; x++) {
9649             if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
9650                 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
9651               board[y][x] = EmptySquare;
9652             }
9653           }
9654         }
9655         board[toY][toX] = EmptySquare;
9656       }
9657     }
9658     if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
9659         board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
9660     } else
9661     if(promoChar == '+') {
9662         /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
9663         board[toY][toX] = (ChessSquare) (PROMOTED piece);
9664     } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
9665         ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
9666         if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
9667            && pieceToChar[PROMOTED newPiece] == '~') newPiece = PROMOTED newPiece; // but promoted version available
9668         board[toY][toX] = newPiece;
9669     }
9670     if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
9671                 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
9672         // [HGM] superchess: take promotion piece out of holdings
9673         int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
9674         if((int)piece < (int)BlackPawn) { // determine stm from piece color
9675             if(!--board[k][BOARD_WIDTH-2])
9676                 board[k][BOARD_WIDTH-1] = EmptySquare;
9677         } else {
9678             if(!--board[BOARD_HEIGHT-1-k][1])
9679                 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
9680         }
9681     }
9682
9683 }
9684
9685 /* Updates forwardMostMove */
9686 void
9687 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
9688 {
9689 //    forwardMostMove++; // [HGM] bare: moved downstream
9690
9691     (void) CoordsToAlgebraic(boards[forwardMostMove],
9692                              PosFlags(forwardMostMove),
9693                              fromY, fromX, toY, toX, promoChar,
9694                              parseList[forwardMostMove]);
9695
9696     if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
9697         int timeLeft; static int lastLoadFlag=0; int king, piece;
9698         piece = boards[forwardMostMove][fromY][fromX];
9699         king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
9700         if(gameInfo.variant == VariantKnightmate)
9701             king += (int) WhiteUnicorn - (int) WhiteKing;
9702         if(forwardMostMove == 0) {
9703             if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
9704                 fprintf(serverMoves, "%s;", UserName());
9705             else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
9706                 fprintf(serverMoves, "%s;", second.tidy);
9707             fprintf(serverMoves, "%s;", first.tidy);
9708             if(gameMode == MachinePlaysWhite)
9709                 fprintf(serverMoves, "%s;", UserName());
9710             else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
9711                 fprintf(serverMoves, "%s;", second.tidy);
9712         } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
9713         lastLoadFlag = loadFlag;
9714         // print base move
9715         fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
9716         // print castling suffix
9717         if( toY == fromY && piece == king ) {
9718             if(toX-fromX > 1)
9719                 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
9720             if(fromX-toX >1)
9721                 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
9722         }
9723         // e.p. suffix
9724         if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
9725              boards[forwardMostMove][fromY][fromX] == BlackPawn   ) &&
9726              boards[forwardMostMove][toY][toX] == EmptySquare
9727              && fromX != toX && fromY != toY)
9728                 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
9729         // promotion suffix
9730         if(promoChar != NULLCHAR) {
9731             if(fromY == 0 || fromY == BOARD_HEIGHT-1)
9732                  fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
9733                                                  ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
9734             else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
9735         }
9736         if(!loadFlag) {
9737                 char buf[MOVE_LEN*2], *p; int len;
9738             fprintf(serverMoves, "/%d/%d",
9739                pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
9740             if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
9741             else                      timeLeft = blackTimeRemaining/1000;
9742             fprintf(serverMoves, "/%d", timeLeft);
9743                 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
9744                 if(p = strchr(buf, '/')) *p = NULLCHAR; else
9745                 if(p = strchr(buf, '=')) *p = NULLCHAR;
9746                 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
9747             fprintf(serverMoves, "/%s", buf);
9748         }
9749         fflush(serverMoves);
9750     }
9751
9752     if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
9753         GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
9754       return;
9755     }
9756     UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
9757     if (commentList[forwardMostMove+1] != NULL) {
9758         free(commentList[forwardMostMove+1]);
9759         commentList[forwardMostMove+1] = NULL;
9760     }
9761     CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9762     ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
9763     // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
9764     SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
9765     timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
9766     timeRemaining[1][forwardMostMove] = blackTimeRemaining;
9767     adjustedClock = FALSE;
9768     gameInfo.result = GameUnfinished;
9769     if (gameInfo.resultDetails != NULL) {
9770         free(gameInfo.resultDetails);
9771         gameInfo.resultDetails = NULL;
9772     }
9773     CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
9774                               moveList[forwardMostMove - 1]);
9775     switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
9776       case MT_NONE:
9777       case MT_STALEMATE:
9778       default:
9779         break;
9780       case MT_CHECK:
9781         if(gameInfo.variant != VariantShogi)
9782             strcat(parseList[forwardMostMove - 1], "+");
9783         break;
9784       case MT_CHECKMATE:
9785       case MT_STAINMATE:
9786         strcat(parseList[forwardMostMove - 1], "#");
9787         break;
9788     }
9789
9790 }
9791
9792 /* Updates currentMove if not pausing */
9793 void
9794 ShowMove (int fromX, int fromY, int toX, int toY)
9795 {
9796     int instant = (gameMode == PlayFromGameFile) ?
9797         (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9798     if(appData.noGUI) return;
9799     if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9800         if (!instant) {
9801             if (forwardMostMove == currentMove + 1) {
9802                 AnimateMove(boards[forwardMostMove - 1],
9803                             fromX, fromY, toX, toY);
9804             }
9805         }
9806         currentMove = forwardMostMove;
9807     }
9808
9809     if (instant) return;
9810
9811     DisplayMove(currentMove - 1);
9812     if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9813             if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
9814                 SetHighlights(fromX, fromY, toX, toY);
9815             }
9816     }
9817     DrawPosition(FALSE, boards[currentMove]);
9818     DisplayBothClocks();
9819     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9820 }
9821
9822 void
9823 SendEgtPath (ChessProgramState *cps)
9824 {       /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9825         char buf[MSG_SIZ], name[MSG_SIZ], *p;
9826
9827         if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9828
9829         while(*p) {
9830             char c, *q = name+1, *r, *s;
9831
9832             name[0] = ','; // extract next format name from feature and copy with prefixed ','
9833             while(*p && *p != ',') *q++ = *p++;
9834             *q++ = ':'; *q = 0;
9835             if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9836                 strcmp(name, ",nalimov:") == 0 ) {
9837                 // take nalimov path from the menu-changeable option first, if it is defined
9838               snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9839                 SendToProgram(buf,cps);     // send egtbpath command for nalimov
9840             } else
9841             if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9842                 (s = StrStr(appData.egtFormats, name)) != NULL) {
9843                 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9844                 s = r = StrStr(s, ":") + 1; // beginning of path info
9845                 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9846                 c = *r; *r = 0;             // temporarily null-terminate path info
9847                     *--q = 0;               // strip of trailig ':' from name
9848                     snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9849                 *r = c;
9850                 SendToProgram(buf,cps);     // send egtbpath command for this format
9851             }
9852             if(*p == ',') p++; // read away comma to position for next format name
9853         }
9854 }
9855
9856 static int
9857 NonStandardBoardSize ()
9858 {
9859       /* [HGM] Awkward testing. Should really be a table */
9860       int overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9861       if( gameInfo.variant == VariantXiangqi )
9862            overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9863       if( gameInfo.variant == VariantShogi )
9864            overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9865       if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9866            overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9867       if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9868           gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9869            overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9870       if( gameInfo.variant == VariantCourier )
9871            overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9872       if( gameInfo.variant == VariantSuper )
9873            overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9874       if( gameInfo.variant == VariantGreat )
9875            overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9876       if( gameInfo.variant == VariantSChess )
9877            overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9878       if( gameInfo.variant == VariantGrand )
9879            overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 7;
9880       return overruled;
9881 }
9882
9883 void
9884 InitChessProgram (ChessProgramState *cps, int setup)
9885 /* setup needed to setup FRC opening position */
9886 {
9887     char buf[MSG_SIZ], b[MSG_SIZ];
9888     if (appData.noChessProgram) return;
9889     hintRequested = FALSE;
9890     bookRequested = FALSE;
9891
9892     ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
9893     /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9894     /*       moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9895     if(cps->memSize) { /* [HGM] memory */
9896       snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9897         SendToProgram(buf, cps);
9898     }
9899     SendEgtPath(cps); /* [HGM] EGT */
9900     if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9901       snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9902         SendToProgram(buf, cps);
9903     }
9904
9905     SendToProgram(cps->initString, cps);
9906     if (gameInfo.variant != VariantNormal &&
9907         gameInfo.variant != VariantLoadable
9908         /* [HGM] also send variant if board size non-standard */
9909         || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9910                                             ) {
9911       char *v = VariantName(gameInfo.variant);
9912       if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9913         /* [HGM] in protocol 1 we have to assume all variants valid */
9914         snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9915         DisplayFatalError(buf, 0, 1);
9916         return;
9917       }
9918
9919       if(NonStandardBoardSize()) { /* [HGM] make prefix for non-standard board size. */
9920         snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9921                  gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9922            /* [HGM] varsize: try first if this defiant size variant is specifically known */
9923            if(StrStr(cps->variants, b) == NULL) {
9924                // specific sized variant not known, check if general sizing allowed
9925                if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9926                    if(StrStr(cps->variants, "boardsize") == NULL) {
9927                      snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9928                             gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9929                        DisplayFatalError(buf, 0, 1);
9930                        return;
9931                    }
9932                    /* [HGM] here we really should compare with the maximum supported board size */
9933                }
9934            }
9935       } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9936       snprintf(buf, MSG_SIZ, "variant %s\n", b);
9937       SendToProgram(buf, cps);
9938     }
9939     currentlyInitializedVariant = gameInfo.variant;
9940
9941     /* [HGM] send opening position in FRC to first engine */
9942     if(setup) {
9943           SendToProgram("force\n", cps);
9944           SendBoard(cps, 0);
9945           /* engine is now in force mode! Set flag to wake it up after first move. */
9946           setboardSpoiledMachineBlack = 1;
9947     }
9948
9949     if (cps->sendICS) {
9950       snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9951       SendToProgram(buf, cps);
9952     }
9953     cps->maybeThinking = FALSE;
9954     cps->offeredDraw = 0;
9955     if (!appData.icsActive) {
9956         SendTimeControl(cps, movesPerSession, timeControl,
9957                         timeIncrement, appData.searchDepth,
9958                         searchTime);
9959     }
9960     if (appData.showThinking
9961         // [HGM] thinking: four options require thinking output to be sent
9962         || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9963                                 ) {
9964         SendToProgram("post\n", cps);
9965     }
9966     SendToProgram("hard\n", cps);
9967     if (!appData.ponderNextMove) {
9968         /* Warning: "easy" is a toggle in GNU Chess, so don't send
9969            it without being sure what state we are in first.  "hard"
9970            is not a toggle, so that one is OK.
9971          */
9972         SendToProgram("easy\n", cps);
9973     }
9974     if (cps->usePing) {
9975       snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9976       SendToProgram(buf, cps);
9977     }
9978     cps->initDone = TRUE;
9979     ClearEngineOutputPane(cps == &second);
9980 }
9981
9982
9983 void
9984 ResendOptions (ChessProgramState *cps)
9985 { // send the stored value of the options
9986   int i;
9987   char buf[MSG_SIZ];
9988   Option *opt = cps->option;
9989   for(i=0; i<cps->nrOptions; i++, opt++) {
9990       switch(opt->type) {
9991         case Spin:
9992         case Slider:
9993         case CheckBox:
9994             snprintf(buf, MSG_SIZ, "option %s=%d\n", opt->name, opt->value);
9995           break;
9996         case ComboBox:
9997           snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->choice[opt->value]);
9998           break;
9999         default:
10000             snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->textValue);
10001           break;
10002         case Button:
10003         case SaveButton:
10004           continue;
10005       }
10006       SendToProgram(buf, cps);
10007   }
10008 }
10009
10010 void
10011 StartChessProgram (ChessProgramState *cps)
10012 {
10013     char buf[MSG_SIZ];
10014     int err;
10015
10016     if (appData.noChessProgram) return;
10017     cps->initDone = FALSE;
10018
10019     if (strcmp(cps->host, "localhost") == 0) {
10020         err = StartChildProcess(cps->program, cps->dir, &cps->pr);
10021     } else if (*appData.remoteShell == NULLCHAR) {
10022         err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
10023     } else {
10024         if (*appData.remoteUser == NULLCHAR) {
10025           snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
10026                     cps->program);
10027         } else {
10028           snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
10029                     cps->host, appData.remoteUser, cps->program);
10030         }
10031         err = StartChildProcess(buf, "", &cps->pr);
10032     }
10033
10034     if (err != 0) {
10035       snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
10036         DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
10037         if(cps != &first) return;
10038         appData.noChessProgram = TRUE;
10039         ThawUI();
10040         SetNCPMode();
10041 //      DisplayFatalError(buf, err, 1);
10042 //      cps->pr = NoProc;
10043 //      cps->isr = NULL;
10044         return;
10045     }
10046
10047     cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
10048     if (cps->protocolVersion > 1) {
10049       snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
10050       if(!cps->reload) { // do not clear options when reloading because of -xreuse
10051         cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
10052         cps->comboCnt = 0;  //                and values of combo boxes
10053       }
10054       SendToProgram(buf, cps);
10055       if(cps->reload) ResendOptions(cps);
10056     } else {
10057       SendToProgram("xboard\n", cps);
10058     }
10059 }
10060
10061 void
10062 TwoMachinesEventIfReady P((void))
10063 {
10064   static int curMess = 0;
10065   if (first.lastPing != first.lastPong) {
10066     if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
10067     ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10068     return;
10069   }
10070   if (second.lastPing != second.lastPong) {
10071     if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
10072     ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10073     return;
10074   }
10075   DisplayMessage("", ""); curMess = 0;
10076   TwoMachinesEvent();
10077 }
10078
10079 char *
10080 MakeName (char *template)
10081 {
10082     time_t clock;
10083     struct tm *tm;
10084     static char buf[MSG_SIZ];
10085     char *p = buf;
10086     int i;
10087
10088     clock = time((time_t *)NULL);
10089     tm = localtime(&clock);
10090
10091     while(*p++ = *template++) if(p[-1] == '%') {
10092         switch(*template++) {
10093           case 0:   *p = 0; return buf;
10094           case 'Y': i = tm->tm_year+1900; break;
10095           case 'y': i = tm->tm_year-100; break;
10096           case 'M': i = tm->tm_mon+1; break;
10097           case 'd': i = tm->tm_mday; break;
10098           case 'h': i = tm->tm_hour; break;
10099           case 'm': i = tm->tm_min; break;
10100           case 's': i = tm->tm_sec; break;
10101           default:  i = 0;
10102         }
10103         snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
10104     }
10105     return buf;
10106 }
10107
10108 int
10109 CountPlayers (char *p)
10110 {
10111     int n = 0;
10112     while(p = strchr(p, '\n')) p++, n++; // count participants
10113     return n;
10114 }
10115
10116 FILE *
10117 WriteTourneyFile (char *results, FILE *f)
10118 {   // write tournament parameters on tourneyFile; on success return the stream pointer for closing
10119     if(f == NULL) f = fopen(appData.tourneyFile, "w");
10120     if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
10121         // create a file with tournament description
10122         fprintf(f, "-participants {%s}\n", appData.participants);
10123         fprintf(f, "-seedBase %d\n", appData.seedBase);
10124         fprintf(f, "-tourneyType %d\n", appData.tourneyType);
10125         fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
10126         fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
10127         fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
10128         fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
10129         fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
10130         fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
10131         fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
10132         fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
10133         fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
10134         fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
10135         fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
10136         fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
10137         fprintf(f, "-bookDepth %d\n", appData.bookDepth);
10138         fprintf(f, "-bookVariation %d\n", appData.bookStrength);
10139         fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
10140         fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
10141         fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
10142         fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
10143         fprintf(f, "-smpCores %d\n", appData.smpCores);
10144         if(searchTime > 0)
10145                 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
10146         else {
10147                 fprintf(f, "-mps %d\n", appData.movesPerSession);
10148                 fprintf(f, "-tc %s\n", appData.timeControl);
10149                 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
10150         }
10151         fprintf(f, "-results \"%s\"\n", results);
10152     }
10153     return f;
10154 }
10155
10156 char *command[MAXENGINES], *mnemonic[MAXENGINES];
10157
10158 void
10159 Substitute (char *participants, int expunge)
10160 {
10161     int i, changed, changes=0, nPlayers=0;
10162     char *p, *q, *r, buf[MSG_SIZ];
10163     if(participants == NULL) return;
10164     if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
10165     r = p = participants; q = appData.participants;
10166     while(*p && *p == *q) {
10167         if(*p == '\n') r = p+1, nPlayers++;
10168         p++; q++;
10169     }
10170     if(*p) { // difference
10171         while(*p && *p++ != '\n');
10172         while(*q && *q++ != '\n');
10173       changed = nPlayers;
10174         changes = 1 + (strcmp(p, q) != 0);
10175     }
10176     if(changes == 1) { // a single engine mnemonic was changed
10177         q = r; while(*q) nPlayers += (*q++ == '\n');
10178         p = buf; while(*r && (*p = *r++) != '\n') p++;
10179         *p = NULLCHAR;
10180         NamesToList(firstChessProgramNames, command, mnemonic, "all");
10181         for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
10182         if(mnemonic[i]) { // The substitute is valid
10183             FILE *f;
10184             if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
10185                 flock(fileno(f), LOCK_EX);
10186                 ParseArgsFromFile(f);
10187                 fseek(f, 0, SEEK_SET);
10188                 FREE(appData.participants); appData.participants = participants;
10189                 if(expunge) { // erase results of replaced engine
10190                     int len = strlen(appData.results), w, b, dummy;
10191                     for(i=0; i<len; i++) {
10192                         Pairing(i, nPlayers, &w, &b, &dummy);
10193                         if((w == changed || b == changed) && appData.results[i] == '*') {
10194                             DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
10195                             fclose(f);
10196                             return;
10197                         }
10198                     }
10199                     for(i=0; i<len; i++) {
10200                         Pairing(i, nPlayers, &w, &b, &dummy);
10201                         if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
10202                     }
10203                 }
10204                 WriteTourneyFile(appData.results, f);
10205                 fclose(f); // release lock
10206                 return;
10207             }
10208         } else DisplayError(_("No engine with the name you gave is installed"), 0);
10209     }
10210     if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
10211     if(changes > 1)  DisplayError(_("You can only change one engine at the time"), 0);
10212     free(participants);
10213     return;
10214 }
10215
10216 int
10217 CheckPlayers (char *participants)
10218 {
10219         int i;
10220         char buf[MSG_SIZ], *p;
10221         NamesToList(firstChessProgramNames, command, mnemonic, "all");
10222         while(p = strchr(participants, '\n')) {
10223             *p = NULLCHAR;
10224             for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
10225             if(!mnemonic[i]) {
10226                 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
10227                 *p = '\n';
10228                 DisplayError(buf, 0);
10229                 return 1;
10230             }
10231             *p = '\n';
10232             participants = p + 1;
10233         }
10234         return 0;
10235 }
10236
10237 int
10238 CreateTourney (char *name)
10239 {
10240         FILE *f;
10241         if(matchMode && strcmp(name, appData.tourneyFile)) {
10242              ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
10243         }
10244         if(name[0] == NULLCHAR) {
10245             if(appData.participants[0])
10246                 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
10247             return 0;
10248         }
10249         f = fopen(name, "r");
10250         if(f) { // file exists
10251             ASSIGN(appData.tourneyFile, name);
10252             ParseArgsFromFile(f); // parse it
10253         } else {
10254             if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
10255             if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
10256                 DisplayError(_("Not enough participants"), 0);
10257                 return 0;
10258             }
10259             if(CheckPlayers(appData.participants)) return 0;
10260             ASSIGN(appData.tourneyFile, name);
10261             if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
10262             if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
10263         }
10264         fclose(f);
10265         appData.noChessProgram = FALSE;
10266         appData.clockMode = TRUE;
10267         SetGNUMode();
10268         return 1;
10269 }
10270
10271 int
10272 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
10273 {
10274     char buf[MSG_SIZ], *p, *q;
10275     int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
10276     insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
10277     skip = !all && group[0]; // if group requested, we start in skip mode
10278     for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
10279         p = names; q = buf; header = 0;
10280         while(*p && *p != '\n') *q++ = *p++;
10281         *q = 0;
10282         if(*p == '\n') p++;
10283         if(buf[0] == '#') {
10284             if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
10285             depth++; // we must be entering a new group
10286             if(all) continue; // suppress printing group headers when complete list requested
10287             header = 1;
10288             if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
10289         }
10290         if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
10291         if(engineList[i]) free(engineList[i]);
10292         engineList[i] = strdup(buf);
10293         if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
10294         if(engineMnemonic[i]) free(engineMnemonic[i]);
10295         if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
10296             strcat(buf, " (");
10297             sscanf(q + 8, "%s", buf + strlen(buf));
10298             strcat(buf, ")");
10299         }
10300         engineMnemonic[i] = strdup(buf);
10301         i++;
10302     }
10303     engineList[i] = engineMnemonic[i] = NULL;
10304     return i;
10305 }
10306
10307 // following implemented as macro to avoid type limitations
10308 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
10309
10310 void
10311 SwapEngines (int n)
10312 {   // swap settings for first engine and other engine (so far only some selected options)
10313     int h;
10314     char *p;
10315     if(n == 0) return;
10316     SWAP(directory, p)
10317     SWAP(chessProgram, p)
10318     SWAP(isUCI, h)
10319     SWAP(hasOwnBookUCI, h)
10320     SWAP(protocolVersion, h)
10321     SWAP(reuse, h)
10322     SWAP(scoreIsAbsolute, h)
10323     SWAP(timeOdds, h)
10324     SWAP(logo, p)
10325     SWAP(pgnName, p)
10326     SWAP(pvSAN, h)
10327     SWAP(engOptions, p)
10328     SWAP(engInitString, p)
10329     SWAP(computerString, p)
10330     SWAP(features, p)
10331     SWAP(fenOverride, p)
10332     SWAP(NPS, h)
10333     SWAP(accumulateTC, h)
10334     SWAP(host, p)
10335 }
10336
10337 int
10338 GetEngineLine (char *s, int n)
10339 {
10340     int i;
10341     char buf[MSG_SIZ];
10342     extern char *icsNames;
10343     if(!s || !*s) return 0;
10344     NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
10345     for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
10346     if(!mnemonic[i]) return 0;
10347     if(n == 11) return 1; // just testing if there was a match
10348     snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
10349     if(n == 1) SwapEngines(n);
10350     ParseArgsFromString(buf);
10351     if(n == 1) SwapEngines(n);
10352     if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
10353         SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
10354         ParseArgsFromString(buf);
10355     }
10356     return 1;
10357 }
10358
10359 int
10360 SetPlayer (int player, char *p)
10361 {   // [HGM] find the engine line of the partcipant given by number, and parse its options.
10362     int i;
10363     char buf[MSG_SIZ], *engineName;
10364     for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
10365     engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
10366     for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
10367     if(mnemonic[i]) {
10368         snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
10369         ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
10370         appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
10371         ParseArgsFromString(buf);
10372     } else { // no engine with this nickname is installed!
10373         snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
10374         ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
10375         matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10376         ModeHighlight();
10377         DisplayError(buf, 0);
10378         return 0;
10379     }
10380     free(engineName);
10381     return i;
10382 }
10383
10384 char *recentEngines;
10385
10386 void
10387 RecentEngineEvent (int nr)
10388 {
10389     int n;
10390 //    SwapEngines(1); // bump first to second
10391 //    ReplaceEngine(&second, 1); // and load it there
10392     NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10393     n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
10394     if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
10395         ReplaceEngine(&first, 0);
10396         FloatToFront(&appData.recentEngineList, command[n]);
10397     }
10398 }
10399
10400 int
10401 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
10402 {   // determine players from game number
10403     int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
10404
10405     if(appData.tourneyType == 0) {
10406         roundsPerCycle = (nPlayers - 1) | 1;
10407         pairingsPerRound = nPlayers / 2;
10408     } else if(appData.tourneyType > 0) {
10409         roundsPerCycle = nPlayers - appData.tourneyType;
10410         pairingsPerRound = appData.tourneyType;
10411     }
10412     gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
10413     gamesPerCycle = gamesPerRound * roundsPerCycle;
10414     appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
10415     curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
10416     curRound = nr / gamesPerRound; nr %= gamesPerRound;
10417     curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
10418     matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
10419     roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
10420
10421     if(appData.cycleSync) *syncInterval = gamesPerCycle;
10422     if(appData.roundSync) *syncInterval = gamesPerRound;
10423
10424     if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
10425
10426     if(appData.tourneyType == 0) {
10427         if(curPairing == (nPlayers-1)/2 ) {
10428             *whitePlayer = curRound;
10429             *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
10430         } else {
10431             *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
10432             if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
10433             *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
10434             if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
10435         }
10436     } else if(appData.tourneyType > 1) {
10437         *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
10438         *whitePlayer = curRound + appData.tourneyType;
10439     } else if(appData.tourneyType > 0) {
10440         *whitePlayer = curPairing;
10441         *blackPlayer = curRound + appData.tourneyType;
10442     }
10443
10444     // take care of white/black alternation per round.
10445     // For cycles and games this is already taken care of by default, derived from matchGame!
10446     return curRound & 1;
10447 }
10448
10449 int
10450 NextTourneyGame (int nr, int *swapColors)
10451 {   // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
10452     char *p, *q;
10453     int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
10454     FILE *tf;
10455     if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
10456     tf = fopen(appData.tourneyFile, "r");
10457     if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
10458     ParseArgsFromFile(tf); fclose(tf);
10459     InitTimeControls(); // TC might be altered from tourney file
10460
10461     nPlayers = CountPlayers(appData.participants); // count participants
10462     if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
10463     *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
10464
10465     if(syncInterval) {
10466         p = q = appData.results;
10467         while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
10468         if(firstBusy/syncInterval < (nextGame/syncInterval)) {
10469             DisplayMessage(_("Waiting for other game(s)"),"");
10470             waitingForGame = TRUE;
10471             ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
10472             return 0;
10473         }
10474         waitingForGame = FALSE;
10475     }
10476
10477     if(appData.tourneyType < 0) {
10478         if(nr>=0 && !pairingReceived) {
10479             char buf[1<<16];
10480             if(pairing.pr == NoProc) {
10481                 if(!appData.pairingEngine[0]) {
10482                     DisplayFatalError(_("No pairing engine specified"), 0, 1);
10483                     return 0;
10484                 }
10485                 StartChessProgram(&pairing); // starts the pairing engine
10486             }
10487             snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
10488             SendToProgram(buf, &pairing);
10489             snprintf(buf, 1<<16, "pairing %d\n", nr+1);
10490             SendToProgram(buf, &pairing);
10491             return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
10492         }
10493         pairingReceived = 0;                              // ... so we continue here
10494         *swapColors = 0;
10495         appData.matchGames = appData.tourneyCycles * syncInterval - 1;
10496         whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
10497         matchGame = 1; roundNr = nr / syncInterval + 1;
10498     }
10499
10500     if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
10501
10502     // redefine engines, engine dir, etc.
10503     NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10504     if(first.pr == NoProc) {
10505       if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
10506       InitEngine(&first, 0);  // initialize ChessProgramStates based on new settings.
10507     }
10508     if(second.pr == NoProc) {
10509       SwapEngines(1);
10510       if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
10511       SwapEngines(1);         // and make that valid for second engine by swapping
10512       InitEngine(&second, 1);
10513     }
10514     CommonEngineInit();     // after this TwoMachinesEvent will create correct engine processes
10515     UpdateLogos(FALSE);     // leave display to ModeHiglight()
10516     return OK;
10517 }
10518
10519 void
10520 NextMatchGame ()
10521 {   // performs game initialization that does not invoke engines, and then tries to start the game
10522     int res, firstWhite, swapColors = 0;
10523     if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
10524     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
10525         char buf[MSG_SIZ];
10526         snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
10527         if(strcmp(buf, currentDebugFile)) { // name has changed
10528             FILE *f = fopen(buf, "w");
10529             if(f) { // if opening the new file failed, just keep using the old one
10530                 ASSIGN(currentDebugFile, buf);
10531                 fclose(debugFP);
10532                 debugFP = f;
10533             }
10534             if(appData.serverFileName) {
10535                 if(serverFP) fclose(serverFP);
10536                 serverFP = fopen(appData.serverFileName, "w");
10537                 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
10538                 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
10539             }
10540         }
10541     }
10542     firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
10543     firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
10544     first.twoMachinesColor =  firstWhite ? "white\n" : "black\n";   // perform actual color assignement
10545     second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
10546     appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
10547     if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
10548     Reset(FALSE, first.pr != NoProc);
10549     res = LoadGameOrPosition(matchGame); // setup game
10550     appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
10551     if(!res) return; // abort when bad game/pos file
10552     TwoMachinesEvent();
10553 }
10554
10555 void
10556 UserAdjudicationEvent (int result)
10557 {
10558     ChessMove gameResult = GameIsDrawn;
10559
10560     if( result > 0 ) {
10561         gameResult = WhiteWins;
10562     }
10563     else if( result < 0 ) {
10564         gameResult = BlackWins;
10565     }
10566
10567     if( gameMode == TwoMachinesPlay ) {
10568         GameEnds( gameResult, "User adjudication", GE_XBOARD );
10569     }
10570 }
10571
10572
10573 // [HGM] save: calculate checksum of game to make games easily identifiable
10574 int
10575 StringCheckSum (char *s)
10576 {
10577         int i = 0;
10578         if(s==NULL) return 0;
10579         while(*s) i = i*259 + *s++;
10580         return i;
10581 }
10582
10583 int
10584 GameCheckSum ()
10585 {
10586         int i, sum=0;
10587         for(i=backwardMostMove; i<forwardMostMove; i++) {
10588                 sum += pvInfoList[i].depth;
10589                 sum += StringCheckSum(parseList[i]);
10590                 sum += StringCheckSum(commentList[i]);
10591                 sum *= 261;
10592         }
10593         if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
10594         return sum + StringCheckSum(commentList[i]);
10595 } // end of save patch
10596
10597 void
10598 GameEnds (ChessMove result, char *resultDetails, int whosays)
10599 {
10600     GameMode nextGameMode;
10601     int isIcsGame;
10602     char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
10603
10604     if(endingGame) return; /* [HGM] crash: forbid recursion */
10605     endingGame = 1;
10606     if(twoBoards) { // [HGM] dual: switch back to one board
10607         twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
10608         DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
10609     }
10610     if (appData.debugMode) {
10611       fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
10612               result, resultDetails ? resultDetails : "(null)", whosays);
10613     }
10614
10615     fromX = fromY = -1; // [HGM] abort any move the user is entering.
10616
10617     if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
10618
10619     if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
10620         /* If we are playing on ICS, the server decides when the
10621            game is over, but the engine can offer to draw, claim
10622            a draw, or resign.
10623          */
10624 #if ZIPPY
10625         if (appData.zippyPlay && first.initDone) {
10626             if (result == GameIsDrawn) {
10627                 /* In case draw still needs to be claimed */
10628                 SendToICS(ics_prefix);
10629                 SendToICS("draw\n");
10630             } else if (StrCaseStr(resultDetails, "resign")) {
10631                 SendToICS(ics_prefix);
10632                 SendToICS("resign\n");
10633             }
10634         }
10635 #endif
10636         endingGame = 0; /* [HGM] crash */
10637         return;
10638     }
10639
10640     /* If we're loading the game from a file, stop */
10641     if (whosays == GE_FILE) {
10642       (void) StopLoadGameTimer();
10643       gameFileFP = NULL;
10644     }
10645
10646     /* Cancel draw offers */
10647     first.offeredDraw = second.offeredDraw = 0;
10648
10649     /* If this is an ICS game, only ICS can really say it's done;
10650        if not, anyone can. */
10651     isIcsGame = (gameMode == IcsPlayingWhite ||
10652                  gameMode == IcsPlayingBlack ||
10653                  gameMode == IcsObserving    ||
10654                  gameMode == IcsExamining);
10655
10656     if (!isIcsGame || whosays == GE_ICS) {
10657         /* OK -- not an ICS game, or ICS said it was done */
10658         StopClocks();
10659         if (!isIcsGame && !appData.noChessProgram)
10660           SetUserThinkingEnables();
10661
10662         /* [HGM] if a machine claims the game end we verify this claim */
10663         if(gameMode == TwoMachinesPlay && appData.testClaims) {
10664             if(appData.testLegality && whosays >= GE_ENGINE1 ) {
10665                 char claimer;
10666                 ChessMove trueResult = (ChessMove) -1;
10667
10668                 claimer = whosays == GE_ENGINE1 ?      /* color of claimer */
10669                                             first.twoMachinesColor[0] :
10670                                             second.twoMachinesColor[0] ;
10671
10672                 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
10673                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
10674                     /* [HGM] verify: engine mate claims accepted if they were flagged */
10675                     trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
10676                 } else
10677                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
10678                     /* [HGM] verify: engine mate claims accepted if they were flagged */
10679                     trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
10680                 } else
10681                 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
10682                     trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
10683                 }
10684
10685                 // now verify win claims, but not in drop games, as we don't understand those yet
10686                 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10687                                                  || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
10688                     (result == WhiteWins && claimer == 'w' ||
10689                      result == BlackWins && claimer == 'b'   ) ) { // case to verify: engine claims own win
10690                       if (appData.debugMode) {
10691                         fprintf(debugFP, "result=%d sp=%d move=%d\n",
10692                                 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
10693                       }
10694                       if(result != trueResult) {
10695                         snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
10696                               result = claimer == 'w' ? BlackWins : WhiteWins;
10697                               resultDetails = buf;
10698                       }
10699                 } else
10700                 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
10701                     && (forwardMostMove <= backwardMostMove ||
10702                         (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
10703                         (claimer=='b')==(forwardMostMove&1))
10704                                                                                   ) {
10705                       /* [HGM] verify: draws that were not flagged are false claims */
10706                   snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
10707                       result = claimer == 'w' ? BlackWins : WhiteWins;
10708                       resultDetails = buf;
10709                 }
10710                 /* (Claiming a loss is accepted no questions asked!) */
10711             } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
10712                 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
10713                 result = GameUnfinished;
10714                 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
10715             }
10716             /* [HGM] bare: don't allow bare King to win */
10717             if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10718                                             || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10719                && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
10720                && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
10721                && result != GameIsDrawn)
10722             {   int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
10723                 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
10724                         int p = (signed char)boards[forwardMostMove][i][j] - color;
10725                         if(p >= 0 && p <= (int)WhiteKing) k++;
10726                 }
10727                 if (appData.debugMode) {
10728                      fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
10729                         result, resultDetails ? resultDetails : "(null)", whosays, k, color);
10730                 }
10731                 if(k <= 1) {
10732                         result = GameIsDrawn;
10733                         snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
10734                         resultDetails = buf;
10735                 }
10736             }
10737         }
10738
10739
10740         if(serverMoves != NULL && !loadFlag) { char c = '=';
10741             if(result==WhiteWins) c = '+';
10742             if(result==BlackWins) c = '-';
10743             if(resultDetails != NULL)
10744                 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
10745         }
10746         if (resultDetails != NULL) {
10747             gameInfo.result = result;
10748             gameInfo.resultDetails = StrSave(resultDetails);
10749
10750             /* display last move only if game was not loaded from file */
10751             if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
10752                 DisplayMove(currentMove - 1);
10753
10754             if (forwardMostMove != 0) {
10755                 if (gameMode != PlayFromGameFile && gameMode != EditGame
10756                     && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
10757                                                                 ) {
10758                     if (*appData.saveGameFile != NULLCHAR) {
10759                         if(result == GameUnfinished && matchMode && *appData.tourneyFile)
10760                             AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
10761                         else
10762                         SaveGameToFile(appData.saveGameFile, TRUE);
10763                     } else if (appData.autoSaveGames) {
10764                         if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
10765                     }
10766                     if (*appData.savePositionFile != NULLCHAR) {
10767                         SavePositionToFile(appData.savePositionFile);
10768                     }
10769                     AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
10770                 }
10771             }
10772
10773             /* Tell program how game ended in case it is learning */
10774             /* [HGM] Moved this to after saving the PGN, just in case */
10775             /* engine died and we got here through time loss. In that */
10776             /* case we will get a fatal error writing the pipe, which */
10777             /* would otherwise lose us the PGN.                       */
10778             /* [HGM] crash: not needed anymore, but doesn't hurt;     */
10779             /* output during GameEnds should never be fatal anymore   */
10780             if (gameMode == MachinePlaysWhite ||
10781                 gameMode == MachinePlaysBlack ||
10782                 gameMode == TwoMachinesPlay ||
10783                 gameMode == IcsPlayingWhite ||
10784                 gameMode == IcsPlayingBlack ||
10785                 gameMode == BeginningOfGame) {
10786                 char buf[MSG_SIZ];
10787                 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
10788                         resultDetails);
10789                 if (first.pr != NoProc) {
10790                     SendToProgram(buf, &first);
10791                 }
10792                 if (second.pr != NoProc &&
10793                     gameMode == TwoMachinesPlay) {
10794                     SendToProgram(buf, &second);
10795                 }
10796             }
10797         }
10798
10799         if (appData.icsActive) {
10800             if (appData.quietPlay &&
10801                 (gameMode == IcsPlayingWhite ||
10802                  gameMode == IcsPlayingBlack)) {
10803                 SendToICS(ics_prefix);
10804                 SendToICS("set shout 1\n");
10805             }
10806             nextGameMode = IcsIdle;
10807             ics_user_moved = FALSE;
10808             /* clean up premove.  It's ugly when the game has ended and the
10809              * premove highlights are still on the board.
10810              */
10811             if (gotPremove) {
10812               gotPremove = FALSE;
10813               ClearPremoveHighlights();
10814               DrawPosition(FALSE, boards[currentMove]);
10815             }
10816             if (whosays == GE_ICS) {
10817                 switch (result) {
10818                 case WhiteWins:
10819                     if (gameMode == IcsPlayingWhite)
10820                         PlayIcsWinSound();
10821                     else if(gameMode == IcsPlayingBlack)
10822                         PlayIcsLossSound();
10823                     break;
10824                 case BlackWins:
10825                     if (gameMode == IcsPlayingBlack)
10826                         PlayIcsWinSound();
10827                     else if(gameMode == IcsPlayingWhite)
10828                         PlayIcsLossSound();
10829                     break;
10830                 case GameIsDrawn:
10831                     PlayIcsDrawSound();
10832                     break;
10833                 default:
10834                     PlayIcsUnfinishedSound();
10835                 }
10836             }
10837         } else if (gameMode == EditGame ||
10838                    gameMode == PlayFromGameFile ||
10839                    gameMode == AnalyzeMode ||
10840                    gameMode == AnalyzeFile) {
10841             nextGameMode = gameMode;
10842         } else {
10843             nextGameMode = EndOfGame;
10844         }
10845         pausing = FALSE;
10846         ModeHighlight();
10847     } else {
10848         nextGameMode = gameMode;
10849     }
10850
10851     if (appData.noChessProgram) {
10852         gameMode = nextGameMode;
10853         ModeHighlight();
10854         endingGame = 0; /* [HGM] crash */
10855         return;
10856     }
10857
10858     if (first.reuse) {
10859         /* Put first chess program into idle state */
10860         if (first.pr != NoProc &&
10861             (gameMode == MachinePlaysWhite ||
10862              gameMode == MachinePlaysBlack ||
10863              gameMode == TwoMachinesPlay ||
10864              gameMode == IcsPlayingWhite ||
10865              gameMode == IcsPlayingBlack ||
10866              gameMode == BeginningOfGame)) {
10867             SendToProgram("force\n", &first);
10868             if (first.usePing) {
10869               char buf[MSG_SIZ];
10870               snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
10871               SendToProgram(buf, &first);
10872             }
10873         }
10874     } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10875         /* Kill off first chess program */
10876         if (first.isr != NULL)
10877           RemoveInputSource(first.isr);
10878         first.isr = NULL;
10879
10880         if (first.pr != NoProc) {
10881             ExitAnalyzeMode();
10882             DoSleep( appData.delayBeforeQuit );
10883             SendToProgram("quit\n", &first);
10884             DoSleep( appData.delayAfterQuit );
10885             DestroyChildProcess(first.pr, first.useSigterm);
10886             first.reload = TRUE;
10887         }
10888         first.pr = NoProc;
10889     }
10890     if (second.reuse) {
10891         /* Put second chess program into idle state */
10892         if (second.pr != NoProc &&
10893             gameMode == TwoMachinesPlay) {
10894             SendToProgram("force\n", &second);
10895             if (second.usePing) {
10896               char buf[MSG_SIZ];
10897               snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
10898               SendToProgram(buf, &second);
10899             }
10900         }
10901     } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10902         /* Kill off second chess program */
10903         if (second.isr != NULL)
10904           RemoveInputSource(second.isr);
10905         second.isr = NULL;
10906
10907         if (second.pr != NoProc) {
10908             DoSleep( appData.delayBeforeQuit );
10909             SendToProgram("quit\n", &second);
10910             DoSleep( appData.delayAfterQuit );
10911             DestroyChildProcess(second.pr, second.useSigterm);
10912             second.reload = TRUE;
10913         }
10914         second.pr = NoProc;
10915     }
10916
10917     if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
10918         char resChar = '=';
10919         switch (result) {
10920         case WhiteWins:
10921           resChar = '+';
10922           if (first.twoMachinesColor[0] == 'w') {
10923             first.matchWins++;
10924           } else {
10925             second.matchWins++;
10926           }
10927           break;
10928         case BlackWins:
10929           resChar = '-';
10930           if (first.twoMachinesColor[0] == 'b') {
10931             first.matchWins++;
10932           } else {
10933             second.matchWins++;
10934           }
10935           break;
10936         case GameUnfinished:
10937           resChar = ' ';
10938         default:
10939           break;
10940         }
10941
10942         if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
10943         if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
10944             if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
10945             ReserveGame(nextGame, resChar); // sets nextGame
10946             if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
10947             else ranking = strdup("busy"); //suppress popup when aborted but not finished
10948         } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
10949
10950         if (nextGame <= appData.matchGames && !abortMatch) {
10951             gameMode = nextGameMode;
10952             matchGame = nextGame; // this will be overruled in tourney mode!
10953             GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
10954             ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
10955             endingGame = 0; /* [HGM] crash */
10956             return;
10957         } else {
10958             gameMode = nextGameMode;
10959             snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
10960                      first.tidy, second.tidy,
10961                      first.matchWins, second.matchWins,
10962                      appData.matchGames - (first.matchWins + second.matchWins));
10963             if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
10964             if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
10965             popupRequested++; // [HGM] crash: postpone to after resetting endingGame
10966             if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
10967                 first.twoMachinesColor = "black\n";
10968                 second.twoMachinesColor = "white\n";
10969             } else {
10970                 first.twoMachinesColor = "white\n";
10971                 second.twoMachinesColor = "black\n";
10972             }
10973         }
10974     }
10975     if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
10976         !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
10977       ExitAnalyzeMode();
10978     gameMode = nextGameMode;
10979     ModeHighlight();
10980     endingGame = 0;  /* [HGM] crash */
10981     if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
10982         if(matchMode == TRUE) { // match through command line: exit with or without popup
10983             if(ranking) {
10984                 ToNrEvent(forwardMostMove);
10985                 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
10986                 else ExitEvent(0);
10987             } else DisplayFatalError(buf, 0, 0);
10988         } else { // match through menu; just stop, with or without popup
10989             matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10990             ModeHighlight();
10991             if(ranking){
10992                 if(strcmp(ranking, "busy")) DisplayNote(ranking);
10993             } else DisplayNote(buf);
10994       }
10995       if(ranking) free(ranking);
10996     }
10997 }
10998
10999 /* Assumes program was just initialized (initString sent).
11000    Leaves program in force mode. */
11001 void
11002 FeedMovesToProgram (ChessProgramState *cps, int upto)
11003 {
11004     int i;
11005
11006     if (appData.debugMode)
11007       fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
11008               startedFromSetupPosition ? "position and " : "",
11009               backwardMostMove, upto, cps->which);
11010     if(currentlyInitializedVariant != gameInfo.variant) {
11011       char buf[MSG_SIZ];
11012         // [HGM] variantswitch: make engine aware of new variant
11013         if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
11014                 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
11015         snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
11016         SendToProgram(buf, cps);
11017         currentlyInitializedVariant = gameInfo.variant;
11018     }
11019     SendToProgram("force\n", cps);
11020     if (startedFromSetupPosition) {
11021         SendBoard(cps, backwardMostMove);
11022     if (appData.debugMode) {
11023         fprintf(debugFP, "feedMoves\n");
11024     }
11025     }
11026     for (i = backwardMostMove; i < upto; i++) {
11027         SendMoveToProgram(i, cps);
11028     }
11029 }
11030
11031
11032 int
11033 ResurrectChessProgram ()
11034 {
11035      /* The chess program may have exited.
11036         If so, restart it and feed it all the moves made so far. */
11037     static int doInit = 0;
11038
11039     if (appData.noChessProgram) return 1;
11040
11041     if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
11042         if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
11043         if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
11044         doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
11045     } else {
11046         if (first.pr != NoProc) return 1;
11047         StartChessProgram(&first);
11048     }
11049     InitChessProgram(&first, FALSE);
11050     FeedMovesToProgram(&first, currentMove);
11051
11052     if (!first.sendTime) {
11053         /* can't tell gnuchess what its clock should read,
11054            so we bow to its notion. */
11055         ResetClocks();
11056         timeRemaining[0][currentMove] = whiteTimeRemaining;
11057         timeRemaining[1][currentMove] = blackTimeRemaining;
11058     }
11059
11060     if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
11061                 appData.icsEngineAnalyze) && first.analysisSupport) {
11062       SendToProgram("analyze\n", &first);
11063       first.analyzing = TRUE;
11064     }
11065     return 1;
11066 }
11067
11068 /*
11069  * Button procedures
11070  */
11071 void
11072 Reset (int redraw, int init)
11073 {
11074     int i;
11075
11076     if (appData.debugMode) {
11077         fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
11078                 redraw, init, gameMode);
11079     }
11080     CleanupTail(); // [HGM] vari: delete any stored variations
11081     CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
11082     pausing = pauseExamInvalid = FALSE;
11083     startedFromSetupPosition = blackPlaysFirst = FALSE;
11084     firstMove = TRUE;
11085     whiteFlag = blackFlag = FALSE;
11086     userOfferedDraw = FALSE;
11087     hintRequested = bookRequested = FALSE;
11088     first.maybeThinking = FALSE;
11089     second.maybeThinking = FALSE;
11090     first.bookSuspend = FALSE; // [HGM] book
11091     second.bookSuspend = FALSE;
11092     thinkOutput[0] = NULLCHAR;
11093     lastHint[0] = NULLCHAR;
11094     ClearGameInfo(&gameInfo);
11095     gameInfo.variant = StringToVariant(appData.variant);
11096     ics_user_moved = ics_clock_paused = FALSE;
11097     ics_getting_history = H_FALSE;
11098     ics_gamenum = -1;
11099     white_holding[0] = black_holding[0] = NULLCHAR;
11100     ClearProgramStats();
11101     opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
11102
11103     ResetFrontEnd();
11104     ClearHighlights();
11105     flipView = appData.flipView;
11106     ClearPremoveHighlights();
11107     gotPremove = FALSE;
11108     alarmSounded = FALSE;
11109
11110     GameEnds(EndOfFile, NULL, GE_PLAYER);
11111     if(appData.serverMovesName != NULL) {
11112         /* [HGM] prepare to make moves file for broadcasting */
11113         clock_t t = clock();
11114         if(serverMoves != NULL) fclose(serverMoves);
11115         serverMoves = fopen(appData.serverMovesName, "r");
11116         if(serverMoves != NULL) {
11117             fclose(serverMoves);
11118             /* delay 15 sec before overwriting, so all clients can see end */
11119             while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
11120         }
11121         serverMoves = fopen(appData.serverMovesName, "w");
11122     }
11123
11124     ExitAnalyzeMode();
11125     gameMode = BeginningOfGame;
11126     ModeHighlight();
11127     if(appData.icsActive) gameInfo.variant = VariantNormal;
11128     currentMove = forwardMostMove = backwardMostMove = 0;
11129     MarkTargetSquares(1);
11130     InitPosition(redraw);
11131     for (i = 0; i < MAX_MOVES; i++) {
11132         if (commentList[i] != NULL) {
11133             free(commentList[i]);
11134             commentList[i] = NULL;
11135         }
11136     }
11137     ResetClocks();
11138     timeRemaining[0][0] = whiteTimeRemaining;
11139     timeRemaining[1][0] = blackTimeRemaining;
11140
11141     if (first.pr == NoProc) {
11142         StartChessProgram(&first);
11143     }
11144     if (init) {
11145             InitChessProgram(&first, startedFromSetupPosition);
11146     }
11147     DisplayTitle("");
11148     DisplayMessage("", "");
11149     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
11150     lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
11151     ClearMap();        // [HGM] exclude: invalidate map
11152 }
11153
11154 void
11155 AutoPlayGameLoop ()
11156 {
11157     for (;;) {
11158         if (!AutoPlayOneMove())
11159           return;
11160         if (matchMode || appData.timeDelay == 0)
11161           continue;
11162         if (appData.timeDelay < 0)
11163           return;
11164         StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
11165         break;
11166     }
11167 }
11168
11169 void
11170 AnalyzeNextGame()
11171 {
11172     ReloadGame(1); // next game
11173 }
11174
11175 int
11176 AutoPlayOneMove ()
11177 {
11178     int fromX, fromY, toX, toY;
11179
11180     if (appData.debugMode) {
11181       fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
11182     }
11183
11184     if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
11185       return FALSE;
11186
11187     if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
11188       pvInfoList[currentMove].depth = programStats.depth;
11189       pvInfoList[currentMove].score = programStats.score;
11190       pvInfoList[currentMove].time  = 0;
11191       if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
11192       else { // append analysis of final position as comment
11193         char buf[MSG_SIZ];
11194         snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
11195         AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
11196       }
11197       programStats.depth = 0;
11198     }
11199
11200     if (currentMove >= forwardMostMove) {
11201       if(gameMode == AnalyzeFile) {
11202           if(appData.loadGameIndex == -1) {
11203             GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
11204           ScheduleDelayedEvent(AnalyzeNextGame, 10);
11205           } else {
11206           ExitAnalyzeMode(); SendToProgram("force\n", &first);
11207         }
11208       }
11209 //      gameMode = EndOfGame;
11210 //      ModeHighlight();
11211
11212       /* [AS] Clear current move marker at the end of a game */
11213       /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
11214
11215       return FALSE;
11216     }
11217
11218     toX = moveList[currentMove][2] - AAA;
11219     toY = moveList[currentMove][3] - ONE;
11220
11221     if (moveList[currentMove][1] == '@') {
11222         if (appData.highlightLastMove) {
11223             SetHighlights(-1, -1, toX, toY);
11224         }
11225     } else {
11226         fromX = moveList[currentMove][0] - AAA;
11227         fromY = moveList[currentMove][1] - ONE;
11228
11229         HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
11230
11231         AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
11232
11233         if (appData.highlightLastMove) {
11234             SetHighlights(fromX, fromY, toX, toY);
11235         }
11236     }
11237     DisplayMove(currentMove);
11238     SendMoveToProgram(currentMove++, &first);
11239     DisplayBothClocks();
11240     DrawPosition(FALSE, boards[currentMove]);
11241     // [HGM] PV info: always display, routine tests if empty
11242     DisplayComment(currentMove - 1, commentList[currentMove]);
11243     return TRUE;
11244 }
11245
11246
11247 int
11248 LoadGameOneMove (ChessMove readAhead)
11249 {
11250     int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
11251     char promoChar = NULLCHAR;
11252     ChessMove moveType;
11253     char move[MSG_SIZ];
11254     char *p, *q;
11255
11256     if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
11257         gameMode != AnalyzeMode && gameMode != Training) {
11258         gameFileFP = NULL;
11259         return FALSE;
11260     }
11261
11262     yyboardindex = forwardMostMove;
11263     if (readAhead != EndOfFile) {
11264       moveType = readAhead;
11265     } else {
11266       if (gameFileFP == NULL)
11267           return FALSE;
11268       moveType = (ChessMove) Myylex();
11269     }
11270
11271     done = FALSE;
11272     switch (moveType) {
11273       case Comment:
11274         if (appData.debugMode)
11275           fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11276         p = yy_text;
11277
11278         /* append the comment but don't display it */
11279         AppendComment(currentMove, p, FALSE);
11280         return TRUE;
11281
11282       case WhiteCapturesEnPassant:
11283       case BlackCapturesEnPassant:
11284       case WhitePromotion:
11285       case BlackPromotion:
11286       case WhiteNonPromotion:
11287       case BlackNonPromotion:
11288       case NormalMove:
11289       case WhiteKingSideCastle:
11290       case WhiteQueenSideCastle:
11291       case BlackKingSideCastle:
11292       case BlackQueenSideCastle:
11293       case WhiteKingSideCastleWild:
11294       case WhiteQueenSideCastleWild:
11295       case BlackKingSideCastleWild:
11296       case BlackQueenSideCastleWild:
11297       /* PUSH Fabien */
11298       case WhiteHSideCastleFR:
11299       case WhiteASideCastleFR:
11300       case BlackHSideCastleFR:
11301       case BlackASideCastleFR:
11302       /* POP Fabien */
11303         if (appData.debugMode)
11304           fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11305         fromX = currentMoveString[0] - AAA;
11306         fromY = currentMoveString[1] - ONE;
11307         toX = currentMoveString[2] - AAA;
11308         toY = currentMoveString[3] - ONE;
11309         promoChar = currentMoveString[4];
11310         break;
11311
11312       case WhiteDrop:
11313       case BlackDrop:
11314         if (appData.debugMode)
11315           fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11316         fromX = moveType == WhiteDrop ?
11317           (int) CharToPiece(ToUpper(currentMoveString[0])) :
11318         (int) CharToPiece(ToLower(currentMoveString[0]));
11319         fromY = DROP_RANK;
11320         toX = currentMoveString[2] - AAA;
11321         toY = currentMoveString[3] - ONE;
11322         break;
11323
11324       case WhiteWins:
11325       case BlackWins:
11326       case GameIsDrawn:
11327       case GameUnfinished:
11328         if (appData.debugMode)
11329           fprintf(debugFP, "Parsed game end: %s\n", yy_text);
11330         p = strchr(yy_text, '{');
11331         if (p == NULL) p = strchr(yy_text, '(');
11332         if (p == NULL) {
11333             p = yy_text;
11334             if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
11335         } else {
11336             q = strchr(p, *p == '{' ? '}' : ')');
11337             if (q != NULL) *q = NULLCHAR;
11338             p++;
11339         }
11340         while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
11341         GameEnds(moveType, p, GE_FILE);
11342         done = TRUE;
11343         if (cmailMsgLoaded) {
11344             ClearHighlights();
11345             flipView = WhiteOnMove(currentMove);
11346             if (moveType == GameUnfinished) flipView = !flipView;
11347             if (appData.debugMode)
11348               fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
11349         }
11350         break;
11351
11352       case EndOfFile:
11353         if (appData.debugMode)
11354           fprintf(debugFP, "Parser hit end of file\n");
11355         switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11356           case MT_NONE:
11357           case MT_CHECK:
11358             break;
11359           case MT_CHECKMATE:
11360           case MT_STAINMATE:
11361             if (WhiteOnMove(currentMove)) {
11362                 GameEnds(BlackWins, "Black mates", GE_FILE);
11363             } else {
11364                 GameEnds(WhiteWins, "White mates", GE_FILE);
11365             }
11366             break;
11367           case MT_STALEMATE:
11368             GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11369             break;
11370         }
11371         done = TRUE;
11372         break;
11373
11374       case MoveNumberOne:
11375         if (lastLoadGameStart == GNUChessGame) {
11376             /* GNUChessGames have numbers, but they aren't move numbers */
11377             if (appData.debugMode)
11378               fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11379                       yy_text, (int) moveType);
11380             return LoadGameOneMove(EndOfFile); /* tail recursion */
11381         }
11382         /* else fall thru */
11383
11384       case XBoardGame:
11385       case GNUChessGame:
11386       case PGNTag:
11387         /* Reached start of next game in file */
11388         if (appData.debugMode)
11389           fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
11390         switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11391           case MT_NONE:
11392           case MT_CHECK:
11393             break;
11394           case MT_CHECKMATE:
11395           case MT_STAINMATE:
11396             if (WhiteOnMove(currentMove)) {
11397                 GameEnds(BlackWins, "Black mates", GE_FILE);
11398             } else {
11399                 GameEnds(WhiteWins, "White mates", GE_FILE);
11400             }
11401             break;
11402           case MT_STALEMATE:
11403             GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11404             break;
11405         }
11406         done = TRUE;
11407         break;
11408
11409       case PositionDiagram:     /* should not happen; ignore */
11410       case ElapsedTime:         /* ignore */
11411       case NAG:                 /* ignore */
11412         if (appData.debugMode)
11413           fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11414                   yy_text, (int) moveType);
11415         return LoadGameOneMove(EndOfFile); /* tail recursion */
11416
11417       case IllegalMove:
11418         if (appData.testLegality) {
11419             if (appData.debugMode)
11420               fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
11421             snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11422                     (forwardMostMove / 2) + 1,
11423                     WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11424             DisplayError(move, 0);
11425             done = TRUE;
11426         } else {
11427             if (appData.debugMode)
11428               fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
11429                       yy_text, currentMoveString);
11430             fromX = currentMoveString[0] - AAA;
11431             fromY = currentMoveString[1] - ONE;
11432             toX = currentMoveString[2] - AAA;
11433             toY = currentMoveString[3] - ONE;
11434             promoChar = currentMoveString[4];
11435         }
11436         break;
11437
11438       case AmbiguousMove:
11439         if (appData.debugMode)
11440           fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
11441         snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
11442                 (forwardMostMove / 2) + 1,
11443                 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11444         DisplayError(move, 0);
11445         done = TRUE;
11446         break;
11447
11448       default:
11449       case ImpossibleMove:
11450         if (appData.debugMode)
11451           fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
11452         snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11453                 (forwardMostMove / 2) + 1,
11454                 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11455         DisplayError(move, 0);
11456         done = TRUE;
11457         break;
11458     }
11459
11460     if (done) {
11461         if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
11462             DrawPosition(FALSE, boards[currentMove]);
11463             DisplayBothClocks();
11464             if (!appData.matchMode) // [HGM] PV info: routine tests if empty
11465               DisplayComment(currentMove - 1, commentList[currentMove]);
11466         }
11467         (void) StopLoadGameTimer();
11468         gameFileFP = NULL;
11469         cmailOldMove = forwardMostMove;
11470         return FALSE;
11471     } else {
11472         /* currentMoveString is set as a side-effect of yylex */
11473
11474         thinkOutput[0] = NULLCHAR;
11475         MakeMove(fromX, fromY, toX, toY, promoChar);
11476         currentMove = forwardMostMove;
11477         return TRUE;
11478     }
11479 }
11480
11481 /* Load the nth game from the given file */
11482 int
11483 LoadGameFromFile (char *filename, int n, char *title, int useList)
11484 {
11485     FILE *f;
11486     char buf[MSG_SIZ];
11487
11488     if (strcmp(filename, "-") == 0) {
11489         f = stdin;
11490         title = "stdin";
11491     } else {
11492         f = fopen(filename, "rb");
11493         if (f == NULL) {
11494           snprintf(buf, sizeof(buf),  _("Can't open \"%s\""), filename);
11495             DisplayError(buf, errno);
11496             return FALSE;
11497         }
11498     }
11499     if (fseek(f, 0, 0) == -1) {
11500         /* f is not seekable; probably a pipe */
11501         useList = FALSE;
11502     }
11503     if (useList && n == 0) {
11504         int error = GameListBuild(f);
11505         if (error) {
11506             DisplayError(_("Cannot build game list"), error);
11507         } else if (!ListEmpty(&gameList) &&
11508                    ((ListGame *) gameList.tailPred)->number > 1) {
11509             GameListPopUp(f, title);
11510             return TRUE;
11511         }
11512         GameListDestroy();
11513         n = 1;
11514     }
11515     if (n == 0) n = 1;
11516     return LoadGame(f, n, title, FALSE);
11517 }
11518
11519
11520 void
11521 MakeRegisteredMove ()
11522 {
11523     int fromX, fromY, toX, toY;
11524     char promoChar;
11525     if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11526         switch (cmailMoveType[lastLoadGameNumber - 1]) {
11527           case CMAIL_MOVE:
11528           case CMAIL_DRAW:
11529             if (appData.debugMode)
11530               fprintf(debugFP, "Restoring %s for game %d\n",
11531                       cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11532
11533             thinkOutput[0] = NULLCHAR;
11534             safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
11535             fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
11536             fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
11537             toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
11538             toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
11539             promoChar = cmailMove[lastLoadGameNumber - 1][4];
11540             MakeMove(fromX, fromY, toX, toY, promoChar);
11541             ShowMove(fromX, fromY, toX, toY);
11542
11543             switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11544               case MT_NONE:
11545               case MT_CHECK:
11546                 break;
11547
11548               case MT_CHECKMATE:
11549               case MT_STAINMATE:
11550                 if (WhiteOnMove(currentMove)) {
11551                     GameEnds(BlackWins, "Black mates", GE_PLAYER);
11552                 } else {
11553                     GameEnds(WhiteWins, "White mates", GE_PLAYER);
11554                 }
11555                 break;
11556
11557               case MT_STALEMATE:
11558                 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
11559                 break;
11560             }
11561
11562             break;
11563
11564           case CMAIL_RESIGN:
11565             if (WhiteOnMove(currentMove)) {
11566                 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11567             } else {
11568                 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11569             }
11570             break;
11571
11572           case CMAIL_ACCEPT:
11573             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11574             break;
11575
11576           default:
11577             break;
11578         }
11579     }
11580
11581     return;
11582 }
11583
11584 /* Wrapper around LoadGame for use when a Cmail message is loaded */
11585 int
11586 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
11587 {
11588     int retVal;
11589
11590     if (gameNumber > nCmailGames) {
11591         DisplayError(_("No more games in this message"), 0);
11592         return FALSE;
11593     }
11594     if (f == lastLoadGameFP) {
11595         int offset = gameNumber - lastLoadGameNumber;
11596         if (offset == 0) {
11597             cmailMsg[0] = NULLCHAR;
11598             if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11599                 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11600                 nCmailMovesRegistered--;
11601             }
11602             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11603             if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
11604                 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
11605             }
11606         } else {
11607             if (! RegisterMove()) return FALSE;
11608         }
11609     }
11610
11611     retVal = LoadGame(f, gameNumber, title, useList);
11612
11613     /* Make move registered during previous look at this game, if any */
11614     MakeRegisteredMove();
11615
11616     if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
11617         commentList[currentMove]
11618           = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
11619         DisplayComment(currentMove - 1, commentList[currentMove]);
11620     }
11621
11622     return retVal;
11623 }
11624
11625 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
11626 int
11627 ReloadGame (int offset)
11628 {
11629     int gameNumber = lastLoadGameNumber + offset;
11630     if (lastLoadGameFP == NULL) {
11631         DisplayError(_("No game has been loaded yet"), 0);
11632         return FALSE;
11633     }
11634     if (gameNumber <= 0) {
11635         DisplayError(_("Can't back up any further"), 0);
11636         return FALSE;
11637     }
11638     if (cmailMsgLoaded) {
11639         return CmailLoadGame(lastLoadGameFP, gameNumber,
11640                              lastLoadGameTitle, lastLoadGameUseList);
11641     } else {
11642         return LoadGame(lastLoadGameFP, gameNumber,
11643                         lastLoadGameTitle, lastLoadGameUseList);
11644     }
11645 }
11646
11647 int keys[EmptySquare+1];
11648
11649 int
11650 PositionMatches (Board b1, Board b2)
11651 {
11652     int r, f, sum=0;
11653     switch(appData.searchMode) {
11654         case 1: return CompareWithRights(b1, b2);
11655         case 2:
11656             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11657                 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
11658             }
11659             return TRUE;
11660         case 3:
11661             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11662               if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
11663                 sum += keys[b1[r][f]] - keys[b2[r][f]];
11664             }
11665             return sum==0;
11666         case 4:
11667             for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11668                 sum += keys[b1[r][f]] - keys[b2[r][f]];
11669             }
11670             return sum==0;
11671     }
11672     return TRUE;
11673 }
11674
11675 #define Q_PROMO  4
11676 #define Q_EP     3
11677 #define Q_BCASTL 2
11678 #define Q_WCASTL 1
11679
11680 int pieceList[256], quickBoard[256];
11681 ChessSquare pieceType[256] = { EmptySquare };
11682 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
11683 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
11684 int soughtTotal, turn;
11685 Boolean epOK, flipSearch;
11686
11687 typedef struct {
11688     unsigned char piece, to;
11689 } Move;
11690
11691 #define DSIZE (250000)
11692
11693 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
11694 Move *moveDatabase = initialSpace;
11695 unsigned int movePtr, dataSize = DSIZE;
11696
11697 int
11698 MakePieceList (Board board, int *counts)
11699 {
11700     int r, f, n=Q_PROMO, total=0;
11701     for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
11702     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11703         int sq = f + (r<<4);
11704         if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
11705             quickBoard[sq] = ++n;
11706             pieceList[n] = sq;
11707             pieceType[n] = board[r][f];
11708             counts[board[r][f]]++;
11709             if(board[r][f] == WhiteKing) pieceList[1] = n; else
11710             if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
11711             total++;
11712         }
11713     }
11714     epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
11715     return total;
11716 }
11717
11718 void
11719 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
11720 {
11721     int sq = fromX + (fromY<<4);
11722     int piece = quickBoard[sq];
11723     quickBoard[sq] = 0;
11724     moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
11725     if(piece == pieceList[1] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11726         int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
11727         moveDatabase[movePtr++].piece = Q_WCASTL;
11728         quickBoard[sq] = piece;
11729         piece = quickBoard[from]; quickBoard[from] = 0;
11730         moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11731     } else
11732     if(piece == pieceList[2] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11733         int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
11734         moveDatabase[movePtr++].piece = Q_BCASTL;
11735         quickBoard[sq] = piece;
11736         piece = quickBoard[from]; quickBoard[from] = 0;
11737         moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11738     } else
11739     if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
11740         quickBoard[(fromY<<4)+toX] = 0;
11741         moveDatabase[movePtr].piece = Q_EP;
11742         moveDatabase[movePtr++].to = (fromY<<4)+toX;
11743         moveDatabase[movePtr].to = sq;
11744     } else
11745     if(promoPiece != pieceType[piece]) {
11746         moveDatabase[movePtr++].piece = Q_PROMO;
11747         moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
11748     }
11749     moveDatabase[movePtr].piece = piece;
11750     quickBoard[sq] = piece;
11751     movePtr++;
11752 }
11753
11754 int
11755 PackGame (Board board)
11756 {
11757     Move *newSpace = NULL;
11758     moveDatabase[movePtr].piece = 0; // terminate previous game
11759     if(movePtr > dataSize) {
11760         if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
11761         dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
11762         if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
11763         if(newSpace) {
11764             int i;
11765             Move *p = moveDatabase, *q = newSpace;
11766             for(i=0; i<movePtr; i++) *q++ = *p++;    // copy to newly allocated space
11767             if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
11768             moveDatabase = newSpace;
11769         } else { // calloc failed, we must be out of memory. Too bad...
11770             dataSize = 0; // prevent calloc events for all subsequent games
11771             return 0;     // and signal this one isn't cached
11772         }
11773     }
11774     movePtr++;
11775     MakePieceList(board, counts);
11776     return movePtr;
11777 }
11778
11779 int
11780 QuickCompare (Board board, int *minCounts, int *maxCounts)
11781 {   // compare according to search mode
11782     int r, f;
11783     switch(appData.searchMode)
11784     {
11785       case 1: // exact position match
11786         if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
11787         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11788             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11789         }
11790         break;
11791       case 2: // can have extra material on empty squares
11792         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11793             if(board[r][f] == EmptySquare) continue;
11794             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11795         }
11796         break;
11797       case 3: // material with exact Pawn structure
11798         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11799             if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
11800             if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11801         } // fall through to material comparison
11802       case 4: // exact material
11803         for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
11804         break;
11805       case 6: // material range with given imbalance
11806         for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
11807         // fall through to range comparison
11808       case 5: // material range
11809         for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
11810     }
11811     return TRUE;
11812 }
11813
11814 int
11815 QuickScan (Board board, Move *move)
11816 {   // reconstruct game,and compare all positions in it
11817     int cnt=0, stretch=0, total = MakePieceList(board, counts);
11818     do {
11819         int piece = move->piece;
11820         int to = move->to, from = pieceList[piece];
11821         if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
11822           if(!piece) return -1;
11823           if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
11824             piece = (++move)->piece;
11825             from = pieceList[piece];
11826             counts[pieceType[piece]]--;
11827             pieceType[piece] = (ChessSquare) move->to;
11828             counts[move->to]++;
11829           } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
11830             counts[pieceType[quickBoard[to]]]--;
11831             quickBoard[to] = 0; total--;
11832             move++;
11833             continue;
11834           } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
11835             piece = pieceList[piece]; // first two elements of pieceList contain King numbers
11836             from  = pieceList[piece]; // so this must be King
11837             quickBoard[from] = 0;
11838             pieceList[piece] = to;
11839             from = pieceList[(++move)->piece]; // for FRC this has to be done here
11840             quickBoard[from] = 0; // rook
11841             quickBoard[to] = piece;
11842             to = move->to; piece = move->piece;
11843             goto aftercastle;
11844           }
11845         }
11846         if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
11847         if((total -= (quickBoard[to] != 0)) < soughtTotal) return -1; // piece count dropped below what we search for
11848         quickBoard[from] = 0;
11849       aftercastle:
11850         quickBoard[to] = piece;
11851         pieceList[piece] = to;
11852         cnt++; turn ^= 3;
11853         if(QuickCompare(soughtBoard, minSought, maxSought) ||
11854            appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
11855            flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
11856                                 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
11857           ) {
11858             static int lastCounts[EmptySquare+1];
11859             int i;
11860             if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
11861             if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
11862         } else stretch = 0;
11863         if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) return cnt + 1 - stretch;
11864         move++;
11865     } while(1);
11866 }
11867
11868 void
11869 InitSearch ()
11870 {
11871     int r, f;
11872     flipSearch = FALSE;
11873     CopyBoard(soughtBoard, boards[currentMove]);
11874     soughtTotal = MakePieceList(soughtBoard, maxSought);
11875     soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
11876     if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
11877     CopyBoard(reverseBoard, boards[currentMove]);
11878     for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11879         int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
11880         if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
11881         reverseBoard[r][f] = piece;
11882     }
11883     reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
11884     for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
11885     if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
11886                  || (boards[currentMove][CASTLING][2] == NoRights ||
11887                      boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
11888                  && (boards[currentMove][CASTLING][5] == NoRights ||
11889                      boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
11890       ) {
11891         flipSearch = TRUE;
11892         CopyBoard(flipBoard, soughtBoard);
11893         CopyBoard(rotateBoard, reverseBoard);
11894         for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11895             flipBoard[r][f]    = soughtBoard[r][BOARD_WIDTH-1-f];
11896             rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
11897         }
11898     }
11899     for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
11900     if(appData.searchMode >= 5) {
11901         for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
11902         MakePieceList(soughtBoard, minSought);
11903         for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
11904     }
11905     if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
11906         soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
11907 }
11908
11909 GameInfo dummyInfo;
11910 static int creatingBook;
11911
11912 int
11913 GameContainsPosition (FILE *f, ListGame *lg)
11914 {
11915     int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
11916     int fromX, fromY, toX, toY;
11917     char promoChar;
11918     static int initDone=FALSE;
11919
11920     // weed out games based on numerical tag comparison
11921     if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
11922     if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
11923     if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
11924     if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
11925     if(!initDone) {
11926         for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
11927         initDone = TRUE;
11928     }
11929     if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen);
11930     else CopyBoard(boards[scratch], initialPosition); // default start position
11931     if(lg->moves) {
11932         turn = btm + 1;
11933         if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
11934         if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
11935     }
11936     if(btm) plyNr++;
11937     if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
11938     fseek(f, lg->offset, 0);
11939     yynewfile(f);
11940     while(1) {
11941         yyboardindex = scratch;
11942         quickFlag = plyNr+1;
11943         next = Myylex();
11944         quickFlag = 0;
11945         switch(next) {
11946             case PGNTag:
11947                 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
11948             default:
11949                 continue;
11950
11951             case XBoardGame:
11952             case GNUChessGame:
11953                 if(plyNr) return -1; // after we have seen moves, this is for new game
11954               continue;
11955
11956             case AmbiguousMove: // we cannot reconstruct the game beyond these two
11957             case ImpossibleMove:
11958             case WhiteWins: // game ends here with these four
11959             case BlackWins:
11960             case GameIsDrawn:
11961             case GameUnfinished:
11962                 return -1;
11963
11964             case IllegalMove:
11965                 if(appData.testLegality) return -1;
11966             case WhiteCapturesEnPassant:
11967             case BlackCapturesEnPassant:
11968             case WhitePromotion:
11969             case BlackPromotion:
11970             case WhiteNonPromotion:
11971             case BlackNonPromotion:
11972             case NormalMove:
11973             case WhiteKingSideCastle:
11974             case WhiteQueenSideCastle:
11975             case BlackKingSideCastle:
11976             case BlackQueenSideCastle:
11977             case WhiteKingSideCastleWild:
11978             case WhiteQueenSideCastleWild:
11979             case BlackKingSideCastleWild:
11980             case BlackQueenSideCastleWild:
11981             case WhiteHSideCastleFR:
11982             case WhiteASideCastleFR:
11983             case BlackHSideCastleFR:
11984             case BlackASideCastleFR:
11985                 fromX = currentMoveString[0] - AAA;
11986                 fromY = currentMoveString[1] - ONE;
11987                 toX = currentMoveString[2] - AAA;
11988                 toY = currentMoveString[3] - ONE;
11989                 promoChar = currentMoveString[4];
11990                 break;
11991             case WhiteDrop:
11992             case BlackDrop:
11993                 fromX = next == WhiteDrop ?
11994                   (int) CharToPiece(ToUpper(currentMoveString[0])) :
11995                   (int) CharToPiece(ToLower(currentMoveString[0]));
11996                 fromY = DROP_RANK;
11997                 toX = currentMoveString[2] - AAA;
11998                 toY = currentMoveString[3] - ONE;
11999                 promoChar = 0;
12000                 break;
12001         }
12002         // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
12003         plyNr++;
12004         ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
12005         if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
12006         if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
12007         if(appData.findMirror) {
12008             if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
12009             if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
12010         }
12011     }
12012 }
12013
12014 /* Load the nth game from open file f */
12015 int
12016 LoadGame (FILE *f, int gameNumber, char *title, int useList)
12017 {
12018     ChessMove cm;
12019     char buf[MSG_SIZ];
12020     int gn = gameNumber;
12021     ListGame *lg = NULL;
12022     int numPGNTags = 0;
12023     int err, pos = -1;
12024     GameMode oldGameMode;
12025     VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
12026
12027     if (appData.debugMode)
12028         fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
12029
12030     if (gameMode == Training )
12031         SetTrainingModeOff();
12032
12033     oldGameMode = gameMode;
12034     if (gameMode != BeginningOfGame) {
12035       Reset(FALSE, TRUE);
12036     }
12037
12038     gameFileFP = f;
12039     if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
12040         fclose(lastLoadGameFP);
12041     }
12042
12043     if (useList) {
12044         lg = (ListGame *) ListElem(&gameList, gameNumber-1);
12045
12046         if (lg) {
12047             fseek(f, lg->offset, 0);
12048             GameListHighlight(gameNumber);
12049             pos = lg->position;
12050             gn = 1;
12051         }
12052         else {
12053             if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
12054               appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
12055             else
12056             DisplayError(_("Game number out of range"), 0);
12057             return FALSE;
12058         }
12059     } else {
12060         GameListDestroy();
12061         if (fseek(f, 0, 0) == -1) {
12062             if (f == lastLoadGameFP ?
12063                 gameNumber == lastLoadGameNumber + 1 :
12064                 gameNumber == 1) {
12065                 gn = 1;
12066             } else {
12067                 DisplayError(_("Can't seek on game file"), 0);
12068                 return FALSE;
12069             }
12070         }
12071     }
12072     lastLoadGameFP = f;
12073     lastLoadGameNumber = gameNumber;
12074     safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
12075     lastLoadGameUseList = useList;
12076
12077     yynewfile(f);
12078
12079     if (lg && lg->gameInfo.white && lg->gameInfo.black) {
12080       snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
12081                 lg->gameInfo.black);
12082             DisplayTitle(buf);
12083     } else if (*title != NULLCHAR) {
12084         if (gameNumber > 1) {
12085           snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
12086             DisplayTitle(buf);
12087         } else {
12088             DisplayTitle(title);
12089         }
12090     }
12091
12092     if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
12093         gameMode = PlayFromGameFile;
12094         ModeHighlight();
12095     }
12096
12097     currentMove = forwardMostMove = backwardMostMove = 0;
12098     CopyBoard(boards[0], initialPosition);
12099     StopClocks();
12100
12101     /*
12102      * Skip the first gn-1 games in the file.
12103      * Also skip over anything that precedes an identifiable
12104      * start of game marker, to avoid being confused by
12105      * garbage at the start of the file.  Currently
12106      * recognized start of game markers are the move number "1",
12107      * the pattern "gnuchess .* game", the pattern
12108      * "^[#;%] [^ ]* game file", and a PGN tag block.
12109      * A game that starts with one of the latter two patterns
12110      * will also have a move number 1, possibly
12111      * following a position diagram.
12112      * 5-4-02: Let's try being more lenient and allowing a game to
12113      * start with an unnumbered move.  Does that break anything?
12114      */
12115     cm = lastLoadGameStart = EndOfFile;
12116     while (gn > 0) {
12117         yyboardindex = forwardMostMove;
12118         cm = (ChessMove) Myylex();
12119         switch (cm) {
12120           case EndOfFile:
12121             if (cmailMsgLoaded) {
12122                 nCmailGames = CMAIL_MAX_GAMES - gn;
12123             } else {
12124                 Reset(TRUE, TRUE);
12125                 DisplayError(_("Game not found in file"), 0);
12126             }
12127             return FALSE;
12128
12129           case GNUChessGame:
12130           case XBoardGame:
12131             gn--;
12132             lastLoadGameStart = cm;
12133             break;
12134
12135           case MoveNumberOne:
12136             switch (lastLoadGameStart) {
12137               case GNUChessGame:
12138               case XBoardGame:
12139               case PGNTag:
12140                 break;
12141               case MoveNumberOne:
12142               case EndOfFile:
12143                 gn--;           /* count this game */
12144                 lastLoadGameStart = cm;
12145                 break;
12146               default:
12147                 /* impossible */
12148                 break;
12149             }
12150             break;
12151
12152           case PGNTag:
12153             switch (lastLoadGameStart) {
12154               case GNUChessGame:
12155               case PGNTag:
12156               case MoveNumberOne:
12157               case EndOfFile:
12158                 gn--;           /* count this game */
12159                 lastLoadGameStart = cm;
12160                 break;
12161               case XBoardGame:
12162                 lastLoadGameStart = cm; /* game counted already */
12163                 break;
12164               default:
12165                 /* impossible */
12166                 break;
12167             }
12168             if (gn > 0) {
12169                 do {
12170                     yyboardindex = forwardMostMove;
12171                     cm = (ChessMove) Myylex();
12172                 } while (cm == PGNTag || cm == Comment);
12173             }
12174             break;
12175
12176           case WhiteWins:
12177           case BlackWins:
12178           case GameIsDrawn:
12179             if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
12180                 if (   cmailResult[CMAIL_MAX_GAMES - gn - 1]
12181                     != CMAIL_OLD_RESULT) {
12182                     nCmailResults ++ ;
12183                     cmailResult[  CMAIL_MAX_GAMES
12184                                 - gn - 1] = CMAIL_OLD_RESULT;
12185                 }
12186             }
12187             break;
12188
12189           case NormalMove:
12190             /* Only a NormalMove can be at the start of a game
12191              * without a position diagram. */
12192             if (lastLoadGameStart == EndOfFile ) {
12193               gn--;
12194               lastLoadGameStart = MoveNumberOne;
12195             }
12196             break;
12197
12198           default:
12199             break;
12200         }
12201     }
12202
12203     if (appData.debugMode)
12204       fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
12205
12206     if (cm == XBoardGame) {
12207         /* Skip any header junk before position diagram and/or move 1 */
12208         for (;;) {
12209             yyboardindex = forwardMostMove;
12210             cm = (ChessMove) Myylex();
12211
12212             if (cm == EndOfFile ||
12213                 cm == GNUChessGame || cm == XBoardGame) {
12214                 /* Empty game; pretend end-of-file and handle later */
12215                 cm = EndOfFile;
12216                 break;
12217             }
12218
12219             if (cm == MoveNumberOne || cm == PositionDiagram ||
12220                 cm == PGNTag || cm == Comment)
12221               break;
12222         }
12223     } else if (cm == GNUChessGame) {
12224         if (gameInfo.event != NULL) {
12225             free(gameInfo.event);
12226         }
12227         gameInfo.event = StrSave(yy_text);
12228     }
12229
12230     startedFromSetupPosition = FALSE;
12231     while (cm == PGNTag) {
12232         if (appData.debugMode)
12233           fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
12234         err = ParsePGNTag(yy_text, &gameInfo);
12235         if (!err) numPGNTags++;
12236
12237         /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
12238         if(gameInfo.variant != oldVariant) {
12239             startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
12240             ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
12241             InitPosition(TRUE);
12242             oldVariant = gameInfo.variant;
12243             if (appData.debugMode)
12244               fprintf(debugFP, "New variant %d\n", (int) oldVariant);
12245         }
12246
12247
12248         if (gameInfo.fen != NULL) {
12249           Board initial_position;
12250           startedFromSetupPosition = TRUE;
12251           if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
12252             Reset(TRUE, TRUE);
12253             DisplayError(_("Bad FEN position in file"), 0);
12254             return FALSE;
12255           }
12256           CopyBoard(boards[0], initial_position);
12257           if (blackPlaysFirst) {
12258             currentMove = forwardMostMove = backwardMostMove = 1;
12259             CopyBoard(boards[1], initial_position);
12260             safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12261             safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12262             timeRemaining[0][1] = whiteTimeRemaining;
12263             timeRemaining[1][1] = blackTimeRemaining;
12264             if (commentList[0] != NULL) {
12265               commentList[1] = commentList[0];
12266               commentList[0] = NULL;
12267             }
12268           } else {
12269             currentMove = forwardMostMove = backwardMostMove = 0;
12270           }
12271           /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
12272           {   int i;
12273               initialRulePlies = FENrulePlies;
12274               for( i=0; i< nrCastlingRights; i++ )
12275                   initialRights[i] = initial_position[CASTLING][i];
12276           }
12277           yyboardindex = forwardMostMove;
12278           free(gameInfo.fen);
12279           gameInfo.fen = NULL;
12280         }
12281
12282         yyboardindex = forwardMostMove;
12283         cm = (ChessMove) Myylex();
12284
12285         /* Handle comments interspersed among the tags */
12286         while (cm == Comment) {
12287             char *p;
12288             if (appData.debugMode)
12289               fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12290             p = yy_text;
12291             AppendComment(currentMove, p, FALSE);
12292             yyboardindex = forwardMostMove;
12293             cm = (ChessMove) Myylex();
12294         }
12295     }
12296
12297     /* don't rely on existence of Event tag since if game was
12298      * pasted from clipboard the Event tag may not exist
12299      */
12300     if (numPGNTags > 0){
12301         char *tags;
12302         if (gameInfo.variant == VariantNormal) {
12303           VariantClass v = StringToVariant(gameInfo.event);
12304           // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
12305           if(v < VariantShogi) gameInfo.variant = v;
12306         }
12307         if (!matchMode) {
12308           if( appData.autoDisplayTags ) {
12309             tags = PGNTags(&gameInfo);
12310             TagsPopUp(tags, CmailMsg());
12311             free(tags);
12312           }
12313         }
12314     } else {
12315         /* Make something up, but don't display it now */
12316         SetGameInfo();
12317         TagsPopDown();
12318     }
12319
12320     if (cm == PositionDiagram) {
12321         int i, j;
12322         char *p;
12323         Board initial_position;
12324
12325         if (appData.debugMode)
12326           fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
12327
12328         if (!startedFromSetupPosition) {
12329             p = yy_text;
12330             for (i = BOARD_HEIGHT - 1; i >= 0; i--)
12331               for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
12332                 switch (*p) {
12333                   case '{':
12334                   case '[':
12335                   case '-':
12336                   case ' ':
12337                   case '\t':
12338                   case '\n':
12339                   case '\r':
12340                     break;
12341                   default:
12342                     initial_position[i][j++] = CharToPiece(*p);
12343                     break;
12344                 }
12345             while (*p == ' ' || *p == '\t' ||
12346                    *p == '\n' || *p == '\r') p++;
12347
12348             if (strncmp(p, "black", strlen("black"))==0)
12349               blackPlaysFirst = TRUE;
12350             else
12351               blackPlaysFirst = FALSE;
12352             startedFromSetupPosition = TRUE;
12353
12354             CopyBoard(boards[0], initial_position);
12355             if (blackPlaysFirst) {
12356                 currentMove = forwardMostMove = backwardMostMove = 1;
12357                 CopyBoard(boards[1], initial_position);
12358                 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12359                 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12360                 timeRemaining[0][1] = whiteTimeRemaining;
12361                 timeRemaining[1][1] = blackTimeRemaining;
12362                 if (commentList[0] != NULL) {
12363                     commentList[1] = commentList[0];
12364                     commentList[0] = NULL;
12365                 }
12366             } else {
12367                 currentMove = forwardMostMove = backwardMostMove = 0;
12368             }
12369         }
12370         yyboardindex = forwardMostMove;
12371         cm = (ChessMove) Myylex();
12372     }
12373
12374   if(!creatingBook) {
12375     if (first.pr == NoProc) {
12376         StartChessProgram(&first);
12377     }
12378     InitChessProgram(&first, FALSE);
12379     SendToProgram("force\n", &first);
12380     if (startedFromSetupPosition) {
12381         SendBoard(&first, forwardMostMove);
12382     if (appData.debugMode) {
12383         fprintf(debugFP, "Load Game\n");
12384     }
12385         DisplayBothClocks();
12386     }
12387   }
12388
12389     /* [HGM] server: flag to write setup moves in broadcast file as one */
12390     loadFlag = appData.suppressLoadMoves;
12391
12392     while (cm == Comment) {
12393         char *p;
12394         if (appData.debugMode)
12395           fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12396         p = yy_text;
12397         AppendComment(currentMove, p, FALSE);
12398         yyboardindex = forwardMostMove;
12399         cm = (ChessMove) Myylex();
12400     }
12401
12402     if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
12403         cm == WhiteWins || cm == BlackWins ||
12404         cm == GameIsDrawn || cm == GameUnfinished) {
12405         DisplayMessage("", _("No moves in game"));
12406         if (cmailMsgLoaded) {
12407             if (appData.debugMode)
12408               fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
12409             ClearHighlights();
12410             flipView = FALSE;
12411         }
12412         DrawPosition(FALSE, boards[currentMove]);
12413         DisplayBothClocks();
12414         gameMode = EditGame;
12415         ModeHighlight();
12416         gameFileFP = NULL;
12417         cmailOldMove = 0;
12418         return TRUE;
12419     }
12420
12421     // [HGM] PV info: routine tests if comment empty
12422     if (!matchMode && (pausing || appData.timeDelay != 0)) {
12423         DisplayComment(currentMove - 1, commentList[currentMove]);
12424     }
12425     if (!matchMode && appData.timeDelay != 0)
12426       DrawPosition(FALSE, boards[currentMove]);
12427
12428     if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
12429       programStats.ok_to_send = 1;
12430     }
12431
12432     /* if the first token after the PGN tags is a move
12433      * and not move number 1, retrieve it from the parser
12434      */
12435     if (cm != MoveNumberOne)
12436         LoadGameOneMove(cm);
12437
12438     /* load the remaining moves from the file */
12439     while (LoadGameOneMove(EndOfFile)) {
12440       timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12441       timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12442     }
12443
12444     /* rewind to the start of the game */
12445     currentMove = backwardMostMove;
12446
12447     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12448
12449     if (oldGameMode == AnalyzeFile) {
12450       appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
12451       AnalyzeFileEvent();
12452     } else
12453     if (oldGameMode == AnalyzeMode) {
12454       AnalyzeFileEvent();
12455     }
12456
12457     if(creatingBook) return TRUE;
12458     if (!matchMode && pos > 0) {
12459         ToNrEvent(pos); // [HGM] no autoplay if selected on position
12460     } else
12461     if (matchMode || appData.timeDelay == 0) {
12462       ToEndEvent();
12463     } else if (appData.timeDelay > 0) {
12464       AutoPlayGameLoop();
12465     }
12466
12467     if (appData.debugMode)
12468         fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
12469
12470     loadFlag = 0; /* [HGM] true game starts */
12471     return TRUE;
12472 }
12473
12474 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
12475 int
12476 ReloadPosition (int offset)
12477 {
12478     int positionNumber = lastLoadPositionNumber + offset;
12479     if (lastLoadPositionFP == NULL) {
12480         DisplayError(_("No position has been loaded yet"), 0);
12481         return FALSE;
12482     }
12483     if (positionNumber <= 0) {
12484         DisplayError(_("Can't back up any further"), 0);
12485         return FALSE;
12486     }
12487     return LoadPosition(lastLoadPositionFP, positionNumber,
12488                         lastLoadPositionTitle);
12489 }
12490
12491 /* Load the nth position from the given file */
12492 int
12493 LoadPositionFromFile (char *filename, int n, char *title)
12494 {
12495     FILE *f;
12496     char buf[MSG_SIZ];
12497
12498     if (strcmp(filename, "-") == 0) {
12499         return LoadPosition(stdin, n, "stdin");
12500     } else {
12501         f = fopen(filename, "rb");
12502         if (f == NULL) {
12503             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12504             DisplayError(buf, errno);
12505             return FALSE;
12506         } else {
12507             return LoadPosition(f, n, title);
12508         }
12509     }
12510 }
12511
12512 /* Load the nth position from the given open file, and close it */
12513 int
12514 LoadPosition (FILE *f, int positionNumber, char *title)
12515 {
12516     char *p, line[MSG_SIZ];
12517     Board initial_position;
12518     int i, j, fenMode, pn;
12519
12520     if (gameMode == Training )
12521         SetTrainingModeOff();
12522
12523     if (gameMode != BeginningOfGame) {
12524         Reset(FALSE, TRUE);
12525     }
12526     if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
12527         fclose(lastLoadPositionFP);
12528     }
12529     if (positionNumber == 0) positionNumber = 1;
12530     lastLoadPositionFP = f;
12531     lastLoadPositionNumber = positionNumber;
12532     safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
12533     if (first.pr == NoProc && !appData.noChessProgram) {
12534       StartChessProgram(&first);
12535       InitChessProgram(&first, FALSE);
12536     }
12537     pn = positionNumber;
12538     if (positionNumber < 0) {
12539         /* Negative position number means to seek to that byte offset */
12540         if (fseek(f, -positionNumber, 0) == -1) {
12541             DisplayError(_("Can't seek on position file"), 0);
12542             return FALSE;
12543         };
12544         pn = 1;
12545     } else {
12546         if (fseek(f, 0, 0) == -1) {
12547             if (f == lastLoadPositionFP ?
12548                 positionNumber == lastLoadPositionNumber + 1 :
12549                 positionNumber == 1) {
12550                 pn = 1;
12551             } else {
12552                 DisplayError(_("Can't seek on position file"), 0);
12553                 return FALSE;
12554             }
12555         }
12556     }
12557     /* See if this file is FEN or old-style xboard */
12558     if (fgets(line, MSG_SIZ, f) == NULL) {
12559         DisplayError(_("Position not found in file"), 0);
12560         return FALSE;
12561     }
12562     // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
12563     fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
12564
12565     if (pn >= 2) {
12566         if (fenMode || line[0] == '#') pn--;
12567         while (pn > 0) {
12568             /* skip positions before number pn */
12569             if (fgets(line, MSG_SIZ, f) == NULL) {
12570                 Reset(TRUE, TRUE);
12571                 DisplayError(_("Position not found in file"), 0);
12572                 return FALSE;
12573             }
12574             if (fenMode || line[0] == '#') pn--;
12575         }
12576     }
12577
12578     if (fenMode) {
12579         if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
12580             DisplayError(_("Bad FEN position in file"), 0);
12581             return FALSE;
12582         }
12583     } else {
12584         (void) fgets(line, MSG_SIZ, f);
12585         (void) fgets(line, MSG_SIZ, f);
12586
12587         for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
12588             (void) fgets(line, MSG_SIZ, f);
12589             for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
12590                 if (*p == ' ')
12591                   continue;
12592                 initial_position[i][j++] = CharToPiece(*p);
12593             }
12594         }
12595
12596         blackPlaysFirst = FALSE;
12597         if (!feof(f)) {
12598             (void) fgets(line, MSG_SIZ, f);
12599             if (strncmp(line, "black", strlen("black"))==0)
12600               blackPlaysFirst = TRUE;
12601         }
12602     }
12603     startedFromSetupPosition = TRUE;
12604
12605     CopyBoard(boards[0], initial_position);
12606     if (blackPlaysFirst) {
12607         currentMove = forwardMostMove = backwardMostMove = 1;
12608         safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12609         safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12610         CopyBoard(boards[1], initial_position);
12611         DisplayMessage("", _("Black to play"));
12612     } else {
12613         currentMove = forwardMostMove = backwardMostMove = 0;
12614         DisplayMessage("", _("White to play"));
12615     }
12616     initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
12617     if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
12618         SendToProgram("force\n", &first);
12619         SendBoard(&first, forwardMostMove);
12620     }
12621     if (appData.debugMode) {
12622 int i, j;
12623   for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
12624   for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
12625         fprintf(debugFP, "Load Position\n");
12626     }
12627
12628     if (positionNumber > 1) {
12629       snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
12630         DisplayTitle(line);
12631     } else {
12632         DisplayTitle(title);
12633     }
12634     gameMode = EditGame;
12635     ModeHighlight();
12636     ResetClocks();
12637     timeRemaining[0][1] = whiteTimeRemaining;
12638     timeRemaining[1][1] = blackTimeRemaining;
12639     DrawPosition(FALSE, boards[currentMove]);
12640
12641     return TRUE;
12642 }
12643
12644
12645 void
12646 CopyPlayerNameIntoFileName (char **dest, char *src)
12647 {
12648     while (*src != NULLCHAR && *src != ',') {
12649         if (*src == ' ') {
12650             *(*dest)++ = '_';
12651             src++;
12652         } else {
12653             *(*dest)++ = *src++;
12654         }
12655     }
12656 }
12657
12658 char *
12659 DefaultFileName (char *ext)
12660 {
12661     static char def[MSG_SIZ];
12662     char *p;
12663
12664     if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
12665         p = def;
12666         CopyPlayerNameIntoFileName(&p, gameInfo.white);
12667         *p++ = '-';
12668         CopyPlayerNameIntoFileName(&p, gameInfo.black);
12669         *p++ = '.';
12670         safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
12671     } else {
12672         def[0] = NULLCHAR;
12673     }
12674     return def;
12675 }
12676
12677 /* Save the current game to the given file */
12678 int
12679 SaveGameToFile (char *filename, int append)
12680 {
12681     FILE *f;
12682     char buf[MSG_SIZ];
12683     int result, i, t,tot=0;
12684
12685     if (strcmp(filename, "-") == 0) {
12686         return SaveGame(stdout, 0, NULL);
12687     } else {
12688         for(i=0; i<10; i++) { // upto 10 tries
12689              f = fopen(filename, append ? "a" : "w");
12690              if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
12691              if(f || errno != 13) break;
12692              DoSleep(t = 5 + random()%11); // wait 5-15 msec
12693              tot += t;
12694         }
12695         if (f == NULL) {
12696             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12697             DisplayError(buf, errno);
12698             return FALSE;
12699         } else {
12700             safeStrCpy(buf, lastMsg, MSG_SIZ);
12701             DisplayMessage(_("Waiting for access to save file"), "");
12702             flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
12703             DisplayMessage(_("Saving game"), "");
12704             if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno);     // better safe than sorry...
12705             result = SaveGame(f, 0, NULL);
12706             DisplayMessage(buf, "");
12707             return result;
12708         }
12709     }
12710 }
12711
12712 char *
12713 SavePart (char *str)
12714 {
12715     static char buf[MSG_SIZ];
12716     char *p;
12717
12718     p = strchr(str, ' ');
12719     if (p == NULL) return str;
12720     strncpy(buf, str, p - str);
12721     buf[p - str] = NULLCHAR;
12722     return buf;
12723 }
12724
12725 #define PGN_MAX_LINE 75
12726
12727 #define PGN_SIDE_WHITE  0
12728 #define PGN_SIDE_BLACK  1
12729
12730 static int
12731 FindFirstMoveOutOfBook (int side)
12732 {
12733     int result = -1;
12734
12735     if( backwardMostMove == 0 && ! startedFromSetupPosition) {
12736         int index = backwardMostMove;
12737         int has_book_hit = 0;
12738
12739         if( (index % 2) != side ) {
12740             index++;
12741         }
12742
12743         while( index < forwardMostMove ) {
12744             /* Check to see if engine is in book */
12745             int depth = pvInfoList[index].depth;
12746             int score = pvInfoList[index].score;
12747             int in_book = 0;
12748
12749             if( depth <= 2 ) {
12750                 in_book = 1;
12751             }
12752             else if( score == 0 && depth == 63 ) {
12753                 in_book = 1; /* Zappa */
12754             }
12755             else if( score == 2 && depth == 99 ) {
12756                 in_book = 1; /* Abrok */
12757             }
12758
12759             has_book_hit += in_book;
12760
12761             if( ! in_book ) {
12762                 result = index;
12763
12764                 break;
12765             }
12766
12767             index += 2;
12768         }
12769     }
12770
12771     return result;
12772 }
12773
12774 void
12775 GetOutOfBookInfo (char * buf)
12776 {
12777     int oob[2];
12778     int i;
12779     int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12780
12781     oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
12782     oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
12783
12784     *buf = '\0';
12785
12786     if( oob[0] >= 0 || oob[1] >= 0 ) {
12787         for( i=0; i<2; i++ ) {
12788             int idx = oob[i];
12789
12790             if( idx >= 0 ) {
12791                 if( i > 0 && oob[0] >= 0 ) {
12792                     strcat( buf, "   " );
12793                 }
12794
12795                 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
12796                 sprintf( buf+strlen(buf), "%s%.2f",
12797                     pvInfoList[idx].score >= 0 ? "+" : "",
12798                     pvInfoList[idx].score / 100.0 );
12799             }
12800         }
12801     }
12802 }
12803
12804 /* Save game in PGN style and close the file */
12805 int
12806 SaveGamePGN (FILE *f)
12807 {
12808     int i, offset, linelen, newblock;
12809 //    char *movetext;
12810     char numtext[32];
12811     int movelen, numlen, blank;
12812     char move_buffer[100]; /* [AS] Buffer for move+PV info */
12813
12814     offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12815
12816     PrintPGNTags(f, &gameInfo);
12817
12818     if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
12819
12820     if (backwardMostMove > 0 || startedFromSetupPosition) {
12821         char *fen = PositionToFEN(backwardMostMove, NULL);
12822         fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
12823         fprintf(f, "\n{--------------\n");
12824         PrintPosition(f, backwardMostMove);
12825         fprintf(f, "--------------}\n");
12826         free(fen);
12827     }
12828     else {
12829         /* [AS] Out of book annotation */
12830         if( appData.saveOutOfBookInfo ) {
12831             char buf[64];
12832
12833             GetOutOfBookInfo( buf );
12834
12835             if( buf[0] != '\0' ) {
12836                 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
12837             }
12838         }
12839
12840         fprintf(f, "\n");
12841     }
12842
12843     i = backwardMostMove;
12844     linelen = 0;
12845     newblock = TRUE;
12846
12847     while (i < forwardMostMove) {
12848         /* Print comments preceding this move */
12849         if (commentList[i] != NULL) {
12850             if (linelen > 0) fprintf(f, "\n");
12851             fprintf(f, "%s", commentList[i]);
12852             linelen = 0;
12853             newblock = TRUE;
12854         }
12855
12856         /* Format move number */
12857         if ((i % 2) == 0)
12858           snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
12859         else
12860           if (newblock)
12861             snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
12862           else
12863             numtext[0] = NULLCHAR;
12864
12865         numlen = strlen(numtext);
12866         newblock = FALSE;
12867
12868         /* Print move number */
12869         blank = linelen > 0 && numlen > 0;
12870         if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
12871             fprintf(f, "\n");
12872             linelen = 0;
12873             blank = 0;
12874         }
12875         if (blank) {
12876             fprintf(f, " ");
12877             linelen++;
12878         }
12879         fprintf(f, "%s", numtext);
12880         linelen += numlen;
12881
12882         /* Get move */
12883         safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
12884         movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
12885
12886         /* Print move */
12887         blank = linelen > 0 && movelen > 0;
12888         if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12889             fprintf(f, "\n");
12890             linelen = 0;
12891             blank = 0;
12892         }
12893         if (blank) {
12894             fprintf(f, " ");
12895             linelen++;
12896         }
12897         fprintf(f, "%s", move_buffer);
12898         linelen += movelen;
12899
12900         /* [AS] Add PV info if present */
12901         if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
12902             /* [HGM] add time */
12903             char buf[MSG_SIZ]; int seconds;
12904
12905             seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
12906
12907             if( seconds <= 0)
12908               buf[0] = 0;
12909             else
12910               if( seconds < 30 )
12911                 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
12912               else
12913                 {
12914                   seconds = (seconds + 4)/10; // round to full seconds
12915                   if( seconds < 60 )
12916                     snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
12917                   else
12918                     snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
12919                 }
12920
12921             snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
12922                       pvInfoList[i].score >= 0 ? "+" : "",
12923                       pvInfoList[i].score / 100.0,
12924                       pvInfoList[i].depth,
12925                       buf );
12926
12927             movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
12928
12929             /* Print score/depth */
12930             blank = linelen > 0 && movelen > 0;
12931             if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12932                 fprintf(f, "\n");
12933                 linelen = 0;
12934                 blank = 0;
12935             }
12936             if (blank) {
12937                 fprintf(f, " ");
12938                 linelen++;
12939             }
12940             fprintf(f, "%s", move_buffer);
12941             linelen += movelen;
12942         }
12943
12944         i++;
12945     }
12946
12947     /* Start a new line */
12948     if (linelen > 0) fprintf(f, "\n");
12949
12950     /* Print comments after last move */
12951     if (commentList[i] != NULL) {
12952         fprintf(f, "%s\n", commentList[i]);
12953     }
12954
12955     /* Print result */
12956     if (gameInfo.resultDetails != NULL &&
12957         gameInfo.resultDetails[0] != NULLCHAR) {
12958         fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
12959                 PGNResult(gameInfo.result));
12960     } else {
12961         fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12962     }
12963
12964     fclose(f);
12965     lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12966     return TRUE;
12967 }
12968
12969 /* Save game in old style and close the file */
12970 int
12971 SaveGameOldStyle (FILE *f)
12972 {
12973     int i, offset;
12974     time_t tm;
12975
12976     tm = time((time_t *) NULL);
12977
12978     fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
12979     PrintOpponents(f);
12980
12981     if (backwardMostMove > 0 || startedFromSetupPosition) {
12982         fprintf(f, "\n[--------------\n");
12983         PrintPosition(f, backwardMostMove);
12984         fprintf(f, "--------------]\n");
12985     } else {
12986         fprintf(f, "\n");
12987     }
12988
12989     i = backwardMostMove;
12990     offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12991
12992     while (i < forwardMostMove) {
12993         if (commentList[i] != NULL) {
12994             fprintf(f, "[%s]\n", commentList[i]);
12995         }
12996
12997         if ((i % 2) == 1) {
12998             fprintf(f, "%d. ...  %s\n", (i - offset)/2 + 1, parseList[i]);
12999             i++;
13000         } else {
13001             fprintf(f, "%d. %s  ", (i - offset)/2 + 1, parseList[i]);
13002             i++;
13003             if (commentList[i] != NULL) {
13004                 fprintf(f, "\n");
13005                 continue;
13006             }
13007             if (i >= forwardMostMove) {
13008                 fprintf(f, "\n");
13009                 break;
13010             }
13011             fprintf(f, "%s\n", parseList[i]);
13012             i++;
13013         }
13014     }
13015
13016     if (commentList[i] != NULL) {
13017         fprintf(f, "[%s]\n", commentList[i]);
13018     }
13019
13020     /* This isn't really the old style, but it's close enough */
13021     if (gameInfo.resultDetails != NULL &&
13022         gameInfo.resultDetails[0] != NULLCHAR) {
13023         fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
13024                 gameInfo.resultDetails);
13025     } else {
13026         fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
13027     }
13028
13029     fclose(f);
13030     return TRUE;
13031 }
13032
13033 /* Save the current game to open file f and close the file */
13034 int
13035 SaveGame (FILE *f, int dummy, char *dummy2)
13036 {
13037     if (gameMode == EditPosition) EditPositionDone(TRUE);
13038     lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
13039     if (appData.oldSaveStyle)
13040       return SaveGameOldStyle(f);
13041     else
13042       return SaveGamePGN(f);
13043 }
13044
13045 /* Save the current position to the given file */
13046 int
13047 SavePositionToFile (char *filename)
13048 {
13049     FILE *f;
13050     char buf[MSG_SIZ];
13051
13052     if (strcmp(filename, "-") == 0) {
13053         return SavePosition(stdout, 0, NULL);
13054     } else {
13055         f = fopen(filename, "a");
13056         if (f == NULL) {
13057             snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13058             DisplayError(buf, errno);
13059             return FALSE;
13060         } else {
13061             safeStrCpy(buf, lastMsg, MSG_SIZ);
13062             DisplayMessage(_("Waiting for access to save file"), "");
13063             flock(fileno(f), LOCK_EX); // [HGM] lock
13064             DisplayMessage(_("Saving position"), "");
13065             lseek(fileno(f), 0, SEEK_END);     // better safe than sorry...
13066             SavePosition(f, 0, NULL);
13067             DisplayMessage(buf, "");
13068             return TRUE;
13069         }
13070     }
13071 }
13072
13073 /* Save the current position to the given open file and close the file */
13074 int
13075 SavePosition (FILE *f, int dummy, char *dummy2)
13076 {
13077     time_t tm;
13078     char *fen;
13079
13080     if (gameMode == EditPosition) EditPositionDone(TRUE);
13081     if (appData.oldSaveStyle) {
13082         tm = time((time_t *) NULL);
13083
13084         fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
13085         PrintOpponents(f);
13086         fprintf(f, "[--------------\n");
13087         PrintPosition(f, currentMove);
13088         fprintf(f, "--------------]\n");
13089     } else {
13090         fen = PositionToFEN(currentMove, NULL);
13091         fprintf(f, "%s\n", fen);
13092         free(fen);
13093     }
13094     fclose(f);
13095     return TRUE;
13096 }
13097
13098 void
13099 ReloadCmailMsgEvent (int unregister)
13100 {
13101 #if !WIN32
13102     static char *inFilename = NULL;
13103     static char *outFilename;
13104     int i;
13105     struct stat inbuf, outbuf;
13106     int status;
13107
13108     /* Any registered moves are unregistered if unregister is set, */
13109     /* i.e. invoked by the signal handler */
13110     if (unregister) {
13111         for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13112             cmailMoveRegistered[i] = FALSE;
13113             if (cmailCommentList[i] != NULL) {
13114                 free(cmailCommentList[i]);
13115                 cmailCommentList[i] = NULL;
13116             }
13117         }
13118         nCmailMovesRegistered = 0;
13119     }
13120
13121     for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13122         cmailResult[i] = CMAIL_NOT_RESULT;
13123     }
13124     nCmailResults = 0;
13125
13126     if (inFilename == NULL) {
13127         /* Because the filenames are static they only get malloced once  */
13128         /* and they never get freed                                      */
13129         inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
13130         sprintf(inFilename, "%s.game.in", appData.cmailGameName);
13131
13132         outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
13133         sprintf(outFilename, "%s.out", appData.cmailGameName);
13134     }
13135
13136     status = stat(outFilename, &outbuf);
13137     if (status < 0) {
13138         cmailMailedMove = FALSE;
13139     } else {
13140         status = stat(inFilename, &inbuf);
13141         cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
13142     }
13143
13144     /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
13145        counts the games, notes how each one terminated, etc.
13146
13147        It would be nice to remove this kludge and instead gather all
13148        the information while building the game list.  (And to keep it
13149        in the game list nodes instead of having a bunch of fixed-size
13150        parallel arrays.)  Note this will require getting each game's
13151        termination from the PGN tags, as the game list builder does
13152        not process the game moves.  --mann
13153        */
13154     cmailMsgLoaded = TRUE;
13155     LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
13156
13157     /* Load first game in the file or popup game menu */
13158     LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
13159
13160 #endif /* !WIN32 */
13161     return;
13162 }
13163
13164 int
13165 RegisterMove ()
13166 {
13167     FILE *f;
13168     char string[MSG_SIZ];
13169
13170     if (   cmailMailedMove
13171         || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
13172         return TRUE;            /* Allow free viewing  */
13173     }
13174
13175     /* Unregister move to ensure that we don't leave RegisterMove        */
13176     /* with the move registered when the conditions for registering no   */
13177     /* longer hold                                                       */
13178     if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
13179         cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
13180         nCmailMovesRegistered --;
13181
13182         if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
13183           {
13184               free(cmailCommentList[lastLoadGameNumber - 1]);
13185               cmailCommentList[lastLoadGameNumber - 1] = NULL;
13186           }
13187     }
13188
13189     if (cmailOldMove == -1) {
13190         DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
13191         return FALSE;
13192     }
13193
13194     if (currentMove > cmailOldMove + 1) {
13195         DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
13196         return FALSE;
13197     }
13198
13199     if (currentMove < cmailOldMove) {
13200         DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
13201         return FALSE;
13202     }
13203
13204     if (forwardMostMove > currentMove) {
13205         /* Silently truncate extra moves */
13206         TruncateGame();
13207     }
13208
13209     if (   (currentMove == cmailOldMove + 1)
13210         || (   (currentMove == cmailOldMove)
13211             && (   (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
13212                 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
13213         if (gameInfo.result != GameUnfinished) {
13214             cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
13215         }
13216
13217         if (commentList[currentMove] != NULL) {
13218             cmailCommentList[lastLoadGameNumber - 1]
13219               = StrSave(commentList[currentMove]);
13220         }
13221         safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
13222
13223         if (appData.debugMode)
13224           fprintf(debugFP, "Saving %s for game %d\n",
13225                   cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
13226
13227         snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
13228
13229         f = fopen(string, "w");
13230         if (appData.oldSaveStyle) {
13231             SaveGameOldStyle(f); /* also closes the file */
13232
13233             snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
13234             f = fopen(string, "w");
13235             SavePosition(f, 0, NULL); /* also closes the file */
13236         } else {
13237             fprintf(f, "{--------------\n");
13238             PrintPosition(f, currentMove);
13239             fprintf(f, "--------------}\n\n");
13240
13241             SaveGame(f, 0, NULL); /* also closes the file*/
13242         }
13243
13244         cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
13245         nCmailMovesRegistered ++;
13246     } else if (nCmailGames == 1) {
13247         DisplayError(_("You have not made a move yet"), 0);
13248         return FALSE;
13249     }
13250
13251     return TRUE;
13252 }
13253
13254 void
13255 MailMoveEvent ()
13256 {
13257 #if !WIN32
13258     static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
13259     FILE *commandOutput;
13260     char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
13261     int nBytes = 0;             /*  Suppress warnings on uninitialized variables    */
13262     int nBuffers;
13263     int i;
13264     int archived;
13265     char *arcDir;
13266
13267     if (! cmailMsgLoaded) {
13268         DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
13269         return;
13270     }
13271
13272     if (nCmailGames == nCmailResults) {
13273         DisplayError(_("No unfinished games"), 0);
13274         return;
13275     }
13276
13277 #if CMAIL_PROHIBIT_REMAIL
13278     if (cmailMailedMove) {
13279       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);
13280         DisplayError(msg, 0);
13281         return;
13282     }
13283 #endif
13284
13285     if (! (cmailMailedMove || RegisterMove())) return;
13286
13287     if (   cmailMailedMove
13288         || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
13289       snprintf(string, MSG_SIZ, partCommandString,
13290                appData.debugMode ? " -v" : "", appData.cmailGameName);
13291         commandOutput = popen(string, "r");
13292
13293         if (commandOutput == NULL) {
13294             DisplayError(_("Failed to invoke cmail"), 0);
13295         } else {
13296             for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
13297                 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
13298             }
13299             if (nBuffers > 1) {
13300                 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
13301                 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
13302                 nBytes = MSG_SIZ - 1;
13303             } else {
13304                 (void) memcpy(msg, buffer, nBytes);
13305             }
13306             *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
13307
13308             if(StrStr(msg, "Mailed cmail message to ") != NULL) {
13309                 cmailMailedMove = TRUE; /* Prevent >1 moves    */
13310
13311                 archived = TRUE;
13312                 for (i = 0; i < nCmailGames; i ++) {
13313                     if (cmailResult[i] == CMAIL_NOT_RESULT) {
13314                         archived = FALSE;
13315                     }
13316                 }
13317                 if (   archived
13318                     && (   (arcDir = (char *) getenv("CMAIL_ARCDIR"))
13319                         != NULL)) {
13320                   snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
13321                            arcDir,
13322                            appData.cmailGameName,
13323                            gameInfo.date);
13324                     LoadGameFromFile(buffer, 1, buffer, FALSE);
13325                     cmailMsgLoaded = FALSE;
13326                 }
13327             }
13328
13329             DisplayInformation(msg);
13330             pclose(commandOutput);
13331         }
13332     } else {
13333         if ((*cmailMsg) != '\0') {
13334             DisplayInformation(cmailMsg);
13335         }
13336     }
13337
13338     return;
13339 #endif /* !WIN32 */
13340 }
13341
13342 char *
13343 CmailMsg ()
13344 {
13345 #if WIN32
13346     return NULL;
13347 #else
13348     int  prependComma = 0;
13349     char number[5];
13350     char string[MSG_SIZ];       /* Space for game-list */
13351     int  i;
13352
13353     if (!cmailMsgLoaded) return "";
13354
13355     if (cmailMailedMove) {
13356       snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
13357     } else {
13358         /* Create a list of games left */
13359       snprintf(string, MSG_SIZ, "[");
13360         for (i = 0; i < nCmailGames; i ++) {
13361             if (! (   cmailMoveRegistered[i]
13362                    || (cmailResult[i] == CMAIL_OLD_RESULT))) {
13363                 if (prependComma) {
13364                     snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
13365                 } else {
13366                     snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
13367                     prependComma = 1;
13368                 }
13369
13370                 strcat(string, number);
13371             }
13372         }
13373         strcat(string, "]");
13374
13375         if (nCmailMovesRegistered + nCmailResults == 0) {
13376             switch (nCmailGames) {
13377               case 1:
13378                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
13379                 break;
13380
13381               case 2:
13382                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
13383                 break;
13384
13385               default:
13386                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
13387                          nCmailGames);
13388                 break;
13389             }
13390         } else {
13391             switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
13392               case 1:
13393                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
13394                          string);
13395                 break;
13396
13397               case 0:
13398                 if (nCmailResults == nCmailGames) {
13399                   snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
13400                 } else {
13401                   snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
13402                 }
13403                 break;
13404
13405               default:
13406                 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
13407                          string);
13408             }
13409         }
13410     }
13411     return cmailMsg;
13412 #endif /* WIN32 */
13413 }
13414
13415 void
13416 ResetGameEvent ()
13417 {
13418     if (gameMode == Training)
13419       SetTrainingModeOff();
13420
13421     Reset(TRUE, TRUE);
13422     cmailMsgLoaded = FALSE;
13423     if (appData.icsActive) {
13424       SendToICS(ics_prefix);
13425       SendToICS("refresh\n");
13426     }
13427 }
13428
13429 void
13430 ExitEvent (int status)
13431 {
13432     exiting++;
13433     if (exiting > 2) {
13434       /* Give up on clean exit */
13435       exit(status);
13436     }
13437     if (exiting > 1) {
13438       /* Keep trying for clean exit */
13439       return;
13440     }
13441
13442     if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
13443
13444     if (telnetISR != NULL) {
13445       RemoveInputSource(telnetISR);
13446     }
13447     if (icsPR != NoProc) {
13448       DestroyChildProcess(icsPR, TRUE);
13449     }
13450
13451     /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
13452     GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
13453
13454     /* [HGM] crash: the above GameEnds() is a dud if another one was running */
13455     /* make sure this other one finishes before killing it!                  */
13456     if(endingGame) { int count = 0;
13457         if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
13458         while(endingGame && count++ < 10) DoSleep(1);
13459         if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
13460     }
13461
13462     /* Kill off chess programs */
13463     if (first.pr != NoProc) {
13464         ExitAnalyzeMode();
13465
13466         DoSleep( appData.delayBeforeQuit );
13467         SendToProgram("quit\n", &first);
13468         DoSleep( appData.delayAfterQuit );
13469         DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
13470     }
13471     if (second.pr != NoProc) {
13472         DoSleep( appData.delayBeforeQuit );
13473         SendToProgram("quit\n", &second);
13474         DoSleep( appData.delayAfterQuit );
13475         DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
13476     }
13477     if (first.isr != NULL) {
13478         RemoveInputSource(first.isr);
13479     }
13480     if (second.isr != NULL) {
13481         RemoveInputSource(second.isr);
13482     }
13483
13484     if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
13485     if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
13486
13487     ShutDownFrontEnd();
13488     exit(status);
13489 }
13490
13491 void
13492 PauseEngine (ChessProgramState *cps)
13493 {
13494     SendToProgram("pause\n", cps);
13495     cps->pause = 2;
13496 }
13497
13498 void
13499 UnPauseEngine (ChessProgramState *cps)
13500 {
13501     SendToProgram("resume\n", cps);
13502     cps->pause = 1;
13503 }
13504
13505 void
13506 PauseEvent ()
13507 {
13508     if (appData.debugMode)
13509         fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
13510     if (pausing) {
13511         pausing = FALSE;
13512         ModeHighlight();
13513         if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
13514             StartClocks();
13515             if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
13516                 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
13517                 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
13518             }
13519             if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
13520             HandleMachineMove(stashedInputMove, stalledEngine);
13521             stalledEngine = NULL;
13522             return;
13523         }
13524         if (gameMode == MachinePlaysWhite ||
13525             gameMode == TwoMachinesPlay   ||
13526             gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
13527             if(first.pause)  UnPauseEngine(&first);
13528             else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
13529             if(second.pause) UnPauseEngine(&second);
13530             else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
13531             StartClocks();
13532         } else {
13533             DisplayBothClocks();
13534         }
13535         if (gameMode == PlayFromGameFile) {
13536             if (appData.timeDelay >= 0)
13537                 AutoPlayGameLoop();
13538         } else if (gameMode == IcsExamining && pauseExamInvalid) {
13539             Reset(FALSE, TRUE);
13540             SendToICS(ics_prefix);
13541             SendToICS("refresh\n");
13542         } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
13543             ForwardInner(forwardMostMove);
13544         }
13545         pauseExamInvalid = FALSE;
13546     } else {
13547         switch (gameMode) {
13548           default:
13549             return;
13550           case IcsExamining:
13551             pauseExamForwardMostMove = forwardMostMove;
13552             pauseExamInvalid = FALSE;
13553             /* fall through */
13554           case IcsObserving:
13555           case IcsPlayingWhite:
13556           case IcsPlayingBlack:
13557             pausing = TRUE;
13558             ModeHighlight();
13559             return;
13560           case PlayFromGameFile:
13561             (void) StopLoadGameTimer();
13562             pausing = TRUE;
13563             ModeHighlight();
13564             break;
13565           case BeginningOfGame:
13566             if (appData.icsActive) return;
13567             /* else fall through */
13568           case MachinePlaysWhite:
13569           case MachinePlaysBlack:
13570           case TwoMachinesPlay:
13571             if (forwardMostMove == 0)
13572               return;           /* don't pause if no one has moved */
13573             if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
13574                 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
13575                 if(onMove->pause) {           // thinking engine can be paused
13576                     PauseEngine(onMove);      // do it
13577                     if(onMove->other->pause)  // pondering opponent can always be paused immediately
13578                         PauseEngine(onMove->other);
13579                     else
13580                         SendToProgram("easy\n", onMove->other);
13581                     StopClocks();
13582                 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
13583             } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
13584                 if(first.pause) {
13585                     PauseEngine(&first);
13586                     StopClocks();
13587                 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
13588             } else { // human on move, pause pondering by either method
13589                 if(first.pause)
13590                     PauseEngine(&first);
13591                 else if(appData.ponderNextMove)
13592                     SendToProgram("easy\n", &first);
13593                 StopClocks();
13594             }
13595             // if no immediate pausing is possible, wait for engine to move, and stop clocks then
13596           case AnalyzeMode:
13597             pausing = TRUE;
13598             ModeHighlight();
13599             break;
13600         }
13601     }
13602 }
13603
13604 void
13605 EditCommentEvent ()
13606 {
13607     char title[MSG_SIZ];
13608
13609     if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
13610       safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
13611     } else {
13612       snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
13613                WhiteOnMove(currentMove - 1) ? " " : ".. ",
13614                parseList[currentMove - 1]);
13615     }
13616
13617     EditCommentPopUp(currentMove, title, commentList[currentMove]);
13618 }
13619
13620
13621 void
13622 EditTagsEvent ()
13623 {
13624     char *tags = PGNTags(&gameInfo);
13625     bookUp = FALSE;
13626     EditTagsPopUp(tags, NULL);
13627     free(tags);
13628 }
13629
13630 void
13631 ToggleSecond ()
13632 {
13633   if(second.analyzing) {
13634     SendToProgram("exit\n", &second);
13635     second.analyzing = FALSE;
13636   } else {
13637     if (second.pr == NoProc) StartChessProgram(&second);
13638     InitChessProgram(&second, FALSE);
13639     FeedMovesToProgram(&second, currentMove);
13640
13641     SendToProgram("analyze\n", &second);
13642     second.analyzing = TRUE;
13643   }
13644 }
13645
13646 /* Toggle ShowThinking */
13647 void
13648 ToggleShowThinking()
13649 {
13650   appData.showThinking = !appData.showThinking;
13651   ShowThinkingEvent();
13652 }
13653
13654 int
13655 AnalyzeModeEvent ()
13656 {
13657     char buf[MSG_SIZ];
13658
13659     if (!first.analysisSupport) {
13660       snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
13661       DisplayError(buf, 0);
13662       return 0;
13663     }
13664     /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
13665     if (appData.icsActive) {
13666         if (gameMode != IcsObserving) {
13667           snprintf(buf, MSG_SIZ, _("You are not observing a game"));
13668             DisplayError(buf, 0);
13669             /* secure check */
13670             if (appData.icsEngineAnalyze) {
13671                 if (appData.debugMode)
13672                     fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
13673                 ExitAnalyzeMode();
13674                 ModeHighlight();
13675             }
13676             return 0;
13677         }
13678         /* if enable, user wants to disable icsEngineAnalyze */
13679         if (appData.icsEngineAnalyze) {
13680                 ExitAnalyzeMode();
13681                 ModeHighlight();
13682                 return 0;
13683         }
13684         appData.icsEngineAnalyze = TRUE;
13685         if (appData.debugMode)
13686             fprintf(debugFP, "ICS engine analyze starting... \n");
13687     }
13688
13689     if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
13690     if (appData.noChessProgram || gameMode == AnalyzeMode)
13691       return 0;
13692
13693     if (gameMode != AnalyzeFile) {
13694         if (!appData.icsEngineAnalyze) {
13695                EditGameEvent();
13696                if (gameMode != EditGame) return 0;
13697         }
13698         if (!appData.showThinking) ToggleShowThinking();
13699         ResurrectChessProgram();
13700         SendToProgram("analyze\n", &first);
13701         first.analyzing = TRUE;
13702         /*first.maybeThinking = TRUE;*/
13703         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13704         EngineOutputPopUp();
13705     }
13706     if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
13707     pausing = FALSE;
13708     ModeHighlight();
13709     SetGameInfo();
13710
13711     StartAnalysisClock();
13712     GetTimeMark(&lastNodeCountTime);
13713     lastNodeCount = 0;
13714     return 1;
13715 }
13716
13717 void
13718 AnalyzeFileEvent ()
13719 {
13720     if (appData.noChessProgram || gameMode == AnalyzeFile)
13721       return;
13722
13723     if (!first.analysisSupport) {
13724       char buf[MSG_SIZ];
13725       snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
13726       DisplayError(buf, 0);
13727       return;
13728     }
13729
13730     if (gameMode != AnalyzeMode) {
13731         keepInfo = 1; // mere annotating should not alter PGN tags
13732         EditGameEvent();
13733         keepInfo = 0;
13734         if (gameMode != EditGame) return;
13735         if (!appData.showThinking) ToggleShowThinking();
13736         ResurrectChessProgram();
13737         SendToProgram("analyze\n", &first);
13738         first.analyzing = TRUE;
13739         /*first.maybeThinking = TRUE;*/
13740         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13741         EngineOutputPopUp();
13742     }
13743     gameMode = AnalyzeFile;
13744     pausing = FALSE;
13745     ModeHighlight();
13746
13747     StartAnalysisClock();
13748     GetTimeMark(&lastNodeCountTime);
13749     lastNodeCount = 0;
13750     if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
13751     AnalysisPeriodicEvent(1);
13752 }
13753
13754 void
13755 MachineWhiteEvent ()
13756 {
13757     char buf[MSG_SIZ];
13758     char *bookHit = NULL;
13759
13760     if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
13761       return;
13762
13763
13764     if (gameMode == PlayFromGameFile ||
13765         gameMode == TwoMachinesPlay  ||
13766         gameMode == Training         ||
13767         gameMode == AnalyzeMode      ||
13768         gameMode == EndOfGame)
13769         EditGameEvent();
13770
13771     if (gameMode == EditPosition)
13772         EditPositionDone(TRUE);
13773
13774     if (!WhiteOnMove(currentMove)) {
13775         DisplayError(_("It is not White's turn"), 0);
13776         return;
13777     }
13778
13779     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13780       ExitAnalyzeMode();
13781
13782     if (gameMode == EditGame || gameMode == AnalyzeMode ||
13783         gameMode == AnalyzeFile)
13784         TruncateGame();
13785
13786     ResurrectChessProgram();    /* in case it isn't running */
13787     if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
13788         gameMode = MachinePlaysWhite;
13789         ResetClocks();
13790     } else
13791     gameMode = MachinePlaysWhite;
13792     pausing = FALSE;
13793     ModeHighlight();
13794     SetGameInfo();
13795     snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13796     DisplayTitle(buf);
13797     if (first.sendName) {
13798       snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
13799       SendToProgram(buf, &first);
13800     }
13801     if (first.sendTime) {
13802       if (first.useColors) {
13803         SendToProgram("black\n", &first); /*gnu kludge*/
13804       }
13805       SendTimeRemaining(&first, TRUE);
13806     }
13807     if (first.useColors) {
13808       SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
13809     }
13810     bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13811     SetMachineThinkingEnables();
13812     first.maybeThinking = TRUE;
13813     StartClocks();
13814     firstMove = FALSE;
13815
13816     if (appData.autoFlipView && !flipView) {
13817       flipView = !flipView;
13818       DrawPosition(FALSE, NULL);
13819       DisplayBothClocks();       // [HGM] logo: clocks might have to be exchanged;
13820     }
13821
13822     if(bookHit) { // [HGM] book: simulate book reply
13823         static char bookMove[MSG_SIZ]; // a bit generous?
13824
13825         programStats.nodes = programStats.depth = programStats.time =
13826         programStats.score = programStats.got_only_move = 0;
13827         sprintf(programStats.movelist, "%s (xbook)", bookHit);
13828
13829         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13830         strcat(bookMove, bookHit);
13831         HandleMachineMove(bookMove, &first);
13832     }
13833 }
13834
13835 void
13836 MachineBlackEvent ()
13837 {
13838   char buf[MSG_SIZ];
13839   char *bookHit = NULL;
13840
13841     if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
13842         return;
13843
13844
13845     if (gameMode == PlayFromGameFile ||
13846         gameMode == TwoMachinesPlay  ||
13847         gameMode == Training         ||
13848         gameMode == AnalyzeMode      ||
13849         gameMode == EndOfGame)
13850         EditGameEvent();
13851
13852     if (gameMode == EditPosition)
13853         EditPositionDone(TRUE);
13854
13855     if (WhiteOnMove(currentMove)) {
13856         DisplayError(_("It is not Black's turn"), 0);
13857         return;
13858     }
13859
13860     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13861       ExitAnalyzeMode();
13862
13863     if (gameMode == EditGame || gameMode == AnalyzeMode ||
13864         gameMode == AnalyzeFile)
13865         TruncateGame();
13866
13867     ResurrectChessProgram();    /* in case it isn't running */
13868     gameMode = MachinePlaysBlack;
13869     pausing = FALSE;
13870     ModeHighlight();
13871     SetGameInfo();
13872     snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13873     DisplayTitle(buf);
13874     if (first.sendName) {
13875       snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
13876       SendToProgram(buf, &first);
13877     }
13878     if (first.sendTime) {
13879       if (first.useColors) {
13880         SendToProgram("white\n", &first); /*gnu kludge*/
13881       }
13882       SendTimeRemaining(&first, FALSE);
13883     }
13884     if (first.useColors) {
13885       SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
13886     }
13887     bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13888     SetMachineThinkingEnables();
13889     first.maybeThinking = TRUE;
13890     StartClocks();
13891
13892     if (appData.autoFlipView && flipView) {
13893       flipView = !flipView;
13894       DrawPosition(FALSE, NULL);
13895       DisplayBothClocks();       // [HGM] logo: clocks might have to be exchanged;
13896     }
13897     if(bookHit) { // [HGM] book: simulate book reply
13898         static char bookMove[MSG_SIZ]; // a bit generous?
13899
13900         programStats.nodes = programStats.depth = programStats.time =
13901         programStats.score = programStats.got_only_move = 0;
13902         sprintf(programStats.movelist, "%s (xbook)", bookHit);
13903
13904         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13905         strcat(bookMove, bookHit);
13906         HandleMachineMove(bookMove, &first);
13907     }
13908 }
13909
13910
13911 void
13912 DisplayTwoMachinesTitle ()
13913 {
13914     char buf[MSG_SIZ];
13915     if (appData.matchGames > 0) {
13916         if(appData.tourneyFile[0]) {
13917           snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
13918                    gameInfo.white, _("vs."), gameInfo.black,
13919                    nextGame+1, appData.matchGames+1,
13920                    appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
13921         } else
13922         if (first.twoMachinesColor[0] == 'w') {
13923           snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13924                    gameInfo.white, _("vs."),  gameInfo.black,
13925                    first.matchWins, second.matchWins,
13926                    matchGame - 1 - (first.matchWins + second.matchWins));
13927         } else {
13928           snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13929                    gameInfo.white, _("vs."), gameInfo.black,
13930                    second.matchWins, first.matchWins,
13931                    matchGame - 1 - (first.matchWins + second.matchWins));
13932         }
13933     } else {
13934       snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13935     }
13936     DisplayTitle(buf);
13937 }
13938
13939 void
13940 SettingsMenuIfReady ()
13941 {
13942   if (second.lastPing != second.lastPong) {
13943     DisplayMessage("", _("Waiting for second chess program"));
13944     ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
13945     return;
13946   }
13947   ThawUI();
13948   DisplayMessage("", "");
13949   SettingsPopUp(&second);
13950 }
13951
13952 int
13953 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
13954 {
13955     char buf[MSG_SIZ];
13956     if (cps->pr == NoProc) {
13957         StartChessProgram(cps);
13958         if (cps->protocolVersion == 1) {
13959           retry();
13960           ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
13961         } else {
13962           /* kludge: allow timeout for initial "feature" command */
13963           if(retry != TwoMachinesEventIfReady) FreezeUI();
13964           snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
13965           DisplayMessage("", buf);
13966           ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
13967         }
13968         return 1;
13969     }
13970     return 0;
13971 }
13972
13973 void
13974 TwoMachinesEvent P((void))
13975 {
13976     int i;
13977     char buf[MSG_SIZ];
13978     ChessProgramState *onmove;
13979     char *bookHit = NULL;
13980     static int stalling = 0;
13981     TimeMark now;
13982     long wait;
13983
13984     if (appData.noChessProgram) return;
13985
13986     switch (gameMode) {
13987       case TwoMachinesPlay:
13988         return;
13989       case MachinePlaysWhite:
13990       case MachinePlaysBlack:
13991         if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13992             DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13993             return;
13994         }
13995         /* fall through */
13996       case BeginningOfGame:
13997       case PlayFromGameFile:
13998       case EndOfGame:
13999         EditGameEvent();
14000         if (gameMode != EditGame) return;
14001         break;
14002       case EditPosition:
14003         EditPositionDone(TRUE);
14004         break;
14005       case AnalyzeMode:
14006       case AnalyzeFile:
14007         ExitAnalyzeMode();
14008         break;
14009       case EditGame:
14010       default:
14011         break;
14012     }
14013
14014 //    forwardMostMove = currentMove;
14015     TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
14016     startingEngine = TRUE;
14017
14018     if(!ResurrectChessProgram()) return;   /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
14019
14020     if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
14021     if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
14022       ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14023       return;
14024     }
14025     if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
14026
14027     if(second.protocolVersion >= 2 && !strstr(second.variants, VariantName(gameInfo.variant))) {
14028         startingEngine = FALSE;
14029         DisplayError("second engine does not play this", 0);
14030         return;
14031     }
14032
14033     if(!stalling) {
14034       InitChessProgram(&second, FALSE); // unbalances ping of second engine
14035       SendToProgram("force\n", &second);
14036       stalling = 1;
14037       ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14038       return;
14039     }
14040     GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
14041     if(appData.matchPause>10000 || appData.matchPause<10)
14042                 appData.matchPause = 10000; /* [HGM] make pause adjustable */
14043     wait = SubtractTimeMarks(&now, &pauseStart);
14044     if(wait < appData.matchPause) {
14045         ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
14046         return;
14047     }
14048     // we are now committed to starting the game
14049     stalling = 0;
14050     DisplayMessage("", "");
14051     if (startedFromSetupPosition) {
14052         SendBoard(&second, backwardMostMove);
14053     if (appData.debugMode) {
14054         fprintf(debugFP, "Two Machines\n");
14055     }
14056     }
14057     for (i = backwardMostMove; i < forwardMostMove; i++) {
14058         SendMoveToProgram(i, &second);
14059     }
14060
14061     gameMode = TwoMachinesPlay;
14062     pausing = startingEngine = FALSE;
14063     ModeHighlight(); // [HGM] logo: this triggers display update of logos
14064     SetGameInfo();
14065     DisplayTwoMachinesTitle();
14066     firstMove = TRUE;
14067     if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
14068         onmove = &first;
14069     } else {
14070         onmove = &second;
14071     }
14072     if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
14073     SendToProgram(first.computerString, &first);
14074     if (first.sendName) {
14075       snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
14076       SendToProgram(buf, &first);
14077     }
14078     SendToProgram(second.computerString, &second);
14079     if (second.sendName) {
14080       snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
14081       SendToProgram(buf, &second);
14082     }
14083
14084     ResetClocks();
14085     if (!first.sendTime || !second.sendTime) {
14086         timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14087         timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14088     }
14089     if (onmove->sendTime) {
14090       if (onmove->useColors) {
14091         SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
14092       }
14093       SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
14094     }
14095     if (onmove->useColors) {
14096       SendToProgram(onmove->twoMachinesColor, onmove);
14097     }
14098     bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
14099 //    SendToProgram("go\n", onmove);
14100     onmove->maybeThinking = TRUE;
14101     SetMachineThinkingEnables();
14102
14103     StartClocks();
14104
14105     if(bookHit) { // [HGM] book: simulate book reply
14106         static char bookMove[MSG_SIZ]; // a bit generous?
14107
14108         programStats.nodes = programStats.depth = programStats.time =
14109         programStats.score = programStats.got_only_move = 0;
14110         sprintf(programStats.movelist, "%s (xbook)", bookHit);
14111
14112         safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14113         strcat(bookMove, bookHit);
14114         savedMessage = bookMove; // args for deferred call
14115         savedState = onmove;
14116         ScheduleDelayedEvent(DeferredBookMove, 1);
14117     }
14118 }
14119
14120 void
14121 TrainingEvent ()
14122 {
14123     if (gameMode == Training) {
14124       SetTrainingModeOff();
14125       gameMode = PlayFromGameFile;
14126       DisplayMessage("", _("Training mode off"));
14127     } else {
14128       gameMode = Training;
14129       animateTraining = appData.animate;
14130
14131       /* make sure we are not already at the end of the game */
14132       if (currentMove < forwardMostMove) {
14133         SetTrainingModeOn();
14134         DisplayMessage("", _("Training mode on"));
14135       } else {
14136         gameMode = PlayFromGameFile;
14137         DisplayError(_("Already at end of game"), 0);
14138       }
14139     }
14140     ModeHighlight();
14141 }
14142
14143 void
14144 IcsClientEvent ()
14145 {
14146     if (!appData.icsActive) return;
14147     switch (gameMode) {
14148       case IcsPlayingWhite:
14149       case IcsPlayingBlack:
14150       case IcsObserving:
14151       case IcsIdle:
14152       case BeginningOfGame:
14153       case IcsExamining:
14154         return;
14155
14156       case EditGame:
14157         break;
14158
14159       case EditPosition:
14160         EditPositionDone(TRUE);
14161         break;
14162
14163       case AnalyzeMode:
14164       case AnalyzeFile:
14165         ExitAnalyzeMode();
14166         break;
14167
14168       default:
14169         EditGameEvent();
14170         break;
14171     }
14172
14173     gameMode = IcsIdle;
14174     ModeHighlight();
14175     return;
14176 }
14177
14178 void
14179 EditGameEvent ()
14180 {
14181     int i;
14182
14183     switch (gameMode) {
14184       case Training:
14185         SetTrainingModeOff();
14186         break;
14187       case MachinePlaysWhite:
14188       case MachinePlaysBlack:
14189       case BeginningOfGame:
14190         SendToProgram("force\n", &first);
14191         SetUserThinkingEnables();
14192         break;
14193       case PlayFromGameFile:
14194         (void) StopLoadGameTimer();
14195         if (gameFileFP != NULL) {
14196             gameFileFP = NULL;
14197         }
14198         break;
14199       case EditPosition:
14200         EditPositionDone(TRUE);
14201         break;
14202       case AnalyzeMode:
14203       case AnalyzeFile:
14204         ExitAnalyzeMode();
14205         SendToProgram("force\n", &first);
14206         break;
14207       case TwoMachinesPlay:
14208         GameEnds(EndOfFile, NULL, GE_PLAYER);
14209         ResurrectChessProgram();
14210         SetUserThinkingEnables();
14211         break;
14212       case EndOfGame:
14213         ResurrectChessProgram();
14214         break;
14215       case IcsPlayingBlack:
14216       case IcsPlayingWhite:
14217         DisplayError(_("Warning: You are still playing a game"), 0);
14218         break;
14219       case IcsObserving:
14220         DisplayError(_("Warning: You are still observing a game"), 0);
14221         break;
14222       case IcsExamining:
14223         DisplayError(_("Warning: You are still examining a game"), 0);
14224         break;
14225       case IcsIdle:
14226         break;
14227       case EditGame:
14228       default:
14229         return;
14230     }
14231
14232     pausing = FALSE;
14233     StopClocks();
14234     first.offeredDraw = second.offeredDraw = 0;
14235
14236     if (gameMode == PlayFromGameFile) {
14237         whiteTimeRemaining = timeRemaining[0][currentMove];
14238         blackTimeRemaining = timeRemaining[1][currentMove];
14239         DisplayTitle("");
14240     }
14241
14242     if (gameMode == MachinePlaysWhite ||
14243         gameMode == MachinePlaysBlack ||
14244         gameMode == TwoMachinesPlay ||
14245         gameMode == EndOfGame) {
14246         i = forwardMostMove;
14247         while (i > currentMove) {
14248             SendToProgram("undo\n", &first);
14249             i--;
14250         }
14251         if(!adjustedClock) {
14252         whiteTimeRemaining = timeRemaining[0][currentMove];
14253         blackTimeRemaining = timeRemaining[1][currentMove];
14254         DisplayBothClocks();
14255         }
14256         if (whiteFlag || blackFlag) {
14257             whiteFlag = blackFlag = 0;
14258         }
14259         DisplayTitle("");
14260     }
14261
14262     gameMode = EditGame;
14263     ModeHighlight();
14264     SetGameInfo();
14265 }
14266
14267
14268 void
14269 EditPositionEvent ()
14270 {
14271     if (gameMode == EditPosition) {
14272         EditGameEvent();
14273         return;
14274     }
14275
14276     EditGameEvent();
14277     if (gameMode != EditGame) return;
14278
14279     gameMode = EditPosition;
14280     ModeHighlight();
14281     SetGameInfo();
14282     if (currentMove > 0)
14283       CopyBoard(boards[0], boards[currentMove]);
14284
14285     blackPlaysFirst = !WhiteOnMove(currentMove);
14286     ResetClocks();
14287     currentMove = forwardMostMove = backwardMostMove = 0;
14288     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14289     DisplayMove(-1);
14290     if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
14291 }
14292
14293 void
14294 ExitAnalyzeMode ()
14295 {
14296     /* [DM] icsEngineAnalyze - possible call from other functions */
14297     if (appData.icsEngineAnalyze) {
14298         appData.icsEngineAnalyze = FALSE;
14299
14300         DisplayMessage("",_("Close ICS engine analyze..."));
14301     }
14302     if (first.analysisSupport && first.analyzing) {
14303       SendToBoth("exit\n");
14304       first.analyzing = second.analyzing = FALSE;
14305     }
14306     thinkOutput[0] = NULLCHAR;
14307 }
14308
14309 void
14310 EditPositionDone (Boolean fakeRights)
14311 {
14312     int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
14313
14314     startedFromSetupPosition = TRUE;
14315     InitChessProgram(&first, FALSE);
14316     if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
14317       boards[0][EP_STATUS] = EP_NONE;
14318       boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
14319       if(boards[0][0][BOARD_WIDTH>>1] == king) {
14320         boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? BOARD_LEFT : NoRights;
14321         boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
14322       } else boards[0][CASTLING][2] = NoRights;
14323       if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
14324         boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? BOARD_LEFT : NoRights;
14325         boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
14326       } else boards[0][CASTLING][5] = NoRights;
14327       if(gameInfo.variant == VariantSChess) {
14328         int i;
14329         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // pieces in their original position are assumed virgin
14330           boards[0][VIRGIN][i] = 0;
14331           if(boards[0][0][i]              == FIDEArray[0][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_W;
14332           if(boards[0][BOARD_HEIGHT-1][i] == FIDEArray[1][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_B;
14333         }
14334       }
14335     }
14336     SendToProgram("force\n", &first);
14337     if (blackPlaysFirst) {
14338         safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
14339         safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
14340         currentMove = forwardMostMove = backwardMostMove = 1;
14341         CopyBoard(boards[1], boards[0]);
14342     } else {
14343         currentMove = forwardMostMove = backwardMostMove = 0;
14344     }
14345     SendBoard(&first, forwardMostMove);
14346     if (appData.debugMode) {
14347         fprintf(debugFP, "EditPosDone\n");
14348     }
14349     DisplayTitle("");
14350     DisplayMessage("", "");
14351     timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14352     timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14353     gameMode = EditGame;
14354     ModeHighlight();
14355     HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14356     ClearHighlights(); /* [AS] */
14357 }
14358
14359 /* Pause for `ms' milliseconds */
14360 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14361 void
14362 TimeDelay (long ms)
14363 {
14364     TimeMark m1, m2;
14365
14366     GetTimeMark(&m1);
14367     do {
14368         GetTimeMark(&m2);
14369     } while (SubtractTimeMarks(&m2, &m1) < ms);
14370 }
14371
14372 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14373 void
14374 SendMultiLineToICS (char *buf)
14375 {
14376     char temp[MSG_SIZ+1], *p;
14377     int len;
14378
14379     len = strlen(buf);
14380     if (len > MSG_SIZ)
14381       len = MSG_SIZ;
14382
14383     strncpy(temp, buf, len);
14384     temp[len] = 0;
14385
14386     p = temp;
14387     while (*p) {
14388         if (*p == '\n' || *p == '\r')
14389           *p = ' ';
14390         ++p;
14391     }
14392
14393     strcat(temp, "\n");
14394     SendToICS(temp);
14395     SendToPlayer(temp, strlen(temp));
14396 }
14397
14398 void
14399 SetWhiteToPlayEvent ()
14400 {
14401     if (gameMode == EditPosition) {
14402         blackPlaysFirst = FALSE;
14403         DisplayBothClocks();    /* works because currentMove is 0 */
14404     } else if (gameMode == IcsExamining) {
14405         SendToICS(ics_prefix);
14406         SendToICS("tomove white\n");
14407     }
14408 }
14409
14410 void
14411 SetBlackToPlayEvent ()
14412 {
14413     if (gameMode == EditPosition) {
14414         blackPlaysFirst = TRUE;
14415         currentMove = 1;        /* kludge */
14416         DisplayBothClocks();
14417         currentMove = 0;
14418     } else if (gameMode == IcsExamining) {
14419         SendToICS(ics_prefix);
14420         SendToICS("tomove black\n");
14421     }
14422 }
14423
14424 void
14425 EditPositionMenuEvent (ChessSquare selection, int x, int y)
14426 {
14427     char buf[MSG_SIZ];
14428     ChessSquare piece = boards[0][y][x];
14429
14430     if (gameMode != EditPosition && gameMode != IcsExamining) return;
14431
14432     switch (selection) {
14433       case ClearBoard:
14434         if (gameMode == IcsExamining && ics_type == ICS_FICS) {
14435             SendToICS(ics_prefix);
14436             SendToICS("bsetup clear\n");
14437         } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
14438             SendToICS(ics_prefix);
14439             SendToICS("clearboard\n");
14440         } else {
14441             for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
14442                 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
14443                 for (y = 0; y < BOARD_HEIGHT; y++) {
14444                     if (gameMode == IcsExamining) {
14445                         if (boards[currentMove][y][x] != EmptySquare) {
14446                           snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
14447                                     AAA + x, ONE + y);
14448                             SendToICS(buf);
14449                         }
14450                     } else {
14451                         boards[0][y][x] = p;
14452                     }
14453                 }
14454             }
14455         }
14456         if (gameMode == EditPosition) {
14457             DrawPosition(FALSE, boards[0]);
14458         }
14459         break;
14460
14461       case WhitePlay:
14462         SetWhiteToPlayEvent();
14463         break;
14464
14465       case BlackPlay:
14466         SetBlackToPlayEvent();
14467         break;
14468
14469       case EmptySquare:
14470         if (gameMode == IcsExamining) {
14471             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
14472             snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
14473             SendToICS(buf);
14474         } else {
14475             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
14476                 if(x == BOARD_LEFT-2) {
14477                     if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
14478                     boards[0][y][1] = 0;
14479                 } else
14480                 if(x == BOARD_RGHT+1) {
14481                     if(y >= gameInfo.holdingsSize) break;
14482                     boards[0][y][BOARD_WIDTH-2] = 0;
14483                 } else break;
14484             }
14485             boards[0][y][x] = EmptySquare;
14486             DrawPosition(FALSE, boards[0]);
14487         }
14488         break;
14489
14490       case PromotePiece:
14491         if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
14492            piece >= (int)BlackPawn && piece < (int)BlackMan   ) {
14493             selection = (ChessSquare) (PROMOTED piece);
14494         } else if(piece == EmptySquare) selection = WhiteSilver;
14495         else selection = (ChessSquare)((int)piece - 1);
14496         goto defaultlabel;
14497
14498       case DemotePiece:
14499         if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
14500            piece > (int)BlackMan && piece <= (int)BlackKing   ) {
14501             selection = (ChessSquare) (DEMOTED piece);
14502         } else if(piece == EmptySquare) selection = BlackSilver;
14503         else selection = (ChessSquare)((int)piece + 1);
14504         goto defaultlabel;
14505
14506       case WhiteQueen:
14507       case BlackQueen:
14508         if(gameInfo.variant == VariantShatranj ||
14509            gameInfo.variant == VariantXiangqi  ||
14510            gameInfo.variant == VariantCourier  ||
14511            gameInfo.variant == VariantMakruk     )
14512             selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
14513         goto defaultlabel;
14514
14515       case WhiteKing:
14516       case BlackKing:
14517         if(gameInfo.variant == VariantXiangqi)
14518             selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
14519         if(gameInfo.variant == VariantKnightmate)
14520             selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
14521       default:
14522         defaultlabel:
14523         if (gameMode == IcsExamining) {
14524             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
14525             snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
14526                      PieceToChar(selection), AAA + x, ONE + y);
14527             SendToICS(buf);
14528         } else {
14529             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
14530                 int n;
14531                 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
14532                     n = PieceToNumber(selection - BlackPawn);
14533                     if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
14534                     boards[0][BOARD_HEIGHT-1-n][0] = selection;
14535                     boards[0][BOARD_HEIGHT-1-n][1]++;
14536                 } else
14537                 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
14538                     n = PieceToNumber(selection);
14539                     if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
14540                     boards[0][n][BOARD_WIDTH-1] = selection;
14541                     boards[0][n][BOARD_WIDTH-2]++;
14542                 }
14543             } else
14544             boards[0][y][x] = selection;
14545             DrawPosition(TRUE, boards[0]);
14546             ClearHighlights();
14547             fromX = fromY = -1;
14548         }
14549         break;
14550     }
14551 }
14552
14553
14554 void
14555 DropMenuEvent (ChessSquare selection, int x, int y)
14556 {
14557     ChessMove moveType;
14558
14559     switch (gameMode) {
14560       case IcsPlayingWhite:
14561       case MachinePlaysBlack:
14562         if (!WhiteOnMove(currentMove)) {
14563             DisplayMoveError(_("It is Black's turn"));
14564             return;
14565         }
14566         moveType = WhiteDrop;
14567         break;
14568       case IcsPlayingBlack:
14569       case MachinePlaysWhite:
14570         if (WhiteOnMove(currentMove)) {
14571             DisplayMoveError(_("It is White's turn"));
14572             return;
14573         }
14574         moveType = BlackDrop;
14575         break;
14576       case EditGame:
14577         moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
14578         break;
14579       default:
14580         return;
14581     }
14582
14583     if (moveType == BlackDrop && selection < BlackPawn) {
14584       selection = (ChessSquare) ((int) selection
14585                                  + (int) BlackPawn - (int) WhitePawn);
14586     }
14587     if (boards[currentMove][y][x] != EmptySquare) {
14588         DisplayMoveError(_("That square is occupied"));
14589         return;
14590     }
14591
14592     FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
14593 }
14594
14595 void
14596 AcceptEvent ()
14597 {
14598     /* Accept a pending offer of any kind from opponent */
14599
14600     if (appData.icsActive) {
14601         SendToICS(ics_prefix);
14602         SendToICS("accept\n");
14603     } else if (cmailMsgLoaded) {
14604         if (currentMove == cmailOldMove &&
14605             commentList[cmailOldMove] != NULL &&
14606             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14607                    "Black offers a draw" : "White offers a draw")) {
14608             TruncateGame();
14609             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14610             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14611         } else {
14612             DisplayError(_("There is no pending offer on this move"), 0);
14613             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14614         }
14615     } else {
14616         /* Not used for offers from chess program */
14617     }
14618 }
14619
14620 void
14621 DeclineEvent ()
14622 {
14623     /* Decline a pending offer of any kind from opponent */
14624
14625     if (appData.icsActive) {
14626         SendToICS(ics_prefix);
14627         SendToICS("decline\n");
14628     } else if (cmailMsgLoaded) {
14629         if (currentMove == cmailOldMove &&
14630             commentList[cmailOldMove] != NULL &&
14631             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14632                    "Black offers a draw" : "White offers a draw")) {
14633 #ifdef NOTDEF
14634             AppendComment(cmailOldMove, "Draw declined", TRUE);
14635             DisplayComment(cmailOldMove - 1, "Draw declined");
14636 #endif /*NOTDEF*/
14637         } else {
14638             DisplayError(_("There is no pending offer on this move"), 0);
14639         }
14640     } else {
14641         /* Not used for offers from chess program */
14642     }
14643 }
14644
14645 void
14646 RematchEvent ()
14647 {
14648     /* Issue ICS rematch command */
14649     if (appData.icsActive) {
14650         SendToICS(ics_prefix);
14651         SendToICS("rematch\n");
14652     }
14653 }
14654
14655 void
14656 CallFlagEvent ()
14657 {
14658     /* Call your opponent's flag (claim a win on time) */
14659     if (appData.icsActive) {
14660         SendToICS(ics_prefix);
14661         SendToICS("flag\n");
14662     } else {
14663         switch (gameMode) {
14664           default:
14665             return;
14666           case MachinePlaysWhite:
14667             if (whiteFlag) {
14668                 if (blackFlag)
14669                   GameEnds(GameIsDrawn, "Both players ran out of time",
14670                            GE_PLAYER);
14671                 else
14672                   GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
14673             } else {
14674                 DisplayError(_("Your opponent is not out of time"), 0);
14675             }
14676             break;
14677           case MachinePlaysBlack:
14678             if (blackFlag) {
14679                 if (whiteFlag)
14680                   GameEnds(GameIsDrawn, "Both players ran out of time",
14681                            GE_PLAYER);
14682                 else
14683                   GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
14684             } else {
14685                 DisplayError(_("Your opponent is not out of time"), 0);
14686             }
14687             break;
14688         }
14689     }
14690 }
14691
14692 void
14693 ClockClick (int which)
14694 {       // [HGM] code moved to back-end from winboard.c
14695         if(which) { // black clock
14696           if (gameMode == EditPosition || gameMode == IcsExamining) {
14697             if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14698             SetBlackToPlayEvent();
14699           } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !blackFlag && WhiteOnMove(currentMove)) {
14700           UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
14701           } else if (shiftKey) {
14702             AdjustClock(which, -1);
14703           } else if (gameMode == IcsPlayingWhite ||
14704                      gameMode == MachinePlaysBlack) {
14705             CallFlagEvent();
14706           }
14707         } else { // white clock
14708           if (gameMode == EditPosition || gameMode == IcsExamining) {
14709             if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14710             SetWhiteToPlayEvent();
14711           } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !whiteFlag && !WhiteOnMove(currentMove)) {
14712           UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
14713           } else if (shiftKey) {
14714             AdjustClock(which, -1);
14715           } else if (gameMode == IcsPlayingBlack ||
14716                    gameMode == MachinePlaysWhite) {
14717             CallFlagEvent();
14718           }
14719         }
14720 }
14721
14722 void
14723 DrawEvent ()
14724 {
14725     /* Offer draw or accept pending draw offer from opponent */
14726
14727     if (appData.icsActive) {
14728         /* Note: tournament rules require draw offers to be
14729            made after you make your move but before you punch
14730            your clock.  Currently ICS doesn't let you do that;
14731            instead, you immediately punch your clock after making
14732            a move, but you can offer a draw at any time. */
14733
14734         SendToICS(ics_prefix);
14735         SendToICS("draw\n");
14736         userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
14737     } else if (cmailMsgLoaded) {
14738         if (currentMove == cmailOldMove &&
14739             commentList[cmailOldMove] != NULL &&
14740             StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14741                    "Black offers a draw" : "White offers a draw")) {
14742             GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14743             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14744         } else if (currentMove == cmailOldMove + 1) {
14745             char *offer = WhiteOnMove(cmailOldMove) ?
14746               "White offers a draw" : "Black offers a draw";
14747             AppendComment(currentMove, offer, TRUE);
14748             DisplayComment(currentMove - 1, offer);
14749             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
14750         } else {
14751             DisplayError(_("You must make your move before offering a draw"), 0);
14752             cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14753         }
14754     } else if (first.offeredDraw) {
14755         GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
14756     } else {
14757         if (first.sendDrawOffers) {
14758             SendToProgram("draw\n", &first);
14759             userOfferedDraw = TRUE;
14760         }
14761     }
14762 }
14763
14764 void
14765 AdjournEvent ()
14766 {
14767     /* Offer Adjourn or accept pending Adjourn offer from opponent */
14768
14769     if (appData.icsActive) {
14770         SendToICS(ics_prefix);
14771         SendToICS("adjourn\n");
14772     } else {
14773         /* Currently GNU Chess doesn't offer or accept Adjourns */
14774     }
14775 }
14776
14777
14778 void
14779 AbortEvent ()
14780 {
14781     /* Offer Abort or accept pending Abort offer from opponent */
14782
14783     if (appData.icsActive) {
14784         SendToICS(ics_prefix);
14785         SendToICS("abort\n");
14786     } else {
14787         GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
14788     }
14789 }
14790
14791 void
14792 ResignEvent ()
14793 {
14794     /* Resign.  You can do this even if it's not your turn. */
14795
14796     if (appData.icsActive) {
14797         SendToICS(ics_prefix);
14798         SendToICS("resign\n");
14799     } else {
14800         switch (gameMode) {
14801           case MachinePlaysWhite:
14802             GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14803             break;
14804           case MachinePlaysBlack:
14805             GameEnds(BlackWins, "White resigns", GE_PLAYER);
14806             break;
14807           case EditGame:
14808             if (cmailMsgLoaded) {
14809                 TruncateGame();
14810                 if (WhiteOnMove(cmailOldMove)) {
14811                     GameEnds(BlackWins, "White resigns", GE_PLAYER);
14812                 } else {
14813                     GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14814                 }
14815                 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
14816             }
14817             break;
14818           default:
14819             break;
14820         }
14821     }
14822 }
14823
14824
14825 void
14826 StopObservingEvent ()
14827 {
14828     /* Stop observing current games */
14829     SendToICS(ics_prefix);
14830     SendToICS("unobserve\n");
14831 }
14832
14833 void
14834 StopExaminingEvent ()
14835 {
14836     /* Stop observing current game */
14837     SendToICS(ics_prefix);
14838     SendToICS("unexamine\n");
14839 }
14840
14841 void
14842 ForwardInner (int target)
14843 {
14844     int limit; int oldSeekGraphUp = seekGraphUp;
14845
14846     if (appData.debugMode)
14847         fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
14848                 target, currentMove, forwardMostMove);
14849
14850     if (gameMode == EditPosition)
14851       return;
14852
14853     seekGraphUp = FALSE;
14854     MarkTargetSquares(1);
14855
14856     if (gameMode == PlayFromGameFile && !pausing)
14857       PauseEvent();
14858
14859     if (gameMode == IcsExamining && pausing)
14860       limit = pauseExamForwardMostMove;
14861     else
14862       limit = forwardMostMove;
14863
14864     if (target > limit) target = limit;
14865
14866     if (target > 0 && moveList[target - 1][0]) {
14867         int fromX, fromY, toX, toY;
14868         toX = moveList[target - 1][2] - AAA;
14869         toY = moveList[target - 1][3] - ONE;
14870         if (moveList[target - 1][1] == '@') {
14871             if (appData.highlightLastMove) {
14872                 SetHighlights(-1, -1, toX, toY);
14873             }
14874         } else {
14875             fromX = moveList[target - 1][0] - AAA;
14876             fromY = moveList[target - 1][1] - ONE;
14877             if (target == currentMove + 1) {
14878                 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
14879             }
14880             if (appData.highlightLastMove) {
14881                 SetHighlights(fromX, fromY, toX, toY);
14882             }
14883         }
14884     }
14885     if (gameMode == EditGame || gameMode == AnalyzeMode ||
14886         gameMode == Training || gameMode == PlayFromGameFile ||
14887         gameMode == AnalyzeFile) {
14888         while (currentMove < target) {
14889             if(second.analyzing) SendMoveToProgram(currentMove, &second);
14890             SendMoveToProgram(currentMove++, &first);
14891         }
14892     } else {
14893         currentMove = target;
14894     }
14895
14896     if (gameMode == EditGame || gameMode == EndOfGame) {
14897         whiteTimeRemaining = timeRemaining[0][currentMove];
14898         blackTimeRemaining = timeRemaining[1][currentMove];
14899     }
14900     DisplayBothClocks();
14901     DisplayMove(currentMove - 1);
14902     DrawPosition(oldSeekGraphUp, boards[currentMove]);
14903     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14904     if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
14905         DisplayComment(currentMove - 1, commentList[currentMove]);
14906     }
14907     ClearMap(); // [HGM] exclude: invalidate map
14908 }
14909
14910
14911 void
14912 ForwardEvent ()
14913 {
14914     if (gameMode == IcsExamining && !pausing) {
14915         SendToICS(ics_prefix);
14916         SendToICS("forward\n");
14917     } else {
14918         ForwardInner(currentMove + 1);
14919     }
14920 }
14921
14922 void
14923 ToEndEvent ()
14924 {
14925     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14926         /* to optimze, we temporarily turn off analysis mode while we feed
14927          * the remaining moves to the engine. Otherwise we get analysis output
14928          * after each move.
14929          */
14930         if (first.analysisSupport) {
14931           SendToProgram("exit\nforce\n", &first);
14932           first.analyzing = FALSE;
14933         }
14934     }
14935
14936     if (gameMode == IcsExamining && !pausing) {
14937         SendToICS(ics_prefix);
14938         SendToICS("forward 999999\n");
14939     } else {
14940         ForwardInner(forwardMostMove);
14941     }
14942
14943     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14944         /* we have fed all the moves, so reactivate analysis mode */
14945         SendToProgram("analyze\n", &first);
14946         first.analyzing = TRUE;
14947         /*first.maybeThinking = TRUE;*/
14948         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14949     }
14950 }
14951
14952 void
14953 BackwardInner (int target)
14954 {
14955     int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
14956
14957     if (appData.debugMode)
14958         fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
14959                 target, currentMove, forwardMostMove);
14960
14961     if (gameMode == EditPosition) return;
14962     seekGraphUp = FALSE;
14963     MarkTargetSquares(1);
14964     if (currentMove <= backwardMostMove) {
14965         ClearHighlights();
14966         DrawPosition(full_redraw, boards[currentMove]);
14967         return;
14968     }
14969     if (gameMode == PlayFromGameFile && !pausing)
14970       PauseEvent();
14971
14972     if (moveList[target][0]) {
14973         int fromX, fromY, toX, toY;
14974         toX = moveList[target][2] - AAA;
14975         toY = moveList[target][3] - ONE;
14976         if (moveList[target][1] == '@') {
14977             if (appData.highlightLastMove) {
14978                 SetHighlights(-1, -1, toX, toY);
14979             }
14980         } else {
14981             fromX = moveList[target][0] - AAA;
14982             fromY = moveList[target][1] - ONE;
14983             if (target == currentMove - 1) {
14984                 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
14985             }
14986             if (appData.highlightLastMove) {
14987                 SetHighlights(fromX, fromY, toX, toY);
14988             }
14989         }
14990     }
14991     if (gameMode == EditGame || gameMode==AnalyzeMode ||
14992         gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
14993         while (currentMove > target) {
14994             if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
14995                 // null move cannot be undone. Reload program with move history before it.
14996                 int i;
14997                 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
14998                     if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
14999                 }
15000                 SendBoard(&first, i);
15001               if(second.analyzing) SendBoard(&second, i);
15002                 for(currentMove=i; currentMove<target; currentMove++) {
15003                     SendMoveToProgram(currentMove, &first);
15004                     if(second.analyzing) SendMoveToProgram(currentMove, &second);
15005                 }
15006                 break;
15007             }
15008             SendToBoth("undo\n");
15009             currentMove--;
15010         }
15011     } else {
15012         currentMove = target;
15013     }
15014
15015     if (gameMode == EditGame || gameMode == EndOfGame) {
15016         whiteTimeRemaining = timeRemaining[0][currentMove];
15017         blackTimeRemaining = timeRemaining[1][currentMove];
15018     }
15019     DisplayBothClocks();
15020     DisplayMove(currentMove - 1);
15021     DrawPosition(full_redraw, boards[currentMove]);
15022     HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
15023     // [HGM] PV info: routine tests if comment empty
15024     DisplayComment(currentMove - 1, commentList[currentMove]);
15025     ClearMap(); // [HGM] exclude: invalidate map
15026 }
15027
15028 void
15029 BackwardEvent ()
15030 {
15031     if (gameMode == IcsExamining && !pausing) {
15032         SendToICS(ics_prefix);
15033         SendToICS("backward\n");
15034     } else {
15035         BackwardInner(currentMove - 1);
15036     }
15037 }
15038
15039 void
15040 ToStartEvent ()
15041 {
15042     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15043         /* to optimize, we temporarily turn off analysis mode while we undo
15044          * all the moves. Otherwise we get analysis output after each undo.
15045          */
15046         if (first.analysisSupport) {
15047           SendToProgram("exit\nforce\n", &first);
15048           first.analyzing = FALSE;
15049         }
15050     }
15051
15052     if (gameMode == IcsExamining && !pausing) {
15053         SendToICS(ics_prefix);
15054         SendToICS("backward 999999\n");
15055     } else {
15056         BackwardInner(backwardMostMove);
15057     }
15058
15059     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15060         /* we have fed all the moves, so reactivate analysis mode */
15061         SendToProgram("analyze\n", &first);
15062         first.analyzing = TRUE;
15063         /*first.maybeThinking = TRUE;*/
15064         first.maybeThinking = FALSE; /* avoid killing GNU Chess */
15065     }
15066 }
15067
15068 void
15069 ToNrEvent (int to)
15070 {
15071   if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
15072   if (to >= forwardMostMove) to = forwardMostMove;
15073   if (to <= backwardMostMove) to = backwardMostMove;
15074   if (to < currentMove) {
15075     BackwardInner(to);
15076   } else {
15077     ForwardInner(to);
15078   }
15079 }
15080
15081 void
15082 RevertEvent (Boolean annotate)
15083 {
15084     if(PopTail(annotate)) { // [HGM] vari: restore old game tail
15085         return;
15086     }
15087     if (gameMode != IcsExamining) {
15088         DisplayError(_("You are not examining a game"), 0);
15089         return;
15090     }
15091     if (pausing) {
15092         DisplayError(_("You can't revert while pausing"), 0);
15093         return;
15094     }
15095     SendToICS(ics_prefix);
15096     SendToICS("revert\n");
15097 }
15098
15099 void
15100 RetractMoveEvent ()
15101 {
15102     switch (gameMode) {
15103       case MachinePlaysWhite:
15104       case MachinePlaysBlack:
15105         if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15106             DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
15107             return;
15108         }
15109         if (forwardMostMove < 2) return;
15110         currentMove = forwardMostMove = forwardMostMove - 2;
15111         whiteTimeRemaining = timeRemaining[0][currentMove];
15112         blackTimeRemaining = timeRemaining[1][currentMove];
15113         DisplayBothClocks();
15114         DisplayMove(currentMove - 1);
15115         ClearHighlights();/*!! could figure this out*/
15116         DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
15117         SendToProgram("remove\n", &first);
15118         /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
15119         break;
15120
15121       case BeginningOfGame:
15122       default:
15123         break;
15124
15125       case IcsPlayingWhite:
15126       case IcsPlayingBlack:
15127         if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
15128             SendToICS(ics_prefix);
15129             SendToICS("takeback 2\n");
15130         } else {
15131             SendToICS(ics_prefix);
15132             SendToICS("takeback 1\n");
15133         }
15134         break;
15135     }
15136 }
15137
15138 void
15139 MoveNowEvent ()
15140 {
15141     ChessProgramState *cps;
15142
15143     switch (gameMode) {
15144       case MachinePlaysWhite:
15145         if (!WhiteOnMove(forwardMostMove)) {
15146             DisplayError(_("It is your turn"), 0);
15147             return;
15148         }
15149         cps = &first;
15150         break;
15151       case MachinePlaysBlack:
15152         if (WhiteOnMove(forwardMostMove)) {
15153             DisplayError(_("It is your turn"), 0);
15154             return;
15155         }
15156         cps = &first;
15157         break;
15158       case TwoMachinesPlay:
15159         if (WhiteOnMove(forwardMostMove) ==
15160             (first.twoMachinesColor[0] == 'w')) {
15161             cps = &first;
15162         } else {
15163             cps = &second;
15164         }
15165         break;
15166       case BeginningOfGame:
15167       default:
15168         return;
15169     }
15170     SendToProgram("?\n", cps);
15171 }
15172
15173 void
15174 TruncateGameEvent ()
15175 {
15176     EditGameEvent();
15177     if (gameMode != EditGame) return;
15178     TruncateGame();
15179 }
15180
15181 void
15182 TruncateGame ()
15183 {
15184     CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
15185     if (forwardMostMove > currentMove) {
15186         if (gameInfo.resultDetails != NULL) {
15187             free(gameInfo.resultDetails);
15188             gameInfo.resultDetails = NULL;
15189             gameInfo.result = GameUnfinished;
15190         }
15191         forwardMostMove = currentMove;
15192         HistorySet(parseList, backwardMostMove, forwardMostMove,
15193                    currentMove-1);
15194     }
15195 }
15196
15197 void
15198 HintEvent ()
15199 {
15200     if (appData.noChessProgram) return;
15201     switch (gameMode) {
15202       case MachinePlaysWhite:
15203         if (WhiteOnMove(forwardMostMove)) {
15204             DisplayError(_("Wait until your turn"), 0);
15205             return;
15206         }
15207         break;
15208       case BeginningOfGame:
15209       case MachinePlaysBlack:
15210         if (!WhiteOnMove(forwardMostMove)) {
15211             DisplayError(_("Wait until your turn"), 0);
15212             return;
15213         }
15214         break;
15215       default:
15216         DisplayError(_("No hint available"), 0);
15217         return;
15218     }
15219     SendToProgram("hint\n", &first);
15220     hintRequested = TRUE;
15221 }
15222
15223 void
15224 CreateBookEvent ()
15225 {
15226     ListGame * lg = (ListGame *) gameList.head;
15227     FILE *f;
15228     int nItem;
15229     static int secondTime = FALSE;
15230
15231     if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
15232         DisplayError(_("Game list not loaded or empty"), 0);
15233         return;
15234     }
15235
15236     if(!secondTime && (f = fopen(appData.polyglotBook, "r"))) {
15237         fclose(f);
15238         secondTime++;
15239         DisplayNote(_("Book file exists! Try again for overwrite."));
15240         return;
15241     }
15242
15243     creatingBook = TRUE;
15244     secondTime = FALSE;
15245
15246     /* Get list size */
15247     for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
15248         LoadGame(f, nItem, "", TRUE);
15249         AddGameToBook(TRUE);
15250         lg = (ListGame *) lg->node.succ;
15251     }
15252
15253     creatingBook = FALSE;
15254     FlushBook();
15255 }
15256
15257 void
15258 BookEvent ()
15259 {
15260     if (appData.noChessProgram) return;
15261     switch (gameMode) {
15262       case MachinePlaysWhite:
15263         if (WhiteOnMove(forwardMostMove)) {
15264             DisplayError(_("Wait until your turn"), 0);
15265             return;
15266         }
15267         break;
15268       case BeginningOfGame:
15269       case MachinePlaysBlack:
15270         if (!WhiteOnMove(forwardMostMove)) {
15271             DisplayError(_("Wait until your turn"), 0);
15272             return;
15273         }
15274         break;
15275       case EditPosition:
15276         EditPositionDone(TRUE);
15277         break;
15278       case TwoMachinesPlay:
15279         return;
15280       default:
15281         break;
15282     }
15283     SendToProgram("bk\n", &first);
15284     bookOutput[0] = NULLCHAR;
15285     bookRequested = TRUE;
15286 }
15287
15288 void
15289 AboutGameEvent ()
15290 {
15291     char *tags = PGNTags(&gameInfo);
15292     TagsPopUp(tags, CmailMsg());
15293     free(tags);
15294 }
15295
15296 /* end button procedures */
15297
15298 void
15299 PrintPosition (FILE *fp, int move)
15300 {
15301     int i, j;
15302
15303     for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15304         for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15305             char c = PieceToChar(boards[move][i][j]);
15306             fputc(c == 'x' ? '.' : c, fp);
15307             fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
15308         }
15309     }
15310     if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
15311       fprintf(fp, "white to play\n");
15312     else
15313       fprintf(fp, "black to play\n");
15314 }
15315
15316 void
15317 PrintOpponents (FILE *fp)
15318 {
15319     if (gameInfo.white != NULL) {
15320         fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
15321     } else {
15322         fprintf(fp, "\n");
15323     }
15324 }
15325
15326 /* Find last component of program's own name, using some heuristics */
15327 void
15328 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
15329 {
15330     char *p, *q, c;
15331     int local = (strcmp(host, "localhost") == 0);
15332     while (!local && (p = strchr(prog, ';')) != NULL) {
15333         p++;
15334         while (*p == ' ') p++;
15335         prog = p;
15336     }
15337     if (*prog == '"' || *prog == '\'') {
15338         q = strchr(prog + 1, *prog);
15339     } else {
15340         q = strchr(prog, ' ');
15341     }
15342     if (q == NULL) q = prog + strlen(prog);
15343     p = q;
15344     while (p >= prog && *p != '/' && *p != '\\') p--;
15345     p++;
15346     if(p == prog && *p == '"') p++;
15347     c = *q; *q = 0;
15348     if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
15349     memcpy(buf, p, q - p);
15350     buf[q - p] = NULLCHAR;
15351     if (!local) {
15352         strcat(buf, "@");
15353         strcat(buf, host);
15354     }
15355 }
15356
15357 char *
15358 TimeControlTagValue ()
15359 {
15360     char buf[MSG_SIZ];
15361     if (!appData.clockMode) {
15362       safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
15363     } else if (movesPerSession > 0) {
15364       snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
15365     } else if (timeIncrement == 0) {
15366       snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
15367     } else {
15368       snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
15369     }
15370     return StrSave(buf);
15371 }
15372
15373 void
15374 SetGameInfo ()
15375 {
15376     /* This routine is used only for certain modes */
15377     VariantClass v = gameInfo.variant;
15378     ChessMove r = GameUnfinished;
15379     char *p = NULL;
15380
15381     if(keepInfo) return;
15382
15383     if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
15384         r = gameInfo.result;
15385         p = gameInfo.resultDetails;
15386         gameInfo.resultDetails = NULL;
15387     }
15388     ClearGameInfo(&gameInfo);
15389     gameInfo.variant = v;
15390
15391     switch (gameMode) {
15392       case MachinePlaysWhite:
15393         gameInfo.event = StrSave( appData.pgnEventHeader );
15394         gameInfo.site = StrSave(HostName());
15395         gameInfo.date = PGNDate();
15396         gameInfo.round = StrSave("-");
15397         gameInfo.white = StrSave(first.tidy);
15398         gameInfo.black = StrSave(UserName());
15399         gameInfo.timeControl = TimeControlTagValue();
15400         break;
15401
15402       case MachinePlaysBlack:
15403         gameInfo.event = StrSave( appData.pgnEventHeader );
15404         gameInfo.site = StrSave(HostName());
15405         gameInfo.date = PGNDate();
15406         gameInfo.round = StrSave("-");
15407         gameInfo.white = StrSave(UserName());
15408         gameInfo.black = StrSave(first.tidy);
15409         gameInfo.timeControl = TimeControlTagValue();
15410         break;
15411
15412       case TwoMachinesPlay:
15413         gameInfo.event = StrSave( appData.pgnEventHeader );
15414         gameInfo.site = StrSave(HostName());
15415         gameInfo.date = PGNDate();
15416         if (roundNr > 0) {
15417             char buf[MSG_SIZ];
15418             snprintf(buf, MSG_SIZ, "%d", roundNr);
15419             gameInfo.round = StrSave(buf);
15420         } else {
15421             gameInfo.round = StrSave("-");
15422         }
15423         if (first.twoMachinesColor[0] == 'w') {
15424             gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
15425             gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
15426         } else {
15427             gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
15428             gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
15429         }
15430         gameInfo.timeControl = TimeControlTagValue();
15431         break;
15432
15433       case EditGame:
15434         gameInfo.event = StrSave("Edited game");
15435         gameInfo.site = StrSave(HostName());
15436         gameInfo.date = PGNDate();
15437         gameInfo.round = StrSave("-");
15438         gameInfo.white = StrSave("-");
15439         gameInfo.black = StrSave("-");
15440         gameInfo.result = r;
15441         gameInfo.resultDetails = p;
15442         break;
15443
15444       case EditPosition:
15445         gameInfo.event = StrSave("Edited position");
15446         gameInfo.site = StrSave(HostName());
15447         gameInfo.date = PGNDate();
15448         gameInfo.round = StrSave("-");
15449         gameInfo.white = StrSave("-");
15450         gameInfo.black = StrSave("-");
15451         break;
15452
15453       case IcsPlayingWhite:
15454       case IcsPlayingBlack:
15455       case IcsObserving:
15456       case IcsExamining:
15457         break;
15458
15459       case PlayFromGameFile:
15460         gameInfo.event = StrSave("Game from non-PGN file");
15461         gameInfo.site = StrSave(HostName());
15462         gameInfo.date = PGNDate();
15463         gameInfo.round = StrSave("-");
15464         gameInfo.white = StrSave("?");
15465         gameInfo.black = StrSave("?");
15466         break;
15467
15468       default:
15469         break;
15470     }
15471 }
15472
15473 void
15474 ReplaceComment (int index, char *text)
15475 {
15476     int len;
15477     char *p;
15478     float score;
15479
15480     if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
15481        pvInfoList[index-1].depth == len &&
15482        fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
15483        (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
15484     while (*text == '\n') text++;
15485     len = strlen(text);
15486     while (len > 0 && text[len - 1] == '\n') len--;
15487
15488     if (commentList[index] != NULL)
15489       free(commentList[index]);
15490
15491     if (len == 0) {
15492         commentList[index] = NULL;
15493         return;
15494     }
15495   if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
15496       *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
15497       *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
15498     commentList[index] = (char *) malloc(len + 2);
15499     strncpy(commentList[index], text, len);
15500     commentList[index][len] = '\n';
15501     commentList[index][len + 1] = NULLCHAR;
15502   } else {
15503     // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
15504     char *p;
15505     commentList[index] = (char *) malloc(len + 7);
15506     safeStrCpy(commentList[index], "{\n", 3);
15507     safeStrCpy(commentList[index]+2, text, len+1);
15508     commentList[index][len+2] = NULLCHAR;
15509     while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
15510     strcat(commentList[index], "\n}\n");
15511   }
15512 }
15513
15514 void
15515 CrushCRs (char *text)
15516 {
15517   char *p = text;
15518   char *q = text;
15519   char ch;
15520
15521   do {
15522     ch = *p++;
15523     if (ch == '\r') continue;
15524     *q++ = ch;
15525   } while (ch != '\0');
15526 }
15527
15528 void
15529 AppendComment (int index, char *text, Boolean addBraces)
15530 /* addBraces  tells if we should add {} */
15531 {
15532     int oldlen, len;
15533     char *old;
15534
15535 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
15536     if(addBraces == 3) addBraces = 0; else // force appending literally
15537     text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
15538
15539     CrushCRs(text);
15540     while (*text == '\n') text++;
15541     len = strlen(text);
15542     while (len > 0 && text[len - 1] == '\n') len--;
15543     text[len] = NULLCHAR;
15544
15545     if (len == 0) return;
15546
15547     if (commentList[index] != NULL) {
15548       Boolean addClosingBrace = addBraces;
15549         old = commentList[index];
15550         oldlen = strlen(old);
15551         while(commentList[index][oldlen-1] ==  '\n')
15552           commentList[index][--oldlen] = NULLCHAR;
15553         commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
15554         safeStrCpy(commentList[index], old, oldlen + len + 6);
15555         free(old);
15556         // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
15557         if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
15558           if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
15559           while (*text == '\n') { text++; len--; }
15560           commentList[index][--oldlen] = NULLCHAR;
15561       }
15562         if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
15563         else          strcat(commentList[index], "\n");
15564         strcat(commentList[index], text);
15565         if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
15566         else          strcat(commentList[index], "\n");
15567     } else {
15568         commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
15569         if(addBraces)
15570           safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
15571         else commentList[index][0] = NULLCHAR;
15572         strcat(commentList[index], text);
15573         strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
15574         if(addBraces == TRUE) strcat(commentList[index], "}\n");
15575     }
15576 }
15577
15578 static char *
15579 FindStr (char * text, char * sub_text)
15580 {
15581     char * result = strstr( text, sub_text );
15582
15583     if( result != NULL ) {
15584         result += strlen( sub_text );
15585     }
15586
15587     return result;
15588 }
15589
15590 /* [AS] Try to extract PV info from PGN comment */
15591 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
15592 char *
15593 GetInfoFromComment (int index, char * text)
15594 {
15595     char * sep = text, *p;
15596
15597     if( text != NULL && index > 0 ) {
15598         int score = 0;
15599         int depth = 0;
15600         int time = -1, sec = 0, deci;
15601         char * s_eval = FindStr( text, "[%eval " );
15602         char * s_emt = FindStr( text, "[%emt " );
15603 #if 0
15604         if( s_eval != NULL || s_emt != NULL ) {
15605 #else
15606         if(0) { // [HGM] this code is not finished, and could actually be detrimental
15607 #endif
15608             /* New style */
15609             char delim;
15610
15611             if( s_eval != NULL ) {
15612                 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
15613                     return text;
15614                 }
15615
15616                 if( delim != ']' ) {
15617                     return text;
15618                 }
15619             }
15620
15621             if( s_emt != NULL ) {
15622             }
15623                 return text;
15624         }
15625         else {
15626             /* We expect something like: [+|-]nnn.nn/dd */
15627             int score_lo = 0;
15628
15629             if(*text != '{') return text; // [HGM] braces: must be normal comment
15630
15631             sep = strchr( text, '/' );
15632             if( sep == NULL || sep < (text+4) ) {
15633                 return text;
15634             }
15635
15636             p = text;
15637             if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
15638             if(p[1] == '(') { // comment starts with PV
15639                p = strchr(p, ')'); // locate end of PV
15640                if(p == NULL || sep < p+5) return text;
15641                // at this point we have something like "{(.*) +0.23/6 ..."
15642                p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
15643                *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
15644                // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
15645             }
15646             time = -1; sec = -1; deci = -1;
15647             if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
15648                 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
15649                 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
15650                 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3   ) {
15651                 return text;
15652             }
15653
15654             if( score_lo < 0 || score_lo >= 100 ) {
15655                 return text;
15656             }
15657
15658             if(sec >= 0) time = 600*time + 10*sec; else
15659             if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
15660
15661             score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
15662
15663             /* [HGM] PV time: now locate end of PV info */
15664             while( *++sep >= '0' && *sep <= '9'); // strip depth
15665             if(time >= 0)
15666             while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
15667             if(sec >= 0)
15668             while( *++sep >= '0' && *sep <= '9'); // strip seconds
15669             if(deci >= 0)
15670             while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
15671             while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
15672         }
15673
15674         if( depth <= 0 ) {
15675             return text;
15676         }
15677
15678         if( time < 0 ) {
15679             time = -1;
15680         }
15681
15682         pvInfoList[index-1].depth = depth;
15683         pvInfoList[index-1].score = score;
15684         pvInfoList[index-1].time  = 10*time; // centi-sec
15685         if(*sep == '}') *sep = 0; else *--sep = '{';
15686         if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
15687     }
15688     return sep;
15689 }
15690
15691 void
15692 SendToProgram (char *message, ChessProgramState *cps)
15693 {
15694     int count, outCount, error;
15695     char buf[MSG_SIZ];
15696
15697     if (cps->pr == NoProc) return;
15698     Attention(cps);
15699
15700     if (appData.debugMode) {
15701         TimeMark now;
15702         GetTimeMark(&now);
15703         fprintf(debugFP, "%ld >%-6s: %s",
15704                 SubtractTimeMarks(&now, &programStartTime),
15705                 cps->which, message);
15706         if(serverFP)
15707             fprintf(serverFP, "%ld >%-6s: %s",
15708                 SubtractTimeMarks(&now, &programStartTime),
15709                 cps->which, message), fflush(serverFP);
15710     }
15711
15712     count = strlen(message);
15713     outCount = OutputToProcess(cps->pr, message, count, &error);
15714     if (outCount < count && !exiting
15715                          && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
15716       if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
15717       snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
15718         if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15719             if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15720                 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15721                 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15722                 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15723             } else {
15724                 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15725                 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15726                 gameInfo.result = res;
15727             }
15728             gameInfo.resultDetails = StrSave(buf);
15729         }
15730         if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15731         if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15732     }
15733 }
15734
15735 void
15736 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
15737 {
15738     char *end_str;
15739     char buf[MSG_SIZ];
15740     ChessProgramState *cps = (ChessProgramState *)closure;
15741
15742     if (isr != cps->isr) return; /* Killed intentionally */
15743     if (count <= 0) {
15744         if (count == 0) {
15745             RemoveInputSource(cps->isr);
15746             snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
15747                     _(cps->which), cps->program);
15748             if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
15749             if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15750                 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15751                     snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15752                     if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15753                     gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15754                 } else {
15755                     ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15756                     if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15757                     gameInfo.result = res;
15758                 }
15759                 gameInfo.resultDetails = StrSave(buf);
15760             }
15761             if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15762             if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
15763         } else {
15764             snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
15765                     _(cps->which), cps->program);
15766             RemoveInputSource(cps->isr);
15767
15768             /* [AS] Program is misbehaving badly... kill it */
15769             if( count == -2 ) {
15770                 DestroyChildProcess( cps->pr, 9 );
15771                 cps->pr = NoProc;
15772             }
15773
15774             if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15775         }
15776         return;
15777     }
15778
15779     if ((end_str = strchr(message, '\r')) != NULL)
15780       *end_str = NULLCHAR;
15781     if ((end_str = strchr(message, '\n')) != NULL)
15782       *end_str = NULLCHAR;
15783
15784     if (appData.debugMode) {
15785         TimeMark now; int print = 1;
15786         char *quote = ""; char c; int i;
15787
15788         if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
15789                 char start = message[0];
15790                 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
15791                 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
15792                    sscanf(message, "move %c", &c)!=1  && sscanf(message, "offer%c", &c)!=1 &&
15793                    sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
15794                    sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
15795                    sscanf(message, "tell%c", &c)!=1   && sscanf(message, "0-1 %c", &c)!=1 &&
15796                    sscanf(message, "1-0 %c", &c)!=1   && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
15797                    sscanf(message, "setboard %c", &c)!=1   && sscanf(message, "setup %c", &c)!=1 &&
15798                    sscanf(message, "hint: %c", &c)!=1 &&
15799                    sscanf(message, "pong %c", &c)!=1   && start != '#') {
15800                     quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
15801                     print = (appData.engineComments >= 2);
15802                 }
15803                 message[0] = start; // restore original message
15804         }
15805         if(print) {
15806                 GetTimeMark(&now);
15807                 fprintf(debugFP, "%ld <%-6s: %s%s\n",
15808                         SubtractTimeMarks(&now, &programStartTime), cps->which,
15809                         quote,
15810                         message);
15811                 if(serverFP)
15812                     fprintf(serverFP, "%ld <%-6s: %s%s\n",
15813                         SubtractTimeMarks(&now, &programStartTime), cps->which,
15814                         quote,
15815                         message), fflush(serverFP);
15816         }
15817     }
15818
15819     /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
15820     if (appData.icsEngineAnalyze) {
15821         if (strstr(message, "whisper") != NULL ||
15822              strstr(message, "kibitz") != NULL ||
15823             strstr(message, "tellics") != NULL) return;
15824     }
15825
15826     HandleMachineMove(message, cps);
15827 }
15828
15829
15830 void
15831 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
15832 {
15833     char buf[MSG_SIZ];
15834     int seconds;
15835
15836     if( timeControl_2 > 0 ) {
15837         if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
15838             tc = timeControl_2;
15839         }
15840     }
15841     tc  /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
15842     inc /= cps->timeOdds;
15843     st  /= cps->timeOdds;
15844
15845     seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
15846
15847     if (st > 0) {
15848       /* Set exact time per move, normally using st command */
15849       if (cps->stKludge) {
15850         /* GNU Chess 4 has no st command; uses level in a nonstandard way */
15851         seconds = st % 60;
15852         if (seconds == 0) {
15853           snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
15854         } else {
15855           snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
15856         }
15857       } else {
15858         snprintf(buf, MSG_SIZ, "st %d\n", st);
15859       }
15860     } else {
15861       /* Set conventional or incremental time control, using level command */
15862       if (seconds == 0) {
15863         /* Note old gnuchess bug -- minutes:seconds used to not work.
15864            Fixed in later versions, but still avoid :seconds
15865            when seconds is 0. */
15866         snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
15867       } else {
15868         snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
15869                  seconds, inc/1000.);
15870       }
15871     }
15872     SendToProgram(buf, cps);
15873
15874     /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
15875     /* Orthogonally, limit search to given depth */
15876     if (sd > 0) {
15877       if (cps->sdKludge) {
15878         snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
15879       } else {
15880         snprintf(buf, MSG_SIZ, "sd %d\n", sd);
15881       }
15882       SendToProgram(buf, cps);
15883     }
15884
15885     if(cps->nps >= 0) { /* [HGM] nps */
15886         if(cps->supportsNPS == FALSE)
15887           cps->nps = -1; // don't use if engine explicitly says not supported!
15888         else {
15889           snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
15890           SendToProgram(buf, cps);
15891         }
15892     }
15893 }
15894
15895 ChessProgramState *
15896 WhitePlayer ()
15897 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
15898 {
15899     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
15900        gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
15901         return &second;
15902     return &first;
15903 }
15904
15905 void
15906 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
15907 {
15908     char message[MSG_SIZ];
15909     long time, otime;
15910
15911     /* Note: this routine must be called when the clocks are stopped
15912        or when they have *just* been set or switched; otherwise
15913        it will be off by the time since the current tick started.
15914     */
15915     if (machineWhite) {
15916         time = whiteTimeRemaining / 10;
15917         otime = blackTimeRemaining / 10;
15918     } else {
15919         time = blackTimeRemaining / 10;
15920         otime = whiteTimeRemaining / 10;
15921     }
15922     /* [HGM] translate opponent's time by time-odds factor */
15923     otime = (otime * cps->other->timeOdds) / cps->timeOdds;
15924
15925     if (time <= 0) time = 1;
15926     if (otime <= 0) otime = 1;
15927
15928     snprintf(message, MSG_SIZ, "time %ld\n", time);
15929     SendToProgram(message, cps);
15930
15931     snprintf(message, MSG_SIZ, "otim %ld\n", otime);
15932     SendToProgram(message, cps);
15933 }
15934
15935 int
15936 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15937 {
15938   char buf[MSG_SIZ];
15939   int len = strlen(name);
15940   int val;
15941
15942   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15943     (*p) += len + 1;
15944     sscanf(*p, "%d", &val);
15945     *loc = (val != 0);
15946     while (**p && **p != ' ')
15947       (*p)++;
15948     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15949     SendToProgram(buf, cps);
15950     return TRUE;
15951   }
15952   return FALSE;
15953 }
15954
15955 int
15956 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15957 {
15958   char buf[MSG_SIZ];
15959   int len = strlen(name);
15960   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15961     (*p) += len + 1;
15962     sscanf(*p, "%d", loc);
15963     while (**p && **p != ' ') (*p)++;
15964     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15965     SendToProgram(buf, cps);
15966     return TRUE;
15967   }
15968   return FALSE;
15969 }
15970
15971 int
15972 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
15973 {
15974   char buf[MSG_SIZ];
15975   int len = strlen(name);
15976   if (strncmp((*p), name, len) == 0
15977       && (*p)[len] == '=' && (*p)[len+1] == '\"') {
15978     (*p) += len + 2;
15979     ASSIGN(*loc, *p); // kludge alert: assign rest of line just to be sure allocation is large enough so that sscanf below always fits
15980     sscanf(*p, "%[^\"]", *loc);
15981     while (**p && **p != '\"') (*p)++;
15982     if (**p == '\"') (*p)++;
15983     snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15984     SendToProgram(buf, cps);
15985     return TRUE;
15986   }
15987   return FALSE;
15988 }
15989
15990 int
15991 ParseOption (Option *opt, ChessProgramState *cps)
15992 // [HGM] options: process the string that defines an engine option, and determine
15993 // name, type, default value, and allowed value range
15994 {
15995         char *p, *q, buf[MSG_SIZ];
15996         int n, min = (-1)<<31, max = 1<<31, def;
15997
15998         if(p = strstr(opt->name, " -spin ")) {
15999             if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16000             if(max < min) max = min; // enforce consistency
16001             if(def < min) def = min;
16002             if(def > max) def = max;
16003             opt->value = def;
16004             opt->min = min;
16005             opt->max = max;
16006             opt->type = Spin;
16007         } else if((p = strstr(opt->name, " -slider "))) {
16008             // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
16009             if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16010             if(max < min) max = min; // enforce consistency
16011             if(def < min) def = min;
16012             if(def > max) def = max;
16013             opt->value = def;
16014             opt->min = min;
16015             opt->max = max;
16016             opt->type = Spin; // Slider;
16017         } else if((p = strstr(opt->name, " -string "))) {
16018             opt->textValue = p+9;
16019             opt->type = TextBox;
16020         } else if((p = strstr(opt->name, " -file "))) {
16021             // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16022             opt->textValue = p+7;
16023             opt->type = FileName; // FileName;
16024         } else if((p = strstr(opt->name, " -path "))) {
16025             // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16026             opt->textValue = p+7;
16027             opt->type = PathName; // PathName;
16028         } else if(p = strstr(opt->name, " -check ")) {
16029             if(sscanf(p, " -check %d", &def) < 1) return FALSE;
16030             opt->value = (def != 0);
16031             opt->type = CheckBox;
16032         } else if(p = strstr(opt->name, " -combo ")) {
16033             opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
16034             cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
16035             if(*q == '*') cps->comboList[cps->comboCnt-1]++;
16036             opt->value = n = 0;
16037             while(q = StrStr(q, " /// ")) {
16038                 n++; *q = 0;    // count choices, and null-terminate each of them
16039                 q += 5;
16040                 if(*q == '*') { // remember default, which is marked with * prefix
16041                     q++;
16042                     opt->value = n;
16043                 }
16044                 cps->comboList[cps->comboCnt++] = q;
16045             }
16046             cps->comboList[cps->comboCnt++] = NULL;
16047             opt->max = n + 1;
16048             opt->type = ComboBox;
16049         } else if(p = strstr(opt->name, " -button")) {
16050             opt->type = Button;
16051         } else if(p = strstr(opt->name, " -save")) {
16052             opt->type = SaveButton;
16053         } else return FALSE;
16054         *p = 0; // terminate option name
16055         // now look if the command-line options define a setting for this engine option.
16056         if(cps->optionSettings && cps->optionSettings[0])
16057             p = strstr(cps->optionSettings, opt->name); else p = NULL;
16058         if(p && (p == cps->optionSettings || p[-1] == ',')) {
16059           snprintf(buf, MSG_SIZ, "option %s", p);
16060                 if(p = strstr(buf, ",")) *p = 0;
16061                 if(q = strchr(buf, '=')) switch(opt->type) {
16062                     case ComboBox:
16063                         for(n=0; n<opt->max; n++)
16064                             if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
16065                         break;
16066                     case TextBox:
16067                         safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
16068                         break;
16069                     case Spin:
16070                     case CheckBox:
16071                         opt->value = atoi(q+1);
16072                     default:
16073                         break;
16074                 }
16075                 strcat(buf, "\n");
16076                 SendToProgram(buf, cps);
16077         }
16078         return TRUE;
16079 }
16080
16081 void
16082 FeatureDone (ChessProgramState *cps, int val)
16083 {
16084   DelayedEventCallback cb = GetDelayedEvent();
16085   if ((cb == InitBackEnd3 && cps == &first) ||
16086       (cb == SettingsMenuIfReady && cps == &second) ||
16087       (cb == LoadEngine) ||
16088       (cb == TwoMachinesEventIfReady)) {
16089     CancelDelayedEvent();
16090     ScheduleDelayedEvent(cb, val ? 1 : 3600000);
16091   }
16092   cps->initDone = val;
16093   if(val) cps->reload = FALSE;
16094 }
16095
16096 /* Parse feature command from engine */
16097 void
16098 ParseFeatures (char *args, ChessProgramState *cps)
16099 {
16100   char *p = args;
16101   char *q = NULL;
16102   int val;
16103   char buf[MSG_SIZ];
16104
16105   for (;;) {
16106     while (*p == ' ') p++;
16107     if (*p == NULLCHAR) return;
16108
16109     if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
16110     if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
16111     if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
16112     if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
16113     if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
16114     if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
16115     if (BoolFeature(&p, "reuse", &val, cps)) {
16116       /* Engine can disable reuse, but can't enable it if user said no */
16117       if (!val) cps->reuse = FALSE;
16118       continue;
16119     }
16120     if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
16121     if (StringFeature(&p, "myname", &cps->tidy, cps)) {
16122       if (gameMode == TwoMachinesPlay) {
16123         DisplayTwoMachinesTitle();
16124       } else {
16125         DisplayTitle("");
16126       }
16127       continue;
16128     }
16129     if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
16130     if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
16131     if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
16132     if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
16133     if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
16134     if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
16135     if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
16136     if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
16137     if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
16138     if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
16139     if (IntFeature(&p, "done", &val, cps)) {
16140       FeatureDone(cps, val);
16141       continue;
16142     }
16143     /* Added by Tord: */
16144     if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
16145     if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
16146     /* End of additions by Tord */
16147
16148     /* [HGM] added features: */
16149     if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
16150     if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
16151     if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
16152     if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
16153     if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
16154     if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
16155     if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
16156         if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
16157         FREE(cps->option[cps->nrOptions].name);
16158         cps->option[cps->nrOptions].name = q; q = NULL;
16159         if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
16160           snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
16161             SendToProgram(buf, cps);
16162             continue;
16163         }
16164         if(cps->nrOptions >= MAX_OPTIONS) {
16165             cps->nrOptions--;
16166             snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
16167             DisplayError(buf, 0);
16168         }
16169         continue;
16170     }
16171     /* End of additions by HGM */
16172
16173     /* unknown feature: complain and skip */
16174     q = p;
16175     while (*q && *q != '=') q++;
16176     snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
16177     SendToProgram(buf, cps);
16178     p = q;
16179     if (*p == '=') {
16180       p++;
16181       if (*p == '\"') {
16182         p++;
16183         while (*p && *p != '\"') p++;
16184         if (*p == '\"') p++;
16185       } else {
16186         while (*p && *p != ' ') p++;
16187       }
16188     }
16189   }
16190
16191 }
16192
16193 void
16194 PeriodicUpdatesEvent (int newState)
16195 {
16196     if (newState == appData.periodicUpdates)
16197       return;
16198
16199     appData.periodicUpdates=newState;
16200
16201     /* Display type changes, so update it now */
16202 //    DisplayAnalysis();
16203
16204     /* Get the ball rolling again... */
16205     if (newState) {
16206         AnalysisPeriodicEvent(1);
16207         StartAnalysisClock();
16208     }
16209 }
16210
16211 void
16212 PonderNextMoveEvent (int newState)
16213 {
16214     if (newState == appData.ponderNextMove) return;
16215     if (gameMode == EditPosition) EditPositionDone(TRUE);
16216     if (newState) {
16217         SendToProgram("hard\n", &first);
16218         if (gameMode == TwoMachinesPlay) {
16219             SendToProgram("hard\n", &second);
16220         }
16221     } else {
16222         SendToProgram("easy\n", &first);
16223         thinkOutput[0] = NULLCHAR;
16224         if (gameMode == TwoMachinesPlay) {
16225             SendToProgram("easy\n", &second);
16226         }
16227     }
16228     appData.ponderNextMove = newState;
16229 }
16230
16231 void
16232 NewSettingEvent (int option, int *feature, char *command, int value)
16233 {
16234     char buf[MSG_SIZ];
16235
16236     if (gameMode == EditPosition) EditPositionDone(TRUE);
16237     snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
16238     if(feature == NULL || *feature) SendToProgram(buf, &first);
16239     if (gameMode == TwoMachinesPlay) {
16240         if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
16241     }
16242 }
16243
16244 void
16245 ShowThinkingEvent ()
16246 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
16247 {
16248     static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
16249     int newState = appData.showThinking
16250         // [HGM] thinking: other features now need thinking output as well
16251         || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
16252
16253     if (oldState == newState) return;
16254     oldState = newState;
16255     if (gameMode == EditPosition) EditPositionDone(TRUE);
16256     if (oldState) {
16257         SendToProgram("post\n", &first);
16258         if (gameMode == TwoMachinesPlay) {
16259             SendToProgram("post\n", &second);
16260         }
16261     } else {
16262         SendToProgram("nopost\n", &first);
16263         thinkOutput[0] = NULLCHAR;
16264         if (gameMode == TwoMachinesPlay) {
16265             SendToProgram("nopost\n", &second);
16266         }
16267     }
16268 //    appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
16269 }
16270
16271 void
16272 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
16273 {
16274   ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
16275   if (pr == NoProc) return;
16276   AskQuestion(title, question, replyPrefix, pr);
16277 }
16278
16279 void
16280 TypeInEvent (char firstChar)
16281 {
16282     if ((gameMode == BeginningOfGame && !appData.icsActive) ||
16283         gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
16284         gameMode == AnalyzeMode || gameMode == EditGame ||
16285         gameMode == EditPosition || gameMode == IcsExamining ||
16286         gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
16287         isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
16288                 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
16289                   gameMode == IcsObserving || gameMode == TwoMachinesPlay    ) ||
16290         gameMode == Training) PopUpMoveDialog(firstChar);
16291 }
16292
16293 void
16294 TypeInDoneEvent (char *move)
16295 {
16296         Board board;
16297         int n, fromX, fromY, toX, toY;
16298         char promoChar;
16299         ChessMove moveType;
16300
16301         // [HGM] FENedit
16302         if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
16303                 EditPositionPasteFEN(move);
16304                 return;
16305         }
16306         // [HGM] movenum: allow move number to be typed in any mode
16307         if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
16308           ToNrEvent(2*n-1);
16309           return;
16310         }
16311         // undocumented kludge: allow command-line option to be typed in!
16312         // (potentially fatal, and does not implement the effect of the option.)
16313         // should only be used for options that are values on which future decisions will be made,
16314         // and definitely not on options that would be used during initialization.
16315         if(strstr(move, "!!! -") == move) {
16316             ParseArgsFromString(move+4);
16317             return;
16318         }
16319
16320       if (gameMode != EditGame && currentMove != forwardMostMove &&
16321         gameMode != Training) {
16322         DisplayMoveError(_("Displayed move is not current"));
16323       } else {
16324         int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
16325           &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
16326         if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
16327         if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
16328           &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
16329           UserMoveEvent(fromX, fromY, toX, toY, promoChar);
16330         } else {
16331           DisplayMoveError(_("Could not parse move"));
16332         }
16333       }
16334 }
16335
16336 void
16337 DisplayMove (int moveNumber)
16338 {
16339     char message[MSG_SIZ];
16340     char res[MSG_SIZ];
16341     char cpThinkOutput[MSG_SIZ];
16342
16343     if(appData.noGUI) return; // [HGM] fast: suppress display of moves
16344
16345     if (moveNumber == forwardMostMove - 1 ||
16346         gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16347
16348         safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
16349
16350         if (strchr(cpThinkOutput, '\n')) {
16351             *strchr(cpThinkOutput, '\n') = NULLCHAR;
16352         }
16353     } else {
16354         *cpThinkOutput = NULLCHAR;
16355     }
16356
16357     /* [AS] Hide thinking from human user */
16358     if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
16359         *cpThinkOutput = NULLCHAR;
16360         if( thinkOutput[0] != NULLCHAR ) {
16361             int i;
16362
16363             for( i=0; i<=hiddenThinkOutputState; i++ ) {
16364                 cpThinkOutput[i] = '.';
16365             }
16366             cpThinkOutput[i] = NULLCHAR;
16367             hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
16368         }
16369     }
16370
16371     if (moveNumber == forwardMostMove - 1 &&
16372         gameInfo.resultDetails != NULL) {
16373         if (gameInfo.resultDetails[0] == NULLCHAR) {
16374           snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
16375         } else {
16376           snprintf(res, MSG_SIZ, " {%s} %s",
16377                     T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
16378         }
16379     } else {
16380         res[0] = NULLCHAR;
16381     }
16382
16383     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
16384         DisplayMessage(res, cpThinkOutput);
16385     } else {
16386       snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
16387                 WhiteOnMove(moveNumber) ? " " : ".. ",
16388                 parseList[moveNumber], res);
16389         DisplayMessage(message, cpThinkOutput);
16390     }
16391 }
16392
16393 void
16394 DisplayComment (int moveNumber, char *text)
16395 {
16396     char title[MSG_SIZ];
16397
16398     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
16399       safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
16400     } else {
16401       snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
16402               WhiteOnMove(moveNumber) ? " " : ".. ",
16403               parseList[moveNumber]);
16404     }
16405     if (text != NULL && (appData.autoDisplayComment || commentUp))
16406         CommentPopUp(title, text);
16407 }
16408
16409 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
16410  * might be busy thinking or pondering.  It can be omitted if your
16411  * gnuchess is configured to stop thinking immediately on any user
16412  * input.  However, that gnuchess feature depends on the FIONREAD
16413  * ioctl, which does not work properly on some flavors of Unix.
16414  */
16415 void
16416 Attention (ChessProgramState *cps)
16417 {
16418 #if ATTENTION
16419     if (!cps->useSigint) return;
16420     if (appData.noChessProgram || (cps->pr == NoProc)) return;
16421     switch (gameMode) {
16422       case MachinePlaysWhite:
16423       case MachinePlaysBlack:
16424       case TwoMachinesPlay:
16425       case IcsPlayingWhite:
16426       case IcsPlayingBlack:
16427       case AnalyzeMode:
16428       case AnalyzeFile:
16429         /* Skip if we know it isn't thinking */
16430         if (!cps->maybeThinking) return;
16431         if (appData.debugMode)
16432           fprintf(debugFP, "Interrupting %s\n", cps->which);
16433         InterruptChildProcess(cps->pr);
16434         cps->maybeThinking = FALSE;
16435         break;
16436       default:
16437         break;
16438     }
16439 #endif /*ATTENTION*/
16440 }
16441
16442 int
16443 CheckFlags ()
16444 {
16445     if (whiteTimeRemaining <= 0) {
16446         if (!whiteFlag) {
16447             whiteFlag = TRUE;
16448             if (appData.icsActive) {
16449                 if (appData.autoCallFlag &&
16450                     gameMode == IcsPlayingBlack && !blackFlag) {
16451                   SendToICS(ics_prefix);
16452                   SendToICS("flag\n");
16453                 }
16454             } else {
16455                 if (blackFlag) {
16456                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
16457                 } else {
16458                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
16459                     if (appData.autoCallFlag) {
16460                         GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
16461                         return TRUE;
16462                     }
16463                 }
16464             }
16465         }
16466     }
16467     if (blackTimeRemaining <= 0) {
16468         if (!blackFlag) {
16469             blackFlag = TRUE;
16470             if (appData.icsActive) {
16471                 if (appData.autoCallFlag &&
16472                     gameMode == IcsPlayingWhite && !whiteFlag) {
16473                   SendToICS(ics_prefix);
16474                   SendToICS("flag\n");
16475                 }
16476             } else {
16477                 if (whiteFlag) {
16478                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
16479                 } else {
16480                     if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
16481                     if (appData.autoCallFlag) {
16482                         GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
16483                         return TRUE;
16484                     }
16485                 }
16486             }
16487         }
16488     }
16489     return FALSE;
16490 }
16491
16492 void
16493 CheckTimeControl ()
16494 {
16495     if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
16496         gameMode == PlayFromGameFile || forwardMostMove == 0) return;
16497
16498     /*
16499      * add time to clocks when time control is achieved ([HGM] now also used for increment)
16500      */
16501     if ( !WhiteOnMove(forwardMostMove) ) {
16502         /* White made time control */
16503         lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
16504         whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
16505         /* [HGM] time odds: correct new time quota for time odds! */
16506                                             / WhitePlayer()->timeOdds;
16507         lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
16508     } else {
16509         lastBlack -= blackTimeRemaining;
16510         /* Black made time control */
16511         blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
16512                                             / WhitePlayer()->other->timeOdds;
16513         lastWhite = whiteTimeRemaining;
16514     }
16515 }
16516
16517 void
16518 DisplayBothClocks ()
16519 {
16520     int wom = gameMode == EditPosition ?
16521       !blackPlaysFirst : WhiteOnMove(currentMove);
16522     DisplayWhiteClock(whiteTimeRemaining, wom);
16523     DisplayBlackClock(blackTimeRemaining, !wom);
16524 }
16525
16526
16527 /* Timekeeping seems to be a portability nightmare.  I think everyone
16528    has ftime(), but I'm really not sure, so I'm including some ifdefs
16529    to use other calls if you don't.  Clocks will be less accurate if
16530    you have neither ftime nor gettimeofday.
16531 */
16532
16533 /* VS 2008 requires the #include outside of the function */
16534 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
16535 #include <sys/timeb.h>
16536 #endif
16537
16538 /* Get the current time as a TimeMark */
16539 void
16540 GetTimeMark (TimeMark *tm)
16541 {
16542 #if HAVE_GETTIMEOFDAY
16543
16544     struct timeval timeVal;
16545     struct timezone timeZone;
16546
16547     gettimeofday(&timeVal, &timeZone);
16548     tm->sec = (long) timeVal.tv_sec;
16549     tm->ms = (int) (timeVal.tv_usec / 1000L);
16550
16551 #else /*!HAVE_GETTIMEOFDAY*/
16552 #if HAVE_FTIME
16553
16554 // include <sys/timeb.h> / moved to just above start of function
16555     struct timeb timeB;
16556
16557     ftime(&timeB);
16558     tm->sec = (long) timeB.time;
16559     tm->ms = (int) timeB.millitm;
16560
16561 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
16562     tm->sec = (long) time(NULL);
16563     tm->ms = 0;
16564 #endif
16565 #endif
16566 }
16567
16568 /* Return the difference in milliseconds between two
16569    time marks.  We assume the difference will fit in a long!
16570 */
16571 long
16572 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
16573 {
16574     return 1000L*(tm2->sec - tm1->sec) +
16575            (long) (tm2->ms - tm1->ms);
16576 }
16577
16578
16579 /*
16580  * Code to manage the game clocks.
16581  *
16582  * In tournament play, black starts the clock and then white makes a move.
16583  * We give the human user a slight advantage if he is playing white---the
16584  * clocks don't run until he makes his first move, so it takes zero time.
16585  * Also, we don't account for network lag, so we could get out of sync
16586  * with GNU Chess's clock -- but then, referees are always right.
16587  */
16588
16589 static TimeMark tickStartTM;
16590 static long intendedTickLength;
16591
16592 long
16593 NextTickLength (long timeRemaining)
16594 {
16595     long nominalTickLength, nextTickLength;
16596
16597     if (timeRemaining > 0L && timeRemaining <= 10000L)
16598       nominalTickLength = 100L;
16599     else
16600       nominalTickLength = 1000L;
16601     nextTickLength = timeRemaining % nominalTickLength;
16602     if (nextTickLength <= 0) nextTickLength += nominalTickLength;
16603
16604     return nextTickLength;
16605 }
16606
16607 /* Adjust clock one minute up or down */
16608 void
16609 AdjustClock (Boolean which, int dir)
16610 {
16611     if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
16612     if(which) blackTimeRemaining += 60000*dir;
16613     else      whiteTimeRemaining += 60000*dir;
16614     DisplayBothClocks();
16615     adjustedClock = TRUE;
16616 }
16617
16618 /* Stop clocks and reset to a fresh time control */
16619 void
16620 ResetClocks ()
16621 {
16622     (void) StopClockTimer();
16623     if (appData.icsActive) {
16624         whiteTimeRemaining = blackTimeRemaining = 0;
16625     } else if (searchTime) {
16626         whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16627         blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16628     } else { /* [HGM] correct new time quote for time odds */
16629         whiteTC = blackTC = fullTimeControlString;
16630         whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
16631         blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
16632     }
16633     if (whiteFlag || blackFlag) {
16634         DisplayTitle("");
16635         whiteFlag = blackFlag = FALSE;
16636     }
16637     lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
16638     DisplayBothClocks();
16639     adjustedClock = FALSE;
16640 }
16641
16642 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
16643
16644 /* Decrement running clock by amount of time that has passed */
16645 void
16646 DecrementClocks ()
16647 {
16648     long timeRemaining;
16649     long lastTickLength, fudge;
16650     TimeMark now;
16651
16652     if (!appData.clockMode) return;
16653     if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
16654
16655     GetTimeMark(&now);
16656
16657     lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16658
16659     /* Fudge if we woke up a little too soon */
16660     fudge = intendedTickLength - lastTickLength;
16661     if (fudge < 0 || fudge > FUDGE) fudge = 0;
16662
16663     if (WhiteOnMove(forwardMostMove)) {
16664         if(whiteNPS >= 0) lastTickLength = 0;
16665         timeRemaining = whiteTimeRemaining -= lastTickLength;
16666         if(timeRemaining < 0 && !appData.icsActive) {
16667             GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
16668             if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
16669                 whiteStartMove = forwardMostMove; whiteTC = nextSession;
16670                 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
16671             }
16672         }
16673         DisplayWhiteClock(whiteTimeRemaining - fudge,
16674                           WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16675     } else {
16676         if(blackNPS >= 0) lastTickLength = 0;
16677         timeRemaining = blackTimeRemaining -= lastTickLength;
16678         if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
16679             GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
16680             if(suddenDeath) {
16681                 blackStartMove = forwardMostMove;
16682                 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
16683             }
16684         }
16685         DisplayBlackClock(blackTimeRemaining - fudge,
16686                           !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16687     }
16688     if (CheckFlags()) return;
16689
16690     if(twoBoards) { // count down secondary board's clocks as well
16691         activePartnerTime -= lastTickLength;
16692         partnerUp = 1;
16693         if(activePartner == 'W')
16694             DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
16695         else
16696             DisplayBlackClock(activePartnerTime, TRUE);
16697         partnerUp = 0;
16698     }
16699
16700     tickStartTM = now;
16701     intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
16702     StartClockTimer(intendedTickLength);
16703
16704     /* if the time remaining has fallen below the alarm threshold, sound the
16705      * alarm. if the alarm has sounded and (due to a takeback or time control
16706      * with increment) the time remaining has increased to a level above the
16707      * threshold, reset the alarm so it can sound again.
16708      */
16709
16710     if (appData.icsActive && appData.icsAlarm) {
16711
16712         /* make sure we are dealing with the user's clock */
16713         if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
16714                ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
16715            )) return;
16716
16717         if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
16718             alarmSounded = FALSE;
16719         } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
16720             PlayAlarmSound();
16721             alarmSounded = TRUE;
16722         }
16723     }
16724 }
16725
16726
16727 /* A player has just moved, so stop the previously running
16728    clock and (if in clock mode) start the other one.
16729    We redisplay both clocks in case we're in ICS mode, because
16730    ICS gives us an update to both clocks after every move.
16731    Note that this routine is called *after* forwardMostMove
16732    is updated, so the last fractional tick must be subtracted
16733    from the color that is *not* on move now.
16734 */
16735 void
16736 SwitchClocks (int newMoveNr)
16737 {
16738     long lastTickLength;
16739     TimeMark now;
16740     int flagged = FALSE;
16741
16742     GetTimeMark(&now);
16743
16744     if (StopClockTimer() && appData.clockMode) {
16745         lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16746         if (!WhiteOnMove(forwardMostMove)) {
16747             if(blackNPS >= 0) lastTickLength = 0;
16748             blackTimeRemaining -= lastTickLength;
16749            /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16750 //         if(pvInfoList[forwardMostMove].time == -1)
16751                  pvInfoList[forwardMostMove].time =               // use GUI time
16752                       (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
16753         } else {
16754            if(whiteNPS >= 0) lastTickLength = 0;
16755            whiteTimeRemaining -= lastTickLength;
16756            /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16757 //         if(pvInfoList[forwardMostMove].time == -1)
16758                  pvInfoList[forwardMostMove].time =
16759                       (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
16760         }
16761         flagged = CheckFlags();
16762     }
16763     forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
16764     CheckTimeControl();
16765
16766     if (flagged || !appData.clockMode) return;
16767
16768     switch (gameMode) {
16769       case MachinePlaysBlack:
16770       case MachinePlaysWhite:
16771       case BeginningOfGame:
16772         if (pausing) return;
16773         break;
16774
16775       case EditGame:
16776       case PlayFromGameFile:
16777       case IcsExamining:
16778         return;
16779
16780       default:
16781         break;
16782     }
16783
16784     if (searchTime) { // [HGM] st: set clock of player that has to move to max time
16785         if(WhiteOnMove(forwardMostMove))
16786              whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16787         else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16788     }
16789
16790     tickStartTM = now;
16791     intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16792       whiteTimeRemaining : blackTimeRemaining);
16793     StartClockTimer(intendedTickLength);
16794 }
16795
16796
16797 /* Stop both clocks */
16798 void
16799 StopClocks ()
16800 {
16801     long lastTickLength;
16802     TimeMark now;
16803
16804     if (!StopClockTimer()) return;
16805     if (!appData.clockMode) return;
16806
16807     GetTimeMark(&now);
16808
16809     lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16810     if (WhiteOnMove(forwardMostMove)) {
16811         if(whiteNPS >= 0) lastTickLength = 0;
16812         whiteTimeRemaining -= lastTickLength;
16813         DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
16814     } else {
16815         if(blackNPS >= 0) lastTickLength = 0;
16816         blackTimeRemaining -= lastTickLength;
16817         DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
16818     }
16819     CheckFlags();
16820 }
16821
16822 /* Start clock of player on move.  Time may have been reset, so
16823    if clock is already running, stop and restart it. */
16824 void
16825 StartClocks ()
16826 {
16827     (void) StopClockTimer(); /* in case it was running already */
16828     DisplayBothClocks();
16829     if (CheckFlags()) return;
16830
16831     if (!appData.clockMode) return;
16832     if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
16833
16834     GetTimeMark(&tickStartTM);
16835     intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16836       whiteTimeRemaining : blackTimeRemaining);
16837
16838    /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
16839     whiteNPS = blackNPS = -1;
16840     if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
16841        || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
16842         whiteNPS = first.nps;
16843     if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
16844        || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
16845         blackNPS = first.nps;
16846     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
16847         whiteNPS = second.nps;
16848     if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
16849         blackNPS = second.nps;
16850     if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
16851
16852     StartClockTimer(intendedTickLength);
16853 }
16854
16855 char *
16856 TimeString (long ms)
16857 {
16858     long second, minute, hour, day;
16859     char *sign = "";
16860     static char buf[32];
16861
16862     if (ms > 0 && ms <= 9900) {
16863       /* convert milliseconds to tenths, rounding up */
16864       double tenths = floor( ((double)(ms + 99L)) / 100.00 );
16865
16866       snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
16867       return buf;
16868     }
16869
16870     /* convert milliseconds to seconds, rounding up */
16871     /* use floating point to avoid strangeness of integer division
16872        with negative dividends on many machines */
16873     second = (long) floor(((double) (ms + 999L)) / 1000.0);
16874
16875     if (second < 0) {
16876         sign = "-";
16877         second = -second;
16878     }
16879
16880     day = second / (60 * 60 * 24);
16881     second = second % (60 * 60 * 24);
16882     hour = second / (60 * 60);
16883     second = second % (60 * 60);
16884     minute = second / 60;
16885     second = second % 60;
16886
16887     if (day > 0)
16888       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
16889               sign, day, hour, minute, second);
16890     else if (hour > 0)
16891       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
16892     else
16893       snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
16894
16895     return buf;
16896 }
16897
16898
16899 /*
16900  * This is necessary because some C libraries aren't ANSI C compliant yet.
16901  */
16902 char *
16903 StrStr (char *string, char *match)
16904 {
16905     int i, length;
16906
16907     length = strlen(match);
16908
16909     for (i = strlen(string) - length; i >= 0; i--, string++)
16910       if (!strncmp(match, string, length))
16911         return string;
16912
16913     return NULL;
16914 }
16915
16916 char *
16917 StrCaseStr (char *string, char *match)
16918 {
16919     int i, j, length;
16920
16921     length = strlen(match);
16922
16923     for (i = strlen(string) - length; i >= 0; i--, string++) {
16924         for (j = 0; j < length; j++) {
16925             if (ToLower(match[j]) != ToLower(string[j]))
16926               break;
16927         }
16928         if (j == length) return string;
16929     }
16930
16931     return NULL;
16932 }
16933
16934 #ifndef _amigados
16935 int
16936 StrCaseCmp (char *s1, char *s2)
16937 {
16938     char c1, c2;
16939
16940     for (;;) {
16941         c1 = ToLower(*s1++);
16942         c2 = ToLower(*s2++);
16943         if (c1 > c2) return 1;
16944         if (c1 < c2) return -1;
16945         if (c1 == NULLCHAR) return 0;
16946     }
16947 }
16948
16949
16950 int
16951 ToLower (int c)
16952 {
16953     return isupper(c) ? tolower(c) : c;
16954 }
16955
16956
16957 int
16958 ToUpper (int c)
16959 {
16960     return islower(c) ? toupper(c) : c;
16961 }
16962 #endif /* !_amigados    */
16963
16964 char *
16965 StrSave (char *s)
16966 {
16967   char *ret;
16968
16969   if ((ret = (char *) malloc(strlen(s) + 1)))
16970     {
16971       safeStrCpy(ret, s, strlen(s)+1);
16972     }
16973   return ret;
16974 }
16975
16976 char *
16977 StrSavePtr (char *s, char **savePtr)
16978 {
16979     if (*savePtr) {
16980         free(*savePtr);
16981     }
16982     if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
16983       safeStrCpy(*savePtr, s, strlen(s)+1);
16984     }
16985     return(*savePtr);
16986 }
16987
16988 char *
16989 PGNDate ()
16990 {
16991     time_t clock;
16992     struct tm *tm;
16993     char buf[MSG_SIZ];
16994
16995     clock = time((time_t *)NULL);
16996     tm = localtime(&clock);
16997     snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
16998             tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
16999     return StrSave(buf);
17000 }
17001
17002
17003 char *
17004 PositionToFEN (int move, char *overrideCastling)
17005 {
17006     int i, j, fromX, fromY, toX, toY;
17007     int whiteToPlay;
17008     char buf[MSG_SIZ];
17009     char *p, *q;
17010     int emptycount;
17011     ChessSquare piece;
17012
17013     whiteToPlay = (gameMode == EditPosition) ?
17014       !blackPlaysFirst : (move % 2 == 0);
17015     p = buf;
17016
17017     /* Piece placement data */
17018     for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17019         if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
17020         emptycount = 0;
17021         for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
17022             if (boards[move][i][j] == EmptySquare) {
17023                 emptycount++;
17024             } else { ChessSquare piece = boards[move][i][j];
17025                 if (emptycount > 0) {
17026                     if(emptycount<10) /* [HGM] can be >= 10 */
17027                         *p++ = '0' + emptycount;
17028                     else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17029                     emptycount = 0;
17030                 }
17031                 if(PieceToChar(piece) == '+') {
17032                     /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
17033                     *p++ = '+';
17034                     piece = (ChessSquare)(DEMOTED piece);
17035                 }
17036                 *p++ = PieceToChar(piece);
17037                 if(p[-1] == '~') {
17038                     /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
17039                     p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
17040                     *p++ = '~';
17041                 }
17042             }
17043         }
17044         if (emptycount > 0) {
17045             if(emptycount<10) /* [HGM] can be >= 10 */
17046                 *p++ = '0' + emptycount;
17047             else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17048             emptycount = 0;
17049         }
17050         *p++ = '/';
17051     }
17052     *(p - 1) = ' ';
17053
17054     /* [HGM] print Crazyhouse or Shogi holdings */
17055     if( gameInfo.holdingsWidth ) {
17056         *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
17057         q = p;
17058         for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
17059             piece = boards[move][i][BOARD_WIDTH-1];
17060             if( piece != EmptySquare )
17061               for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
17062                   *p++ = PieceToChar(piece);
17063         }
17064         for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
17065             piece = boards[move][BOARD_HEIGHT-i-1][0];
17066             if( piece != EmptySquare )
17067               for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
17068                   *p++ = PieceToChar(piece);
17069         }
17070
17071         if( q == p ) *p++ = '-';
17072         *p++ = ']';
17073         *p++ = ' ';
17074     }
17075
17076     /* Active color */
17077     *p++ = whiteToPlay ? 'w' : 'b';
17078     *p++ = ' ';
17079
17080   if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
17081     while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
17082   } else {
17083   if(nrCastlingRights) {
17084      q = p;
17085      if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
17086        /* [HGM] write directly from rights */
17087            if(boards[move][CASTLING][2] != NoRights &&
17088               boards[move][CASTLING][0] != NoRights   )
17089                 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
17090            if(boards[move][CASTLING][2] != NoRights &&
17091               boards[move][CASTLING][1] != NoRights   )
17092                 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
17093            if(boards[move][CASTLING][5] != NoRights &&
17094               boards[move][CASTLING][3] != NoRights   )
17095                 *p++ = boards[move][CASTLING][3] + AAA;
17096            if(boards[move][CASTLING][5] != NoRights &&
17097               boards[move][CASTLING][4] != NoRights   )
17098                 *p++ = boards[move][CASTLING][4] + AAA;
17099      } else {
17100
17101         /* [HGM] write true castling rights */
17102         if( nrCastlingRights == 6 ) {
17103             int q, k=0;
17104             if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
17105                boards[move][CASTLING][2] != NoRights  ) k = 1, *p++ = 'K';
17106             q = (boards[move][CASTLING][1] == BOARD_LEFT &&
17107                  boards[move][CASTLING][2] != NoRights  );
17108             if(gameInfo.variant == VariantSChess) { // for S-Chess, indicate all vrgin backrank pieces
17109                 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_RGHT]; // count white held pieces
17110                 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
17111                     if((boards[move][0][i] != WhiteKing || k+q == 0) &&
17112                         boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
17113             }
17114             if(q) *p++ = 'Q';
17115             k = 0;
17116             if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
17117                boards[move][CASTLING][5] != NoRights  ) k = 1, *p++ = 'k';
17118             q = (boards[move][CASTLING][4] == BOARD_LEFT &&
17119                  boards[move][CASTLING][5] != NoRights  );
17120             if(gameInfo.variant == VariantSChess) {
17121                 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_LEFT-1]; // count black held pieces
17122                 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
17123                     if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
17124                         boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
17125             }
17126             if(q) *p++ = 'q';
17127         }
17128      }
17129      if (q == p) *p++ = '-'; /* No castling rights */
17130      *p++ = ' ';
17131   }
17132
17133   if(gameInfo.variant != VariantShogi    && gameInfo.variant != VariantXiangqi &&
17134      gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
17135     /* En passant target square */
17136     if (move > backwardMostMove) {
17137         fromX = moveList[move - 1][0] - AAA;
17138         fromY = moveList[move - 1][1] - ONE;
17139         toX = moveList[move - 1][2] - AAA;
17140         toY = moveList[move - 1][3] - ONE;
17141         if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
17142             toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
17143             boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
17144             fromX == toX) {
17145             /* 2-square pawn move just happened */
17146             *p++ = toX + AAA;
17147             *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17148         } else {
17149             *p++ = '-';
17150         }
17151     } else if(move == backwardMostMove) {
17152         // [HGM] perhaps we should always do it like this, and forget the above?
17153         if((signed char)boards[move][EP_STATUS] >= 0) {
17154             *p++ = boards[move][EP_STATUS] + AAA;
17155             *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17156         } else {
17157             *p++ = '-';
17158         }
17159     } else {
17160         *p++ = '-';
17161     }
17162     *p++ = ' ';
17163   }
17164   }
17165
17166     /* [HGM] find reversible plies */
17167     {   int i = 0, j=move;
17168
17169         if (appData.debugMode) { int k;
17170             fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
17171             for(k=backwardMostMove; k<=forwardMostMove; k++)
17172                 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
17173
17174         }
17175
17176         while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
17177         if( j == backwardMostMove ) i += initialRulePlies;
17178         sprintf(p, "%d ", i);
17179         p += i>=100 ? 4 : i >= 10 ? 3 : 2;
17180     }
17181     /* Fullmove number */
17182     sprintf(p, "%d", (move / 2) + 1);
17183
17184     return StrSave(buf);
17185 }
17186
17187 Boolean
17188 ParseFEN (Board board, int *blackPlaysFirst, char *fen)
17189 {
17190     int i, j;
17191     char *p, c;
17192     int emptycount, virgin[BOARD_FILES];
17193     ChessSquare piece;
17194
17195     p = fen;
17196
17197     /* [HGM] by default clear Crazyhouse holdings, if present */
17198     if(gameInfo.holdingsWidth) {
17199        for(i=0; i<BOARD_HEIGHT; i++) {
17200            board[i][0]             = EmptySquare; /* black holdings */
17201            board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
17202            board[i][1]             = (ChessSquare) 0; /* black counts */
17203            board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
17204        }
17205     }
17206
17207     /* Piece placement data */
17208     for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17209         j = 0;
17210         for (;;) {
17211             if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
17212                 if (*p == '/') p++;
17213                 emptycount = gameInfo.boardWidth - j;
17214                 while (emptycount--)
17215                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17216                 break;
17217 #if(BOARD_FILES >= 10)
17218             } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
17219                 p++; emptycount=10;
17220                 if (j + emptycount > gameInfo.boardWidth) return FALSE;
17221                 while (emptycount--)
17222                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17223 #endif
17224             } else if (isdigit(*p)) {
17225                 emptycount = *p++ - '0';
17226                 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
17227                 if (j + emptycount > gameInfo.boardWidth) return FALSE;
17228                 while (emptycount--)
17229                         board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17230             } else if (*p == '+' || isalpha(*p)) {
17231                 if (j >= gameInfo.boardWidth) return FALSE;
17232                 if(*p=='+') {
17233                     piece = CharToPiece(*++p);
17234                     if(piece == EmptySquare) return FALSE; /* unknown piece */
17235                     piece = (ChessSquare) (PROMOTED piece ); p++;
17236                     if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
17237                 } else piece = CharToPiece(*p++);
17238
17239                 if(piece==EmptySquare) return FALSE; /* unknown piece */
17240                 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
17241                     piece = (ChessSquare) (PROMOTED piece);
17242                     if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
17243                     p++;
17244                 }
17245                 board[i][(j++)+gameInfo.holdingsWidth] = piece;
17246             } else {
17247                 return FALSE;
17248             }
17249         }
17250     }
17251     while (*p == '/' || *p == ' ') p++;
17252
17253     /* [HGM] look for Crazyhouse holdings here */
17254     while(*p==' ') p++;
17255     if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
17256         if(*p == '[') p++;
17257         if(*p == '-' ) p++; /* empty holdings */ else {
17258             if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
17259             /* if we would allow FEN reading to set board size, we would   */
17260             /* have to add holdings and shift the board read so far here   */
17261             while( (piece = CharToPiece(*p) ) != EmptySquare ) {
17262                 p++;
17263                 if((int) piece >= (int) BlackPawn ) {
17264                     i = (int)piece - (int)BlackPawn;
17265                     i = PieceToNumber((ChessSquare)i);
17266                     if( i >= gameInfo.holdingsSize ) return FALSE;
17267                     board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
17268                     board[BOARD_HEIGHT-1-i][1]++;       /* black counts   */
17269                 } else {
17270                     i = (int)piece - (int)WhitePawn;
17271                     i = PieceToNumber((ChessSquare)i);
17272                     if( i >= gameInfo.holdingsSize ) return FALSE;
17273                     board[i][BOARD_WIDTH-1] = piece;    /* white holdings */
17274                     board[i][BOARD_WIDTH-2]++;          /* black holdings */
17275                 }
17276             }
17277         }
17278         if(*p == ']') p++;
17279     }
17280
17281     while(*p == ' ') p++;
17282
17283     /* Active color */
17284     c = *p++;
17285     if(appData.colorNickNames) {
17286       if( c == appData.colorNickNames[0] ) c = 'w'; else
17287       if( c == appData.colorNickNames[1] ) c = 'b';
17288     }
17289     switch (c) {
17290       case 'w':
17291         *blackPlaysFirst = FALSE;
17292         break;
17293       case 'b':
17294         *blackPlaysFirst = TRUE;
17295         break;
17296       default:
17297         return FALSE;
17298     }
17299
17300     /* [HGM] We NO LONGER ignore the rest of the FEN notation */
17301     /* return the extra info in global variiables             */
17302
17303     /* set defaults in case FEN is incomplete */
17304     board[EP_STATUS] = EP_UNKNOWN;
17305     for(i=0; i<nrCastlingRights; i++ ) {
17306         board[CASTLING][i] =
17307             gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
17308     }   /* assume possible unless obviously impossible */
17309     if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
17310     if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
17311     if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
17312                                   && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
17313     if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
17314     if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
17315     if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
17316                                   && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
17317     FENrulePlies = 0;
17318
17319     while(*p==' ') p++;
17320     if(nrCastlingRights) {
17321       if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
17322       if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
17323           /* castling indicator present, so default becomes no castlings */
17324           for(i=0; i<nrCastlingRights; i++ ) {
17325                  board[CASTLING][i] = NoRights;
17326           }
17327       }
17328       while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
17329              (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess) &&
17330              ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
17331              ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth)   ) {
17332         int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
17333
17334         for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
17335             if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
17336             if(board[0             ][i] == WhiteKing) whiteKingFile = i;
17337         }
17338         if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
17339             whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
17340         if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
17341                                      && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
17342         if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
17343                                      && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
17344         switch(c) {
17345           case'K':
17346               for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
17347               board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
17348               board[CASTLING][2] = whiteKingFile;
17349               if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
17350               if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
17351               break;
17352           case'Q':
17353               for(i=BOARD_LEFT;  i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
17354               board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
17355               board[CASTLING][2] = whiteKingFile;
17356               if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
17357               if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
17358               break;
17359           case'k':
17360               for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
17361               board[CASTLING][3] = i != blackKingFile ? i : NoRights;
17362               board[CASTLING][5] = blackKingFile;
17363               if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
17364               if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
17365               break;
17366           case'q':
17367               for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
17368               board[CASTLING][4] = i != blackKingFile ? i : NoRights;
17369               board[CASTLING][5] = blackKingFile;
17370               if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
17371               if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
17372           case '-':
17373               break;
17374           default: /* FRC castlings */
17375               if(c >= 'a') { /* black rights */
17376                   if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
17377                   for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
17378                     if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
17379                   if(i == BOARD_RGHT) break;
17380                   board[CASTLING][5] = i;
17381                   c -= AAA;
17382                   if(board[BOARD_HEIGHT-1][c] <  BlackPawn ||
17383                      board[BOARD_HEIGHT-1][c] >= BlackKing   ) break;
17384                   if(c > i)
17385                       board[CASTLING][3] = c;
17386                   else
17387                       board[CASTLING][4] = c;
17388               } else { /* white rights */
17389                   if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
17390                   for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
17391                     if(board[0][i] == WhiteKing) break;
17392                   if(i == BOARD_RGHT) break;
17393                   board[CASTLING][2] = i;
17394                   c -= AAA - 'a' + 'A';
17395                   if(board[0][c] >= WhiteKing) break;
17396                   if(c > i)
17397                       board[CASTLING][0] = c;
17398                   else
17399                       board[CASTLING][1] = c;
17400               }
17401         }
17402       }
17403       for(i=0; i<nrCastlingRights; i++)
17404         if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
17405       if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = virgin[i];
17406     if (appData.debugMode) {
17407         fprintf(debugFP, "FEN castling rights:");
17408         for(i=0; i<nrCastlingRights; i++)
17409         fprintf(debugFP, " %d", board[CASTLING][i]);
17410         fprintf(debugFP, "\n");
17411     }
17412
17413       while(*p==' ') p++;
17414     }
17415
17416     /* read e.p. field in games that know e.p. capture */
17417     if(gameInfo.variant != VariantShogi    && gameInfo.variant != VariantXiangqi &&
17418        gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
17419       if(*p=='-') {
17420         p++; board[EP_STATUS] = EP_NONE;
17421       } else {
17422          char c = *p++ - AAA;
17423
17424          if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
17425          if(*p >= '0' && *p <='9') p++;
17426          board[EP_STATUS] = c;
17427       }
17428     }
17429
17430
17431     if(sscanf(p, "%d", &i) == 1) {
17432         FENrulePlies = i; /* 50-move ply counter */
17433         /* (The move number is still ignored)    */
17434     }
17435
17436     return TRUE;
17437 }
17438
17439 void
17440 EditPositionPasteFEN (char *fen)
17441 {
17442   if (fen != NULL) {
17443     Board initial_position;
17444
17445     if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
17446       DisplayError(_("Bad FEN position in clipboard"), 0);
17447       return ;
17448     } else {
17449       int savedBlackPlaysFirst = blackPlaysFirst;
17450       EditPositionEvent();
17451       blackPlaysFirst = savedBlackPlaysFirst;
17452       CopyBoard(boards[0], initial_position);
17453       initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
17454       EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
17455       DisplayBothClocks();
17456       DrawPosition(FALSE, boards[currentMove]);
17457     }
17458   }
17459 }
17460
17461 static char cseq[12] = "\\   ";
17462
17463 Boolean
17464 set_cont_sequence (char *new_seq)
17465 {
17466     int len;
17467     Boolean ret;
17468
17469     // handle bad attempts to set the sequence
17470         if (!new_seq)
17471                 return 0; // acceptable error - no debug
17472
17473     len = strlen(new_seq);
17474     ret = (len > 0) && (len < sizeof(cseq));
17475     if (ret)
17476       safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
17477     else if (appData.debugMode)
17478       fprintf(debugFP, "Invalid continuation sequence \"%s\"  (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
17479     return ret;
17480 }
17481
17482 /*
17483     reformat a source message so words don't cross the width boundary.  internal
17484     newlines are not removed.  returns the wrapped size (no null character unless
17485     included in source message).  If dest is NULL, only calculate the size required
17486     for the dest buffer.  lp argument indicats line position upon entry, and it's
17487     passed back upon exit.
17488 */
17489 int
17490 wrap (char *dest, char *src, int count, int width, int *lp)
17491 {
17492     int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
17493
17494     cseq_len = strlen(cseq);
17495     old_line = line = *lp;
17496     ansi = len = clen = 0;
17497
17498     for (i=0; i < count; i++)
17499     {
17500         if (src[i] == '\033')
17501             ansi = 1;
17502
17503         // if we hit the width, back up
17504         if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
17505         {
17506             // store i & len in case the word is too long
17507             old_i = i, old_len = len;
17508
17509             // find the end of the last word
17510             while (i && src[i] != ' ' && src[i] != '\n')
17511             {
17512                 i--;
17513                 len--;
17514             }
17515
17516             // word too long?  restore i & len before splitting it
17517             if ((old_i-i+clen) >= width)
17518             {
17519                 i = old_i;
17520                 len = old_len;
17521             }
17522
17523             // extra space?
17524             if (i && src[i-1] == ' ')
17525                 len--;
17526
17527             if (src[i] != ' ' && src[i] != '\n')
17528             {
17529                 i--;
17530                 if (len)
17531                     len--;
17532             }
17533
17534             // now append the newline and continuation sequence
17535             if (dest)
17536                 dest[len] = '\n';
17537             len++;
17538             if (dest)
17539                 strncpy(dest+len, cseq, cseq_len);
17540             len += cseq_len;
17541             line = cseq_len;
17542             clen = cseq_len;
17543             continue;
17544         }
17545
17546         if (dest)
17547             dest[len] = src[i];
17548         len++;
17549         if (!ansi)
17550             line++;
17551         if (src[i] == '\n')
17552             line = 0;
17553         if (src[i] == 'm')
17554             ansi = 0;
17555     }
17556     if (dest && appData.debugMode)
17557     {
17558         fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
17559             count, width, line, len, *lp);
17560         show_bytes(debugFP, src, count);
17561         fprintf(debugFP, "\ndest: ");
17562         show_bytes(debugFP, dest, len);
17563         fprintf(debugFP, "\n");
17564     }
17565     *lp = dest ? line : old_line;
17566
17567     return len;
17568 }
17569
17570 // [HGM] vari: routines for shelving variations
17571 Boolean modeRestore = FALSE;
17572
17573 void
17574 PushInner (int firstMove, int lastMove)
17575 {
17576         int i, j, nrMoves = lastMove - firstMove;
17577
17578         // push current tail of game on stack
17579         savedResult[storedGames] = gameInfo.result;
17580         savedDetails[storedGames] = gameInfo.resultDetails;
17581         gameInfo.resultDetails = NULL;
17582         savedFirst[storedGames] = firstMove;
17583         savedLast [storedGames] = lastMove;
17584         savedFramePtr[storedGames] = framePtr;
17585         framePtr -= nrMoves; // reserve space for the boards
17586         for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
17587             CopyBoard(boards[framePtr+i], boards[firstMove+i]);
17588             for(j=0; j<MOVE_LEN; j++)
17589                 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
17590             for(j=0; j<2*MOVE_LEN; j++)
17591                 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
17592             timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
17593             timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
17594             pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
17595             pvInfoList[firstMove+i-1].depth = 0;
17596             commentList[framePtr+i] = commentList[firstMove+i];
17597             commentList[firstMove+i] = NULL;
17598         }
17599
17600         storedGames++;
17601         forwardMostMove = firstMove; // truncate game so we can start variation
17602 }
17603
17604 void
17605 PushTail (int firstMove, int lastMove)
17606 {
17607         if(appData.icsActive) { // only in local mode
17608                 forwardMostMove = currentMove; // mimic old ICS behavior
17609                 return;
17610         }
17611         if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
17612
17613         PushInner(firstMove, lastMove);
17614         if(storedGames == 1) GreyRevert(FALSE);
17615         if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
17616 }
17617
17618 void
17619 PopInner (Boolean annotate)
17620 {
17621         int i, j, nrMoves;
17622         char buf[8000], moveBuf[20];
17623
17624         ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
17625         storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
17626         nrMoves = savedLast[storedGames] - currentMove;
17627         if(annotate) {
17628                 int cnt = 10;
17629                 if(!WhiteOnMove(currentMove))
17630                   snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
17631                 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
17632                 for(i=currentMove; i<forwardMostMove; i++) {
17633                         if(WhiteOnMove(i))
17634                           snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
17635                         else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
17636                         strcat(buf, moveBuf);
17637                         if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
17638                         if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
17639                 }
17640                 strcat(buf, ")");
17641         }
17642         for(i=1; i<=nrMoves; i++) { // copy last variation back
17643             CopyBoard(boards[currentMove+i], boards[framePtr+i]);
17644             for(j=0; j<MOVE_LEN; j++)
17645                 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
17646             for(j=0; j<2*MOVE_LEN; j++)
17647                 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
17648             timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
17649             timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
17650             pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
17651             if(commentList[currentMove+i]) free(commentList[currentMove+i]);
17652             commentList[currentMove+i] = commentList[framePtr+i];
17653             commentList[framePtr+i] = NULL;
17654         }
17655         if(annotate) AppendComment(currentMove+1, buf, FALSE);
17656         framePtr = savedFramePtr[storedGames];
17657         gameInfo.result = savedResult[storedGames];
17658         if(gameInfo.resultDetails != NULL) {
17659             free(gameInfo.resultDetails);
17660       }
17661         gameInfo.resultDetails = savedDetails[storedGames];
17662         forwardMostMove = currentMove + nrMoves;
17663 }
17664
17665 Boolean
17666 PopTail (Boolean annotate)
17667 {
17668         if(appData.icsActive) return FALSE; // only in local mode
17669         if(!storedGames) return FALSE; // sanity
17670         CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
17671
17672         PopInner(annotate);
17673         if(currentMove < forwardMostMove) ForwardEvent(); else
17674         HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
17675
17676         if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
17677         return TRUE;
17678 }
17679
17680 void
17681 CleanupTail ()
17682 {       // remove all shelved variations
17683         int i;
17684         for(i=0; i<storedGames; i++) {
17685             if(savedDetails[i])
17686                 free(savedDetails[i]);
17687             savedDetails[i] = NULL;
17688         }
17689         for(i=framePtr; i<MAX_MOVES; i++) {
17690                 if(commentList[i]) free(commentList[i]);
17691                 commentList[i] = NULL;
17692         }
17693         framePtr = MAX_MOVES-1;
17694         storedGames = 0;
17695 }
17696
17697 void
17698 LoadVariation (int index, char *text)
17699 {       // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
17700         char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
17701         int level = 0, move;
17702
17703         if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
17704         // first find outermost bracketing variation
17705         while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
17706             if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
17707                 if(*p == '{') wait = '}'; else
17708                 if(*p == '[') wait = ']'; else
17709                 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
17710                 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
17711             }
17712             if(*p == wait) wait = NULLCHAR; // closing ]} found
17713             p++;
17714         }
17715         if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
17716         if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
17717         end[1] = NULLCHAR; // clip off comment beyond variation
17718         ToNrEvent(currentMove-1);
17719         PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
17720         // kludge: use ParsePV() to append variation to game
17721         move = currentMove;
17722         ParsePV(start, TRUE, TRUE);
17723         forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
17724         ClearPremoveHighlights();
17725         CommentPopDown();
17726         ToNrEvent(currentMove+1);
17727 }
17728
17729 void
17730 LoadTheme ()
17731 {
17732     char *p, *q, buf[MSG_SIZ];
17733     if(engineLine && engineLine[0]) { // a theme was selected from the listbox
17734         snprintf(buf, MSG_SIZ, "-theme %s", engineLine);
17735         ParseArgsFromString(buf);
17736         ActivateTheme(TRUE); // also redo colors
17737         return;
17738     }
17739     p = nickName;
17740     if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
17741     {
17742         int len;
17743         q = appData.themeNames;
17744         snprintf(buf, MSG_SIZ, "\"%s\"", nickName);
17745       if(appData.useBitmaps) {
17746         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt true -lbtf \"%s\" -dbtf \"%s\" -lbtm %d -dbtm %d",
17747                 appData.liteBackTextureFile, appData.darkBackTextureFile,
17748                 appData.liteBackTextureMode,
17749                 appData.darkBackTextureMode );
17750       } else {
17751         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt false -lsc %s -dsc %s",
17752                 Col2Text(2),   // lightSquareColor
17753                 Col2Text(3) ); // darkSquareColor
17754       }
17755       if(appData.useBorder) {
17756         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub true -border \"%s\"",
17757                 appData.border);
17758       } else {
17759         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub false");
17760       }
17761       if(appData.useFont) {
17762         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
17763                 appData.renderPiecesWithFont,
17764                 appData.fontToPieceTable,
17765                 Col2Text(9),    // appData.fontBackColorWhite
17766                 Col2Text(10) ); // appData.fontForeColorBlack
17767       } else {
17768         snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf false -pid \"%s\"",
17769                 appData.pieceDirectory);
17770         if(!appData.pieceDirectory[0])
17771           snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -wpc %s -bpc %s",
17772                 Col2Text(0),   // whitePieceColor
17773                 Col2Text(1) ); // blackPieceColor
17774       }
17775       snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -hsc %s -phc %s\n",
17776                 Col2Text(4),   // highlightSquareColor
17777                 Col2Text(5) ); // premoveHighlightColor
17778         appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
17779         if(insert != q) insert[-1] = NULLCHAR;
17780         snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
17781         if(q)   free(q);
17782     }
17783     ActivateTheme(FALSE);
17784 }