File: apply.c

package info (click to toggle)
pgn-extract 16.0-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 912 kB
  • ctags: 737
  • sloc: ansic: 8,857; makefile: 103
file content (1565 lines) | stat: -rw-r--r-- 42,936 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
/*
 *  Program: pgn-extract: a Portable Game Notation (PGN) extractor.
 *  Copyright (C) 1994-2005 David Barnes
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 1, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  David Barnes may be contacted as D.J.Barnes@kent.ac.uk
 *  http://www.cs.kent.ac.uk/people/staff/djb/
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "bool.h"
#include "mymalloc.h"
#include "defs.h"
#include "typedef.h"
#include "map.h"
#include "apply.h"
#include "tokens.h"
#include "taglist.h"
#include "output.h"
#include "lex.h"
#include "grammar.h"
#include "moves.h"
#include "eco.h"
#include "decode.h"
#include "hashing.h"

/* Define a positional search depth that should look at the
 * full length of a game.  This is used in play_moves().
 */
#define DEFAULT_POSITIONAL_DEPTH 300

	/* Prototypes of functions limited to this file. */
static Boolean position_matches(HashCode current_hash_value);
static Boolean play_moves(Game *game_details, Board *board, Move *moves,
		unsigned max_depth);
static Boolean apply_variations(const Game *game_details,const Board *board,
				Variation *variation);
static Boolean rewrite_variations(const Board *board,Variation *variation);
static Boolean rewrite_moves(Board *board,Move *moves);

	/* The English SAN piece characters. These are
	 * always used when building a FEN string, rather
	 * than using any language-dependent user settings.
	 */
static char SAN_piece_characters[NUM_PIECE_VALUES] = {
    '?', '?', 
    'P', 'N', 'B', 'R', 'Q', 'K'
};


    /* These letters may be changed via a call to set_output_piece_characters
     * with a string of the form "PNBRQK".
     * This would normally be done with the -Wsan argument.
     */
static const char *output_piece_characters[NUM_PIECE_VALUES] = {
    "?", "?", 
    "P", "N", "B", "R", "Q", "K"
};

    /* letters should contain a string of the form: "PNBRQK" */
void set_output_piece_characters(const char *letters)
{
    if(letters == NULL){
        fprintf(GlobalState.logfile,
		"NULL string passed to set_output_piece_characters.\n");
    }
    else{
	Piece piece;
	int piece_index;
        for(piece_index = 0, piece = PAWN; piece <= KING &&
					   letters[piece_index] != '\0'; piece++){
	    /* Check whether we have a single character piece, 
	     * or one of the form X+Y, where the piece is represented
	     * by the combination XY.
	     */
	    if(letters[piece_index+1] == '+'){
		/* A two-char piece. */
		static char double_char_piece[] = "XY";
		double_char_piece[0] = letters[piece_index];
		piece_index++;
		/* Skip the plus. */
		piece_index++;
		if(letters[piece_index] != '\0'){
		    double_char_piece[1] = letters[piece_index];
		    output_piece_characters[piece] = StringCopy(double_char_piece);
		    piece_index++;
		}
		else{
		    fprintf(GlobalState.logfile,
			    "Missing piece letter following + in -Wsan%s.\n",
			    letters);
		    exit(1);
		}
	    }
	    else{
		static char single_char_piece[] = "X";
		*single_char_piece = letters[piece_index];
		output_piece_characters[piece] = StringCopy(single_char_piece);
		piece_index++;
	    }
	}
	if(piece < NUM_PIECE_VALUES){
	    fprintf(GlobalState.logfile,
		    "Insufficient piece letters found with -Wsan%s.\n",
		    letters);
	    fprintf(GlobalState.logfile,
	            "The argument should be of the form -Wsan%s.\n",
		    "PNBRQK");
	    exit(1);
	}
	else if(letters[piece_index] != '\0'){
	    fprintf(GlobalState.logfile,
		    "Too many piece letters found with -Wsan%s.\n",
		    letters);
	    fprintf(GlobalState.logfile,
	            "The argument should be of the form -Wsan%s.\n",
		    "PNBRQK");
	    exit(1);
	}
	else{
	    /* Ok. */
	}
    }
}

char *
StringCopy(const char *str)
{   char *result;
    unsigned len = strlen(str);

    result = MallocOrDie(len+1);
    strcpy(result,str);
    return result;
}

	/* Allocate space for a new board. */
static Board *
allocate_new_board(void)
{   
    return (Board *) MallocOrDie(sizeof(Board));
}

	/* Free the board space. */
static void
free_board(Board *board)
{
    (void) free((void *)board);
}

static Piece
is_FEN_piece(char c)
{   Piece piece = EMPTY;

    switch(c){
	case 'K': case 'k':
	    piece = KING;
	    break;
	case 'Q': case 'q':
	    piece = QUEEN;
	    break;
	case 'R': case 'r':
	    piece = ROOK;
	    break;
	case 'N': case 'n':
	    piece = KNIGHT;
	    break;
	case 'B': case 'b':
	    piece = BISHOP;
	    break;
	case 'P': case 'p':
	    piece = PAWN;
	    break;
    }
    return piece;
}

	/* Return the SAN letter associated with the given piece. */
char
SAN_piece_letter(Piece piece)
{
    if(piece >= 0 && piece < NUM_PIECE_VALUES){
        return SAN_piece_characters[piece];
    }
    else{
        return '?';
    }
}

	/* Return the SAN letter for the given Piece. */
char
coloured_piece_to_SAN_letter(Piece coloured_piece)
{   Piece piece = EXTRACT_PIECE(coloured_piece);
    char letter = SAN_piece_letter(piece);
    if(EXTRACT_COLOUR(coloured_piece) == BLACK){
	letter = tolower(letter);
    }
    return letter;
}

	/* Set up the board from the FEN string passed as
	 * argument.
	 * This has the form:
	 *	Forsythe string of the setup position.
	 *	w/b - colour to move.
	 *	castling permissions.
	 *	en-passant square.
	 *	half-moves since pawn move/piece capture.
	 *	move number.
	 */
Board *
new_fen_board(const char *fen)
{   Board *new_board = allocate_new_board();
    /* Start with a clear board. */
    static const Board initial_board = {
	{ { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF},
	  { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF},
	  { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF}
	},
	/* Who to move next. */
	WHITE,
	/* Move number. */
	1,
	/* Castling rights. */
	FALSE, FALSE, FALSE, FALSE,
	/* Initial king positions. */
	'e',FIRSTRANK,
	'e',LASTRANK,
	/* En Passant rights. */
	FALSE, 0, 0,
	/* Initial hash value. */
	0ul,
      };
    Rank rank = LASTRANK;
    Col col;
    const char *fen_char = fen;
    Boolean Ok = TRUE;
    /* In some circumstances we will try to parse the game data,
     * even if there are errors.
     */
    Boolean try_to_parse_game = FALSE;

    /* Reset the contents of the new board. */
    *new_board = initial_board;
    /* Extract the piece positions. */
    col = FIRSTCOL;
    while(Ok && (*fen_char != ' ') && (*fen_char != '\0') &&
		(rank >= FIRSTRANK)){
	Piece piece;
	char ch = *fen_char;
	Colour colour;

	if((piece = is_FEN_piece(ch)) != EMPTY){
	    if(isupper((int) ch)){
		colour = WHITE;
	    }
	    else{
		colour = BLACK;
	    }
	    if(col <= LASTCOL){
		new_board->board[RankConvert(rank)][ColConvert(col)] = 
				MAKE_COLOURED_PIECE(colour,piece);
		if(piece == KING){
		    if(colour == WHITE){
			new_board->WKingCol = col;
			new_board->WKingRank = rank;
		    }
		    else{
			new_board->BKingCol = col;
			new_board->BKingRank = rank;
		    }
		}
		col++;
		fen_char++;
	    }
	    else{
		Ok = FALSE;
	    }
	}
	else if(isdigit((int) ch)){
	   if(('1' <= ch) && (ch <= '8')){
	       col += ch - '0';
	       /* In filling up the remaining columns of a rank we will
		* temporarily exceed LASTCOL, but we expect the
		* next character to be '/' so that we reset.
		*/
	       if(col <= (LASTCOL+1)){
		   fen_char++;
	       }
	       else{
		   Ok = FALSE;
	       }
	   }
	   else{
	       Ok = FALSE;
	   }
	}
	else if(ch == '/'){
	    /* End of that rank. We should have completely filled the
	     * previous rank.
	     */
	    if(col == (LASTCOL+1)){
		col = FIRSTCOL;
		rank--;
		fen_char++;
	    }
	    else{
		Ok = FALSE;
	    }
	}
	else{
	    /* Unknown character. */
	    Ok = FALSE;
	}
    }
    /* As we don't print any error messages until the end of the function,
     * we don't need to guard everything with if(Ok).
     */
    if(*fen_char == ' '){
	/* Find out who is to move. */
	fen_char++;
    }
    else{
	Ok = FALSE;
    }
    if(*fen_char == 'w'){
	new_board->to_move = WHITE;
	fen_char++;
    }
    else if(*fen_char == 'b'){
	new_board->to_move = BLACK;
	fen_char++;
    }
    else{
	Ok = FALSE;
    }
    if(*fen_char == ' '){
	fen_char++;
    }
    else{
	Ok = FALSE;
    }
    /* Determine castling rights. */
    if(*fen_char == '-'){
	/* No castling rights -- default above. */
	new_board->WKingCastle = new_board->WQueenCastle =
	    new_board->BKingCastle = new_board->BQueenCastle = FALSE;
	fen_char++;
    }
    else{
	/* Check to make sure that this section isn't empty. */
	if(*fen_char == ' '){
	    Ok = FALSE;
	}
	if(*fen_char == 'K'){
	    new_board->WKingCastle = TRUE;
	    fen_char++;
	}
	if(*fen_char == 'Q'){
	    new_board->WQueenCastle = TRUE;
	    fen_char++;
	}
	if(*fen_char == 'k'){
	    new_board->BKingCastle = TRUE;
	    fen_char++;
	}
	if(*fen_char == 'q'){
	    new_board->BQueenCastle = TRUE;
	    fen_char++;
	}
    }
    if(*fen_char == ' '){
	fen_char++;
    }
    else{
	Ok = FALSE;
    }
    /* If we are ok to this point, try to make a best efforts approach
     * to handle the game, even if there are subsequent errors.
     */
    if(Ok){
       try_to_parse_game = TRUE;
    }
    /* Check for an en-passant square. */
    if(*fen_char == '-'){
	/* None. */
	fen_char++;
    }
    else if(is_col(*fen_char)){
	col = *fen_char;
	fen_char++;
	if(is_rank(*fen_char)){
	    rank = *fen_char;
	    fen_char++;
	    /* Make sure that the en-passant indicator is consistent
	     * with whose move it is.
	     */
	    if(((new_board->to_move == WHITE) && (rank == '6')) ||
		((new_board->to_move == BLACK) && (rank == '3'))){
		/* Consistent. */
		new_board->EnPassant = TRUE;
		new_board->ep_rank = rank;
		new_board->ep_col = col;
	    }
	    else{
		Ok = FALSE;
	    }
	}
	else{
	    Ok = FALSE;
	}
    }
    else{
	Ok = FALSE;
    }
    if(*fen_char == ' '){
	fen_char++;
    }
    else{
	Ok = FALSE;
    }
    /* Check for half-move count since last pawn move
     * or capture.
     * @@@ This value is not currently used.
     */
    if(isdigit((int) *fen_char)){
	fen_char++;
	while(isdigit((int) *fen_char)){
	    fen_char++;
	}
    }
    else{
	Ok = FALSE;
    }
    if(*fen_char == ' '){
	fen_char++;
    }
    else{
	Ok = FALSE;
    }
    /* Check for current move number. */
    if(isdigit((int) *fen_char)){
	unsigned move_number = 0;

	move_number = *fen_char-'0';
	fen_char++;
	while(isdigit((int) *fen_char)){
	    move_number = (move_number*10)+(*fen_char-'0');
	    fen_char++;
	}
	new_board->move_number = move_number;
    }
    else{
	Ok = FALSE;
    }
    /* Allow trailing space. */
    while(isspace((int) *fen_char)){
	fen_char++;
    }
    if(*fen_char != '\0'){
	Ok = FALSE;
    }
    if(Ok){
    }
    else{
	fprintf(GlobalState.logfile,"Illegal FEN string %s at %s",fen,fen_char);
	if(try_to_parse_game){
	    fprintf(GlobalState.logfile," Attempting to parse the game, anyway.");
	}
	else{
	    (void) free_board((void *)new_board);
	    new_board = NULL;
	}
	putc('\n',GlobalState.logfile);
    }
    return new_board;
}

	/* Set up a board structure for a new game.
	 * This involves placing the pieces in their initial positions,
	 * setting up castling and en-passant rights, and initialising
	 * the hash positions.
	 * If the fen argument is NULL then a completely new board is
	 * setup, otherwise the indicated FEN position is returned.
	 */
static Board *
new_game_board(const char *fen)
{   Board *new_board;
    static const Board initial_board =
      {
	{ { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF},
	  { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF},
	  { OFF,OFF,W(ROOK),W(KNIGHT),W(BISHOP),W(QUEEN),
			    W(KING),W(BISHOP),W(KNIGHT),W(ROOK),OFF,OFF},
	  { OFF,OFF,W(PAWN),W(PAWN),W(PAWN),W(PAWN),
			    W(PAWN),W(PAWN),W(PAWN),W(PAWN),OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,OFF,OFF},
	  { OFF,OFF,B(PAWN),B(PAWN),B(PAWN),B(PAWN),
			    B(PAWN),B(PAWN),B(PAWN),B(PAWN),OFF,OFF},
	  { OFF,OFF,B(ROOK),B(KNIGHT),B(BISHOP),B(QUEEN),
			    B(KING),B(BISHOP),B(KNIGHT),B(ROOK),OFF,OFF},
	  { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF},
	  { OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF}
	},
	/* Who to move next. */
	WHITE,
	/* Move number. */
	1,
	/* Castling rights. */
	TRUE, TRUE, TRUE, TRUE,
	/* Initial king positions. */
	'e',FIRSTRANK,
	'e',LASTRANK,
	/* En Passant rights. */
	FALSE, 0, 0,
	/* Initial hash value. */
	0ul,
      };
    /* Iterate over the columns. */
    Col col;

    if(fen != NULL){
	new_board = new_fen_board(fen);
    }
    /* Guard against failure of new_fen_board as well as the
     * normal game situation.
     */
    if((fen == NULL) || (new_board == NULL)){
	/* Use the initial board setup. */
	new_board = allocate_new_board();
	*new_board = initial_board;
    }

    /* Generate the hash value for the initial position. */
    for(col = FIRSTCOL; col <= LASTCOL; col++){
	Rank rank;

        for(rank = FIRSTRANK; rank <= LASTRANK; rank++){
	    /* Find the basic components. */
	    Piece coloured_piece = new_board->board[
				RankConvert(rank)][ColConvert(col)];
	    Piece piece = EXTRACT_PIECE(coloured_piece);
	    Colour colour = EXTRACT_COLOUR(coloured_piece);

	    if(coloured_piece != EMPTY){
		new_board->hash_value ^= HashLookup(col,rank,piece,colour);
	    }
	}
    }

    return new_board;
}

	/* Print out the current occupant of the given square. */
static void
print_square(Col col, Rank rank, const Board *board,FILE *outfp)
{   short r = RankConvert(rank);
    short c = ColConvert(col);

    Piece coloured_piece = board->board[r][c];
    switch(coloured_piece){
	case W(PAWN):
	case W(KNIGHT):
	case W(BISHOP):
	case W(ROOK):
	case W(QUEEN):
	case W(KING):
	case B(PAWN):
	case B(KNIGHT):
	case B(BISHOP):
	case B(ROOK): 
	case B(QUEEN):
	case B(KING):
	    putc(coloured_piece_to_SAN_letter(coloured_piece),outfp);
	    break;
	case EMPTY:
	    putc('.',outfp);
	    break;
	case OFF:
	    putc('?',outfp);
	    break;
	default:
	    fprintf(GlobalState.logfile,
		"Attempt to print illegal square %c%c in print_square.\n",
			col,rank);
	    break;
    }
}

	/* Print out the contents of the given board. */
static void
print_board(const Board *board,FILE *outfp)
{  Rank rank;
   Col col;

   for(rank = LASTRANK; rank >= FIRSTRANK; rank--){
       for(col = FIRSTCOL; col <= LASTCOL; col++){
	   print_square(col,rank,board,outfp);
       }
       putc('\n',outfp);
   }
   putc('\n',outfp);
}

#if INCLUDE_UNUSED_FUNCTIONS

	/* Check the consistency of the board. */
static void
check_board(const Board *board,const char *where)
{  Rank rank;
   Col col;

   for(rank = LASTRANK; rank >= FIRSTRANK; rank--){
       for(col = FIRSTCOL; col <= LASTCOL; col++){
	  short r = RankConvert(rank);
	  short c = ColConvert(col);

	  switch(board->board[r][c]){
	    case W(PAWN):
	    case W(KNIGHT):
	    case W(BISHOP):
	    case W(ROOK):
	    case W(QUEEN):
	    case W(KING):
	    case B(PAWN):
	    case B(KNIGHT):
	    case B(BISHOP):
	    case B(ROOK):
	    case B(QUEEN):
	    case B(KING):
	    case EMPTY: 
		break;
	    default:
		fprintf(GlobalState.logfile,
				"%s: Illegal square %c%c (%u %u) contains %d.\n",
				where,col,rank,r,c,board->board[r][c]);
		report_details(GlobalState.logfile);
		abort();
		break;
	  }
      }
   }
}
#endif

    /* Return the number of half moves that have been completed
     * on the board.
     */
static int
half_moves_played(const Board *board)
{
    int half_moves = 2*(board->move_number-1);
    if(board->to_move == BLACK){
        half_moves ++;
    }
    return half_moves;
}

	/* Implement move_details on the board.
	 * Return TRUE if the move is ok, FALSE otherwise.
	 * move_details is completed by the call to determine_move_details.
	 * Thereafter, it is safe to make the move on board.
	 */
static Boolean
apply_move(Colour colour,Move *move_details, Board *board)
{   /* Assume success. */
    Boolean Ok = TRUE;

    if(determine_move_details(colour,move_details,board)){
	Piece piece_to_move = move_details->piece_to_move;

	if(GlobalState.output_format == EPD){
	    move_details->epd = (char *)malloc(FEN_SPACE);
	    build_basic_EPD_string(board,move_details->epd);
	}

	make_move(move_details->from_col,move_details->from_rank,
			move_details->to_col,move_details->to_rank,
			piece_to_move,colour,board);
	/* See if there are any subsiduary actions. */
	switch(move_details->class){
	    case PAWN_MOVE:
	    case PIECE_MOVE:
	    case ENPASSANT_PAWN_MOVE:
		/* Nothing more to do. */
		break;
	    case PAWN_MOVE_WITH_PROMOTION:
		if(move_details->class == PAWN_MOVE_WITH_PROMOTION){
		    if(move_details->promoted_piece != EMPTY){
			/* Now make the promotion. */
			make_move(move_details->to_col,move_details->to_rank,
				  move_details->to_col,move_details->to_rank,
				  move_details->promoted_piece,colour,board);
		    }
		    else{
			Ok = FALSE;
		    }
		}
		break;
	case KINGSIDE_CASTLE:
	    /* Step the Rook to the left of the king. */
	    piece_to_move = ROOK;
	    make_move(LASTCOL,move_details->from_rank,move_details->to_col-1,
			    move_details->to_rank,
			    piece_to_move,colour,board);
	    break;
	case QUEENSIDE_CASTLE:
	    /* Step the Rook to the right of the king. */
	    piece_to_move = ROOK;
	    make_move(FIRSTCOL,move_details->from_rank,move_details->to_col+1,
			    move_details->to_rank,
			    piece_to_move,colour,board);
	    break;
	case UNKNOWN_MOVE:
	default:
	    Ok = FALSE;
	    break;
	}
	/* Determine whether or not this move gives check. */
	if(Ok){
	    move_details->check_status =
			king_is_in_check(board,OPPOSITE_COLOUR(colour));
	    if(move_details->check_status == CHECK){
		/* See whether it is CHECKMATE. */
		if(king_is_in_checkmate(OPPOSITE_COLOUR(colour),board)){
		    move_details->check_status = CHECKMATE;
		}
	    }
	    /* @@@ At this stage, it should be possible to determine/reset
	     * pawn move/capture info.
	     * if(piece_to_move == PAWN ||
	     *        move_details->captured_piece != EMPTY)
	     */
	}
    }
    else{
	Ok = FALSE;
    }
    return Ok;
}


	/* Play out the moves on the given board.
	 * game_details is updated with the final_ and cumulative_ hash
	 * values.
	 */
static Boolean
play_moves(Game *game_details, Board *board, Move *moves, unsigned max_depth)
{   Boolean game_ok = TRUE;
    /* Force a match if we aren't looking for positional variations. */
    Boolean game_matches = GlobalState.positional_variations?FALSE:TRUE;
    Move *next_move = moves;
    /* Keep track of the final ECO match. */
    EcoLog *eco_match = NULL;

    /* Try the initial board position for a match.
     * This is required because the game might have been set up
     * from a FEN string, rather than being the normal starting
     * position.
     */
    if(!game_matches && position_matches(board->hash_value)){
        game_matches = TRUE;
    }
    /* Keep going while the game is ok, and we have some more
     * moves and we haven't exceeded the search depth without finding
     * a match.
     */
    while(game_ok && (next_move != NULL) &&
		(game_matches || (board->move_number <= max_depth))){
	if(*(next_move->move) != '\0'){
	    /* See if there are any variations associated with this move. */
	    if((next_move->Variants != NULL) && GlobalState.keep_variations){
		game_matches |= apply_variations(game_details,board,
					    next_move->Variants);
	    }
	    /* Now try the main move. */
	    if(apply_move(board->to_move,next_move,board)){
	       /* Don't try for a positional match if we already have one. */
	       if(!game_matches && position_matches(board->hash_value)){
		   game_matches = TRUE;
	       }
	       /* Combine this hash value with the cumulative one. */
	       game_details->cumulative_hash_value += board->hash_value;
	       board->to_move = OPPOSITE_COLOUR(board->to_move);
	       if(board->to_move == WHITE){
		   board->move_number++;
	       }
	       if(GlobalState.add_ECO && !GlobalState.parsing_ECO_file){
		   int half_moves = half_moves_played(board);
		   EcoLog *entry = eco_matches(
			   board->hash_value,
			   game_details->cumulative_hash_value,
			   half_moves);
		   if(entry != NULL){
		       /* Consider keeping the match.
		        * Try to avoid spurious matches which become
			* more likely with larger ECO files and
			* the longer a game goes on.
			* Try to mitigate this partly by preferring
			* an ECO line of exactly the same length as
			* the current game line.
			*/
		       if(eco_match == NULL){
			   eco_match = entry;
		       }
		       else {
			   /* This logic prefers a longer match
			    * to a shorter, irrespective of whether
			    * either match is exact or not.
			    * This logic was followed in versions
			    * up to and including v13.8.
			    */
			   eco_match = entry;
		       }
		   }
	       }
	       next_move = next_move->next;
	    }
	    else{
		print_error_context(GlobalState.logfile);
		fprintf(GlobalState.logfile,
				"Failed to make move %u%s %s in the game:\n",
				board->move_number,
				(board->to_move == WHITE)?".":"...",
				next_move->move);
		print_board(board,GlobalState.logfile);
		report_details(GlobalState.logfile);
		game_ok = FALSE;
	    }
	}
	else{
	    /* An empty move. */
	    fprintf(GlobalState.logfile,
			"Internal error: Empty move in play_moves.\n");
	    report_details(GlobalState.logfile);
	    game_ok = FALSE;
	}
    }
    if(game_ok){
	if(eco_match != NULL){
	   /* Free any details of the old one. */
	   if(game_details->tags[ECO_TAG] != NULL){
	       (void) free((void *) game_details->tags[ECO_TAG]);
	       game_details->tags[ECO_TAG] = NULL;
	   }
	   if(game_details->tags[OPENING_TAG] != NULL){
	       (void) free((void *)game_details->tags[OPENING_TAG]);
	       game_details->tags[OPENING_TAG] = NULL;
	   }
	   if(game_details->tags[VARIATION_TAG] != NULL){
	       (void) free((void *)game_details->tags[VARIATION_TAG]);
	       game_details->tags[VARIATION_TAG] = NULL;
	   }
	   if(game_details->tags[SUB_VARIATION_TAG] != NULL){
	       (void) free((void *)game_details->tags[SUB_VARIATION_TAG]);
	       game_details->tags[SUB_VARIATION_TAG] = NULL;
	   }
	   /* Add in the new one. */
	   if(eco_match->ECO_tag != NULL){
	       game_details->tags[ECO_TAG] = StringCopy(eco_match->ECO_tag);
	   }
	   if(eco_match->Opening_tag != NULL){
	       game_details->tags[OPENING_TAG] = StringCopy(eco_match->Opening_tag);
	   }
	   if(eco_match->Variation_tag != NULL){
	       game_details->tags[VARIATION_TAG] =
				StringCopy(eco_match->Variation_tag);
	   }
	   if(eco_match->Sub_Variation_tag != NULL){
	       game_details->tags[SUB_VARIATION_TAG] =
				StringCopy(eco_match->Sub_Variation_tag);
	   }
	}
    }
    /* Fill in the hash value of the final position reached. */
    game_details->final_hash_value = board->hash_value;
    game_details->moves_ok = game_ok;
    if(!game_ok){
	/* Only return a match if it genuinely matched a variation
	 * in which we were interested.
	 */
	if(!GlobalState.positional_variations){
	    /* We can't have found a genuine match. */
	    game_matches = FALSE;
	}
    }
    return game_matches;
}

	/* Play out the moves of an ECO line on the given board.
	 * game_details is updated with the final_ and cumulative_ hash
	 * values.
	 */

static void
play_eco_moves(Game *game_details, Board *board,Move *moves)
{   Boolean game_ok = TRUE;
    Move *next_move = moves;

    /* Keep going while the game is ok, and we have some more
     * moves and we haven't exceeded the search depth without finding
     * a match.
     */
    while(game_ok && (next_move != NULL)){
	if(*(next_move->move) != '\0'){
	    /* Ignore variations. */
	    if(apply_move(board->to_move,next_move,board)){
	       /* Combine this hash value to the cumulative one. */
	       game_details->cumulative_hash_value += board->hash_value;
	       board->to_move = OPPOSITE_COLOUR(board->to_move);
	       if(board->to_move == WHITE){
		   board->move_number++;
	       }
	       next_move = next_move->next;
	    }
	    else{
		print_error_context(GlobalState.logfile);
		fprintf(GlobalState.logfile,
				"Failed to make move %u%s %s in the game:\n",
				board->move_number,
				(board->to_move == WHITE)?".":"...",
				next_move->move);
		print_board(board,GlobalState.logfile);
		report_details(GlobalState.logfile);
		game_ok = FALSE;
	    }
	}
	else{
	    /* An empty move. */
	    fprintf(GlobalState.logfile,
			"Internal error: Empty move in play_eco_moves.\n");
	    report_details(GlobalState.logfile);
	    game_ok = FALSE;
	}
    }
    /* Fill in the hash value of the final position reached. */
    game_details->final_hash_value = board->hash_value;
    game_details->moves_ok = game_ok;
}

	/* Play out a variation.
 	 * Return TRUE if the variation matches a position that
	 * we are looking for.
	 */
static Boolean
apply_variations(const Game *game_details,const Board *board,Variation *variation)
{   /* Force a match if we aren't looking for positional variations. */
    Boolean variation_matches = GlobalState.positional_variations?FALSE:TRUE;
    /* Allocate space for the copies.
     * Allocation is done, rather than relying on local copies in the body
     * of the loop because the recursive nature of this function has
     * resulted in stack overflow on the PC version.
     */
    Game *copy_game = (Game *) MallocOrDie(sizeof(*copy_game));
    Board *copy_board = allocate_new_board();

    while(variation != NULL){
	/* Work on the copies. */
	*copy_game = *game_details;
	*copy_board = *board;

	/* We only need one variation to match to declare a match.
	 * Play out the variation to its full depth, because we
	 * will want the full move information if the main line
	 * later matches.
	 */
	variation_matches |= play_moves(copy_game,copy_board,variation->moves,
					DEFAULT_POSITIONAL_DEPTH);
	variation = variation->next;
    }
    (void) free((void *)copy_game);
    (void) free_board((void *)copy_board);
    return variation_matches;
}

	/* game_details contains a complete move score.
	 * Try to apply each move on a new board.
	 * Store in number_or_moves the final value of
	 * board->move_number.
	 * Return TRUE if the game matches a variation that we are
	 * looking for.
	 */
Boolean
apply_move_list(Game *game_details,unsigned *number_of_moves)
{   Move *moves = game_details->moves;
    Board *board = new_game_board(game_details->tags[FEN_TAG]);
    Boolean game_matches;
    /* Set the default search depth. */
    unsigned max_depth = GlobalState.depth_of_positional_search;

    /* Ensure that we have a sensible search depth. */
    if(max_depth == 0){
	/* No positional variations specified. */
	max_depth = DEFAULT_POSITIONAL_DEPTH;
    }

    /* Start off the cumulative hash value. */
    game_details->cumulative_hash_value = 0;
    game_matches = play_moves(game_details,board,moves,max_depth);
    game_details->moves_checked = TRUE;
    /* Record how long the game was. */
    if(board->to_move == BLACK){
	*number_of_moves = board->move_number;
    }
    else{
	/* This move number hasn't been played. */
	*number_of_moves = board->move_number-1;
    }
    (void) free_board((void *)board);
    return game_matches;
}

	/* game_details contains a complete move score.
	 * Try to apply each move on a new board.
	 * Store in number_of_moves the length of the game.
	 * Return TRUE if the game is ok.
	 */
Boolean
apply_eco_move_list(Game *game_details,unsigned *number_of_half_moves)
{   Move *moves = game_details->moves;
    Board *board = new_game_board(game_details->tags[FEN_TAG]);

    /* Start off the cumulative hash value. */
    game_details->cumulative_hash_value = 0;
    play_eco_moves(game_details,board,moves);
    game_details->moves_checked = TRUE;
    /* Record how long the game was. */
    *number_of_half_moves = half_moves_played(board);
    (void) free_board((void *)board);
    return game_details->moves_ok;
}


	/* Return the string associated with the given piece. */
const char *
piece_str(Piece piece)
{
    if(piece >= 0 && piece < NUM_PIECE_VALUES){
        return output_piece_characters[piece];
    }
    else{
        return "?";
    }
}

	/* Rewrite move_details->move according to the details held
	 * within the structure and the current state of the board.
	 */
static Boolean
rewrite_SAN_string(Colour colour,Move *move_details, Board *board)
{   Boolean Ok = TRUE;

    if(move_details == NULL){
	/* Shouldn't happen. */
	fprintf(GlobalState.logfile,
		"Internal error: NULL move details in rewrite_SAN_string.\n");
	Ok = FALSE;
    }
    else if(move_details->move[0] == '\0'){
	/* Shouldn't happen. */
	fprintf(GlobalState.logfile,"Empty move in rewrite_SAN_string.\n");
	Ok = FALSE;
    }
    else{
	const unsigned char *move = move_details->move;
	MoveClass class = move_details->class;
	MovePair *move_list = NULL;
	Col to_col = move_details->to_col;
	Rank to_rank = move_details->to_rank;
	unsigned char new_move_str[MAX_MOVE_LEN+1] = "";

	switch(class){
	    case PAWN_MOVE:
	    case ENPASSANT_PAWN_MOVE:
	    case PAWN_MOVE_WITH_PROMOTION:
		move_list = find_pawn_moves(move_details->from_col,
						'0',to_col,to_rank,
						colour,board);
		break;
	    case PIECE_MOVE:
		switch(move_details->piece_to_move){
		    case KING:
			move_list = find_king_moves(to_col,to_rank,colour,board);
		        break;
		    case QUEEN:
			move_list = find_queen_moves(to_col,to_rank,colour,board);
			break;
		    case ROOK:
			move_list = find_rook_moves(to_col,to_rank,colour,board);
			break;
		    case KNIGHT:
			move_list = find_knight_moves(to_col,to_rank,colour,board);
			break;
		    case BISHOP:
			move_list = find_bishop_moves(to_col,to_rank,colour,board);
			break;
		    default:
			fprintf(GlobalState.logfile,"Unknown piece move %s\n",move);
			Ok = FALSE;
			break;
		}
		break;
	    case KINGSIDE_CASTLE:
	    case QUEENSIDE_CASTLE:
		/* No move list to prepare. */
		break;
	    case UNKNOWN_MOVE:
	    default:
		fprintf(GlobalState.logfile,
			"Unknown move class in rewrite_SAN_string(%d).\n",
			move_details->class);
		Ok = FALSE;
		break;
	}
	if(move_list != NULL){
	    move_list = exclude_checks(move_details->piece_to_move,colour,
						move_list,board);
	}
	if((move_list == NULL) && (class != KINGSIDE_CASTLE) &&
			(class != QUEENSIDE_CASTLE)){
	    Ok = FALSE;
	}
	/* We should now have enough information in move_details to compose a
	 * SAN string.
	 */
	if(Ok){
	    int new_move_index = 0;

	    switch(class){
		case PAWN_MOVE:
		case ENPASSANT_PAWN_MOVE:
		case PAWN_MOVE_WITH_PROMOTION:
		    /* See if we need to give the source column. */
		    if(move_details->captured_piece != EMPTY){
			new_move_str[new_move_index] = move_details->from_col;
			new_move_index++;
			new_move_str[new_move_index] = 'x';
			new_move_index++;
		    }
		    else if(move_list->next != NULL){
			new_move_str[new_move_index] = move_details->from_col;
			new_move_index++;
		    }
		    /* Add in the destination. */
		    new_move_str[new_move_index] = to_col;
		    new_move_index++;
		    new_move_str[new_move_index] = to_rank;
		    new_move_index++;
		    if(class == PAWN_MOVE_WITH_PROMOTION){
			const char *promoted_piece =
					piece_str(move_details->promoted_piece);
			new_move_str[new_move_index] = '=';
			new_move_index++;
			strcpy((char *) &new_move_str[new_move_index],
			       promoted_piece);
			new_move_index += strlen(promoted_piece);
		    }
		    new_move_str[new_move_index] = '\0';
		    break;
		case PIECE_MOVE:
		    {   const char *piece = piece_str(move_details->piece_to_move);
			strcpy((char *) &new_move_str[0],piece);
			new_move_index += strlen(piece);
			/* Check for the need to disambiguate. */
			if(move_list->next != NULL){
			    /* It is necessary.  Count how many times
			     * the from_ col and rank occur in the list
			     * of possibles in order to determine which to use
			     * for this purpose.
			     */
			    int col_times = 0, rank_times = 0;
			    MovePair *possible;
			    Col from_col = move_details->from_col;
			    Rank from_rank = move_details->from_rank;

			    for(possible = move_list; possible != NULL;
					    possible = possible->next){
				if(possible->from_col == from_col){
				    col_times++;
				}
				if(possible->from_rank == from_rank){
				    rank_times++;
				}
			    }
			    if(col_times == 1){
				/* Use the col. */
				new_move_str[new_move_index] = from_col;
				new_move_index++;
			    }
			    else if(rank_times == 1){
				/* Use the rank. */
				new_move_str[new_move_index] = from_rank;
				new_move_index++;
			    }
			    else{
				/* Use both. */
				new_move_str[new_move_index] = from_col;
				new_move_index++;
				new_move_str[new_move_index] = from_rank;
				new_move_index++;
			    }
			}
			/* See if a capture symbol is needed. */
			if(move_details->captured_piece != EMPTY){
			    new_move_str[new_move_index] = 'x';
			    new_move_index++;
			}
			/* Add in the destination. */
			new_move_str[new_move_index] = to_col;
			new_move_index++;
			new_move_str[new_move_index] = to_rank;
			new_move_index++;
			new_move_str[new_move_index] = '\0';
		    }
		    break;
		case KINGSIDE_CASTLE:
		    strcpy((char *) new_move_str,"O-O");
		    break;
		case QUEENSIDE_CASTLE:
		    strcpy((char *) new_move_str,"O-O-O");
		    break;
		case UNKNOWN_MOVE:
		default:
		    Ok = FALSE;
		    break;
	    }
	    if(Ok){
		if(move_details->check_status != NOCHECK){
		    if(move_details->check_status == CHECK){
			/* It isn't mate. */
			strcat((char *) new_move_str,"+");
		    }
		    else{
			if(GlobalState.output_format == CM){
			    strcat((char *) new_move_str,"++");
			}
			else{
			    strcat((char *) new_move_str,"#");
			}
		    }
		}
	    }
	    /* Update the move_details structure with the new string. */
	    strcpy((char *) move_details->move,
		   (const char *) new_move_str);
	}
	if(move_list != NULL){
	    free_move_pair_list(move_list);
	}
    }
    return Ok;
}

	/* Rewrite move_details->move and apply the move to board.
	 * Return TRUE if the move is ok, FALSE otherwise.
	 */
static Boolean
rewrite_move(Colour colour,Move *move_details, Board *board)
{   /* Assume success. */
    Boolean Ok = TRUE;

    if(rewrite_SAN_string(colour,move_details,board)){
	Piece piece_to_move = move_details->piece_to_move;

	make_move(move_details->from_col,move_details->from_rank,
			move_details->to_col,move_details->to_rank,
			piece_to_move,colour,board);
	/* See if there are any subsiduary actions. */
	switch(move_details->class){
	    case PAWN_MOVE:
	    case PIECE_MOVE:
	    case ENPASSANT_PAWN_MOVE:
		/* Nothing more to do. */
		break;
	    case PAWN_MOVE_WITH_PROMOTION:
		if(move_details->class == PAWN_MOVE_WITH_PROMOTION){
		    if(move_details->promoted_piece != EMPTY){
			/* @@@ Do promoted moves have '+' properly appended? */
			/* Now make the promotion. */
			make_move(move_details->to_col,move_details->to_rank,
				  move_details->to_col,move_details->to_rank,
				  move_details->promoted_piece,colour,board);
		    }
		    else{
			Ok = FALSE;
		    }
		}
		break;
	case KINGSIDE_CASTLE:
	    /* Step the Rook to the left of the king. */
	    piece_to_move = ROOK;
	    make_move(LASTCOL,move_details->from_rank,move_details->to_col-1,
			    move_details->to_rank,
			    piece_to_move,colour,board);
	    break;
	case QUEENSIDE_CASTLE:
	    /* Step the Rook to the right of the king. */
	    piece_to_move = ROOK;
	    make_move(FIRSTCOL,move_details->from_rank,move_details->to_col+1,
			    move_details->to_rank,
			    piece_to_move,colour,board);
	    break;
	case UNKNOWN_MOVE:
	default:
	    Ok = FALSE;
	    break;
	}
    }
    else{
	Ok = FALSE;
    }
    return Ok;
}

	/* Rewrite the list of moves by playing through the game. */
static Boolean
rewrite_moves(Board *board,Move *moves)
{   Boolean game_ok = TRUE;
    Move *next_move = moves;

    while(game_ok && (next_move != NULL)){
	if(*(next_move->move) != '\0'){
	    /* See if there are any variations associated with this move. */
	    if((next_move->Variants != NULL) &&
		    GlobalState.keep_variations &&
		    !rewrite_variations(board,next_move->Variants)){
		/* Something wrong with the variations. */
		game_ok = FALSE;
	    }
	    else if(rewrite_move(board->to_move,next_move,board)){
	       board->to_move = OPPOSITE_COLOUR(board->to_move);
	       next_move = next_move->next;
	       if(board->to_move == WHITE){
		   board->move_number++;
	       }
	    }
	    else{
		fprintf(GlobalState.logfile,
				"Failed to rewrite move %u%s %s in the game:\n",
				    board->move_number,
				    (board->to_move == WHITE)?".":"...",
				    next_move->move);
		report_details(GlobalState.logfile);
		print_board(board,GlobalState.logfile);
		game_ok = FALSE;
	    }
	}
	else{
	    /* An empty move. */
	    fprintf(GlobalState.logfile,
				"Internal error: Empty move in rewrite_moves.\n");
	    report_details(GlobalState.logfile);
	    game_ok = FALSE;
	}
    }
    return game_ok;
}

	/* Rewrite the list of variations.
 	 * Return TRUE if the variation are ok. a position that
	 */
static Boolean
rewrite_variations(const Board *board,Variation *variation)
{   Board *copy_board = allocate_new_board();
    Boolean variations_ok = TRUE;

    while((variation != NULL) && variations_ok){
	/* Work on the copy. */
	*copy_board = *board;

	variations_ok = rewrite_moves(copy_board,variation->moves);
	variation = variation->next;
    }
    (void) free_board((void *)copy_board);
    return variations_ok;
}

	/* moves contains a complete game score.
	 * Try to rewrite each move into SAN as it is played on a new board.
	 * Return the final Board position if the game was rewritten alright,
	 * NULL otherwise.
	 */
Board *
rewrite_game(Move *moves,const char *fen)
{   Board *board = new_game_board(fen);
    Boolean game_ok;

    game_ok = rewrite_moves(board,moves);
    if(!game_ok){
	(void) free_board((void *)board);
	board = NULL;
    }
    return board;
}


	/* Define a table to hold the positional hash codes of interest. */
#define MAX_CODE 53
static HashLog *codes_of_interest[MAX_CODE];

	/* move_details is a variation in which we are interested.
	 * Generate and store the hash value in codes_of_interest.
	 */
void
store_hash_value(Move *move_details,const char *fen)
{   Move *move = move_details;
    Board *board = new_game_board(fen);
    Boolean Ok = TRUE;

    while((move != NULL) && Ok){
        /* Reset print_move number if a variation was printed. */
	if(*(move->move) == '\0'){
	    /* A comment node, not a proper move. */
	   move = move->next;
	}
        else if(apply_move(board->to_move,move,board)){
	   board->to_move = OPPOSITE_COLOUR(board->to_move);
	   move = move->next;
	   if(board->to_move == WHITE){
	       board->move_number++;
	   }
	}
	else{
	    print_error_context(GlobalState.logfile);
	    fprintf(GlobalState.logfile,"Failed to make move %u%s %s\n",
				board->move_number,
				(board->to_move == WHITE)?".":"...",
			move->move);
	    Ok = FALSE;
	}
    }

    if(!Ok){
	exit(1);
    }
    else{
	HashLog *entry = (HashLog *)MallocOrDie(sizeof(*entry));
	unsigned ix = board->hash_value % MAX_CODE;

	/* We don't include the cumulative hash value as the sequence
	 * of moves to reach this position is not important.
	 */
	entry->combined_hash_value = board->hash_value;
	/* Link it into the head at this index. */
	entry->next =  codes_of_interest[ix];
	codes_of_interest[ix] = entry;
    }
    (void) free_board((void *)board);
}

	/* Look in codes_of_interest for current_hash_value. */
static Boolean
position_matches(HashCode current_hash_value)
{   unsigned ix = current_hash_value % MAX_CODE;
    Boolean found = FALSE;
    HashLog *entry;

    for(entry = codes_of_interest[ix]; !found && (entry != NULL);
			entry = entry->next){
	/* We can test against just the position value as there is no
	 * cumulative_hash_value stored against these positions.
	 */
	if(entry->combined_hash_value == current_hash_value){
	    found = TRUE;
	}
    }
    return found;
}

    /* Build a basic EPD string from the given board. */
void
build_basic_EPD_string(const Board *board,char *epd)
{   Rank rank;
    int ix = 0;
    for(rank = LASTRANK; rank >= FIRSTRANK; rank--){
	Col col;
	int consecutive_spaces = 0;
	for(col = FIRSTCOL; col <= LASTCOL; col++){
	    int coloured_piece = board->board[RankConvert(rank)]
					     [ColConvert(col)];
	    if(coloured_piece != EMPTY){
		if(consecutive_spaces > 0){
		    epd[ix] = '0'+consecutive_spaces;
		    ix++;
		    consecutive_spaces = 0;
		}
		epd[ix] = coloured_piece_to_SAN_letter(coloured_piece);
		ix++;
	    }
	    else{
	        consecutive_spaces++;
	    }
	}
	if(consecutive_spaces > 0){
	    epd[ix] = '0'+consecutive_spaces;
	    ix++;
	}
	/* Terminate the row. */
	if(rank != FIRSTRANK){
	    epd[ix] = '/'; ix++;
	}
    }
    epd[ix] = ' '; ix++;
    epd[ix]  = '\0';
    epd[ix] = board->to_move == WHITE? 'w' : 'b'; ix++;
    epd[ix] = ' '; ix++;

    /* Castling details. */
    /* In case there are no castling rights. */
    epd[ix] = '-';
    if(board->WKingCastle){
        epd[ix] = 'K'; ix++;
    }
    if(board->WQueenCastle){
        epd[ix] = 'Q'; ix++;
    }
    if(board->BKingCastle){
        epd[ix] = 'k'; ix++;
    }
    if(board->BQueenCastle){
        epd[ix] = 'q'; ix++;
    }
    if(epd[ix] == '-'){
        ix++;
    }
    epd[ix] = ' '; ix++;

    /* Enpassant. */
    if(board->EnPassant){
        epd[ix] = board->ep_col; ix++;
        epd[ix] = board->ep_rank; ix++;
    }
    else{
	epd[ix] = '-'; ix++;
    }
    epd[ix] = '\0';
}