XBoard: deal with semantic differences in "post" between xboard and xshogi protocols
[gnushogi.git] / gnushogi / book.c
1 /*
2  * FILE: book.c
3  *
4  * ----------------------------------------------------------------------
5  * Copyright (c) 1993, 1994, 1995 Matthias Mutz
6  * Copyright (c) 1999 Michael Vanier and the Free Software Foundation
7  * Copyright (c) 2008, 2013, 2014 Yann Dirson and the Free Software Foundation
8  *
9  * GNU SHOGI is based on GNU CHESS
10  *
11  * Copyright (c) 1988, 1989, 1990 John Stanback
12  * Copyright (c) 1992 Free Software Foundation
13  *
14  * This file is part of GNU SHOGI.
15  *
16  * GNU Shogi is free software; you can redistribute it and/or modify it
17  * under the terms of the GNU General Public License as published by the
18  * Free Software Foundation; either version 3 of the License,
19  * or (at your option) any later version.
20  *
21  * GNU Shogi is distributed in the hope that it will be useful, but WITHOUT
22  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
23  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
24  * for more details.
25  *
26  * You should have received a copy of the GNU General Public License along
27  * with GNU Shogi; see the file COPYING. If not, see
28  * <http://www.gnu.org/licenses/>.
29  * ----------------------------------------------------------------------
30  *
31  */
32
33 #include "gnushogi.h"
34
35 #define O_BINARY 0
36
37 #if HAVE_UNISTD_H
38 /* Declarations of read(), write(), close(), and lseek(). */
39 #include <unistd.h>
40 #endif
41
42 #if HAVE_FCNTL_H
43 #include <fcntl.h>
44 #endif
45
46 #include "book.h"
47
48 unsigned booksize = BOOKSIZE;
49 unsigned short bookmaxply = BOOKMAXPLY;
50 unsigned bookcount = 0;
51
52 #ifdef BOOK
53 char *bookfile = BOOK;
54 #else
55 char *bookfile = NULL;
56 #endif
57
58 #ifdef BINBOOK
59 char *binbookfile = BINBOOK;
60 #else
61 char *binbookfile = NULL;
62 #endif
63
64 static char bmvstr[3][7];
65
66 static ULONG bhashbd;
67 static ULONG bhashkey;
68
69
70 /*
71  * Balgbr(f, t, flag)
72  *
73  * Generate move strings in different formats.
74  */
75
76 void
77 Balgbr(short f, short t, short flag)
78 {
79     short promoted = false;
80
81     if ((f & 0x80) != 0)
82     {
83         f &= 0x7f;
84         promoted = true;
85     }
86
87     if (f > NO_SQUARES)
88     {
89         short piece;
90         piece = f - NO_SQUARES;
91
92         if (f > (NO_SQUARES + NO_PIECES))
93             piece -= NO_PIECES;
94
95         flag = (dropmask | piece);
96     }
97
98     if ((t & 0x80) != 0)
99     {
100         flag |= promote;
101         t &= 0x7f;
102     }
103
104     if ((f == t) && ((f != 0) || (t != 0)))
105     {
106         /*
107          * error in algbr: FROM=TO=t
108          */
109
110         bmvstr[0][0] = bmvstr[1][0] = bmvstr[2][0] = '\0';
111     }
112     else
113     {
114         if ((flag & dropmask) != 0)
115         {
116             /* bmvstr[0]: P*3c bmvstr[1]: P'3c */
117             short piece = flag & pmask;
118             bmvstr[0][0] = pxx[piece];
119             bmvstr[0][1] = '*';
120             bmvstr[0][2] = COL_NAME(column(t));
121             bmvstr[0][3] = ROW_NAME(row(t));
122             bmvstr[0][4] = bmvstr[2][0] = '\0';
123             strcpy(bmvstr[1], bmvstr[0]);
124             bmvstr[1][1] = '\'';
125         }
126         else
127         {
128             if ((f != 0) || (t != 0))
129             {
130                 /* algebraic notation */
131                 /* bmvstr[0]: 7g7f bmvstr[1]:
132                  * (+)P7g7f(+) bmvstr[2]: (+)P7f(+) */
133                 bmvstr[0][0] = COL_NAME(column(f));
134                 bmvstr[0][1] = ROW_NAME(row(f));
135                 bmvstr[0][2] = COL_NAME(column(t));
136                 bmvstr[0][3] = ROW_NAME(row(t));
137                 bmvstr[0][4] = '\0';
138
139                 if (promoted)
140                 {
141                     bmvstr[1][0] = bmvstr[2][0] = '+';
142                     bmvstr[1][1] = bmvstr[2][1] = pxx[board[f]];
143                     strcpy(&bmvstr[1][2], &bmvstr[0][0]);
144                     strcpy(&bmvstr[2][2], &bmvstr[0][2]);
145                 }
146                 else
147                 {
148                     bmvstr[1][0] = bmvstr[2][0] = pxx[board[f]];
149                     strcpy(&bmvstr[1][1], &bmvstr[0][0]);
150                     strcpy(&bmvstr[2][1], &bmvstr[0][2]);
151                 }
152
153                 if (flag & promote)
154                 {
155                     strcat(bmvstr[0], "+");
156                     strcat(bmvstr[1], "+");
157                     strcat(bmvstr[2], "+");
158                 }
159             }
160             else
161             {
162                 bmvstr[0][0] = bmvstr[1][0] = bmvstr[2][0] = '\0';
163             }
164         }
165     }
166 }
167
168
169
170
171 #ifndef QUIETBOOKGEN
172 void
173 bkdisplay(char *s, int cnt, int moveno)
174 {
175     static short pnt;
176     struct leaf  *node;
177     int r, c, l;
178
179     pnt = TrPnt[2];
180     printf("matches = %d\n", cnt);
181     printf("inout move is :%s: move number %d side %s\n",
182             s, moveno / 2 + 1, (moveno & 1) ? "white" : "black");
183
184 #ifndef SEMIQUIETBOOKGEN
185     printf("legal moves are \n");
186
187     while (pnt < TrPnt[3])
188     {
189         node = &Tree[pnt++];
190
191         if (is_promoted[board[node->f]] )
192             Balgbr(node->f | 0x80, node->t, (short) node->flags);
193         else
194             Balgbr(node->f, node->t, (short) node->flags);
195
196         printf("%s %s %s\n",
197                bmvstr[0], bmvstr[1], bmvstr[2]);
198     }
199
200     printf("\n current board is\n");
201
202     for (r = (NO_ROWS - 1); r >= 0; r--)
203     {
204         for (c = 0; c <= (NO_COLS - 1); c++)
205         {
206             char pc;
207
208             l = locn(r, c);
209             pc = (is_promoted[board[l]] ? '+' : ' ');
210
211             if (color[l] == neutral)
212                 printf(" -");
213             else if (color[l] == black)
214                 printf("%c%c", pc, qxx[board[l]]);
215             else
216                 printf("%c%c", pc, pxx[board[l]]);
217         }
218
219         printf("\n");
220     }
221
222     printf("\n");
223     {
224         short color;
225
226         for (color = black; color <= white; color++)
227         {
228             short piece, c;
229
230             printf((color == black) ? "black " : "white ");
231
232             for (piece = pawn; piece <= king; piece++)
233             {
234                 if ((c = Captured[color][piece]))
235                     printf("%i%c ", c, pxx[piece]);
236             }
237
238             printf("\n");
239         };
240     }
241 #endif /* SEMIQUIETBOOKGEN */
242 }
243
244 #endif /* QUIETBOOKGEN */
245
246
247
248 /*
249  * BVerifyMove(s, mv, moveno)
250  *
251  * Compare the string 's' to the list of legal moves available for the
252  * opponent. If a match is found, make the move on the board.
253  */
254
255 int
256 BVerifyMove(char *s, unsigned short *mv, int moveno)
257 {
258     static short pnt, tempb, tempc, tempsf, tempst, cnt;
259     static struct leaf xnode;
260     struct leaf  *node;
261
262     *mv = 0;
263     cnt = 0;
264     MoveList(opponent, 2, -2, true);
265     pnt = TrPnt[2];
266
267     while (pnt < TrPnt[3])
268     {
269         node = &Tree[pnt++];
270
271         if (is_promoted[board[node->f]] )
272             Balgbr(node->f | 0x80, node->t, (short) node->flags);
273         else
274             Balgbr(node->f, node->t, (short) node->flags);
275
276         if (strcmp(s, bmvstr[0]) == 0 || strcmp(s, bmvstr[1]) == 0 ||
277             strcmp(s, bmvstr[2]) == 0)
278         {
279             cnt++;
280             xnode = *node;
281         }
282     }
283
284     if (cnt == 1)
285     {
286         short blockable;
287
288         MakeMove(opponent, &xnode, &tempb,
289                  &tempc, &tempsf, &tempst, &INCscore);
290
291         if (SqAttacked(PieceList[opponent][0], computer, &blockable))
292         {
293             UnmakeMove(opponent, &xnode, &tempb, &tempc, &tempsf, &tempst);
294             /* Illegal move in check */
295 #if !defined QUIETBOOKGEN
296             puts("Illegal move (in check): %s");
297             bkdisplay(s, cnt, moveno);
298 #endif
299             return false;
300         }
301         else
302         {
303             *mv = (xnode.f << 8) | xnode.t;
304
305             if (is_promoted[board[xnode.t]] )
306                 Balgbr(xnode.f | 0x80, xnode.t, false);
307             else
308                 Balgbr(xnode.f, xnode.t, false);
309
310             return true;
311         }
312     }
313
314     /* Illegal move */
315 #if !defined QUIETBOOKGEN
316     printf("Illegal move (no match): %s\n", s);
317     bkdisplay(s, cnt, moveno);
318 #endif
319     return false;
320 }
321
322
323
324
325 /*
326  * RESET()
327  *
328  * Reset the board and other variables to start a new game.
329  *
330  */
331
332 void
333 RESET(void)
334 {
335     short l;
336
337     flag.illegal = flag.mate = flag.quit
338         = flag.reverse = flag.bothsides = flag.onemove = flag.force
339         = false;
340
341     flag.post &= xboard; /* [HGM] xboard: do not clear in XBoard mode */
342
343     flag.material = flag.coords = flag.hash = flag.easy
344         = flag.beep = flag.rcptr
345         = true;
346
347     flag.stars = flag.shade = flag.back = flag.musttimeout = false;
348     flag.gamein = false;
349     GenCnt   = 0;
350     GameCnt  = 0;
351     CptrFlag[0] = TesujiFlag[0] = false;
352     opponent = black;
353     computer = white;
354
355     for (l = 0; l < NO_SQUARES; l++)
356     {
357         board[l]   = Stboard[l];
358         color[l]   = Stcolor[l];
359         Mvboard[l] = 0;
360     }
361
362     ClearCaptured();
363     InitializeStats();
364     hashbd = hashkey = 0;
365 }
366
367
368
369 static
370 int
371 Vparse (FILE * fd, USHORT *mv, USHORT *flags, int moveno)
372 {
373     int c, i;
374     char s[255];
375
376     *flags = 0;
377
378     while (true)
379     {
380         while (((c = getc(fd)) == ' ')
381                || (c == '!') || (c == '/') || (c == '\n'));
382
383         if (c == '(')
384         {
385             /* amount of time spent for the last move */
386             while (((c = getc(fd)) != ')') && (c != EOF));
387
388             if (c == ')')
389             {
390                 while (((c = getc(fd)) == ' ') || (c == '\n'));
391             }
392         }
393
394         if (c == '[')
395         {
396             /* comment for the actual game */
397             while (((c = getc(fd))) != ']' && (c != EOF));
398
399             if (c == ']')
400             {
401                 while (((c = getc(fd))) == ' ' || (c == '\n'));
402             }
403         }
404
405         if (c == '\r')
406             continue;
407
408         if (c == '#')
409         {
410             /* comment */
411             do
412             {
413                 c = getc(fd);
414
415                 if (c == '\r')
416                     continue;
417                 /* goes to end of line */
418
419                 if (c == '\n')
420                     return 0;
421
422                 if (c == EOF)
423                     return -1;
424             }
425             while (true);
426         }
427
428         s[i = 0] = (char) c;
429
430         while ((c >= '0') && (c <= '9'))
431         {
432             c = getc(fd);
433             s[++i] = (char) c;
434         }
435
436         if (c == '.')
437         {
438             while (((c = getc(fd)) == ' ') || (c == '.') || (c == '\n'));
439             s[i = 0] = (char) c;
440         }
441
442         while (((c = getc(fd)) != '?') && (c != '!') && (c != ' ')
443                && (c != '(') && (c != '\n') && (c != '\t') && (c != EOF))
444         {
445             if (c == '\r')
446                 continue;
447
448             if ((c != 'x') && (c != '-') && (c != ',')
449                 && (c != ';') && (c != '='))
450             {
451                 s[++i] = (char) c;
452             }
453         }
454
455         s[++i] = '\0';
456
457         if (c == '(')
458         {
459             while (((c = getc(fd)) != ')') && (c != EOF));
460
461             if (c == ')')
462                 c = getc(fd);
463         }
464
465         if (c == EOF)
466             return -1;
467
468         if (s[0] == '#')
469         {
470             while ((c != '\n') && (c != EOF))
471                 c = getc(fd);
472
473             if (c == EOF)
474                 return -1;
475             else
476                 return 0;
477         }
478
479         if (strcmp(s, "draw") == 0)
480             continue;
481         else if (strcmp(s, "1-0") == 0)
482             continue;
483         else if (strcmp(s, "0-1") == 0)
484             continue;
485         else if (strcmp(s, "Resigns") == 0)
486             continue;
487         else if (strcmp(s, "Resigns.") == 0)
488             continue;
489         else if (strcmp(s, "Sennichite") == 0)
490             continue;
491         else if (strcmp(s, "Sennichite.") == 0)
492             continue;
493         else if (strcmp(s, "Jishogi") == 0)
494             continue;
495         else if (strcmp(s, "Jishogi.") == 0)
496             continue;
497
498         bhashkey = hashkey;
499         bhashbd  = hashbd;
500
501         i = BVerifyMove(s, mv, moveno);
502
503         if (c == '?')
504         {
505             /* Bad move, not for the program to play */
506             *flags |= BADMOVE;  /* Flag it ! */
507             while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
508         }
509 #ifdef EASY_OPENINGS
510         else if (c == '~')
511         {
512             /* Do not use by computer */
513             *flags |= BADMOVE;  /* Flag it ! */
514
515             while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
516         }
517 #endif
518         else if (c == '!')
519         {
520             /* Good move */
521             *flags |= GOODMOVE; /* Flag it ! */
522
523             while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
524         }
525         else if (c == '\r')
526         {
527             c = getc(fd);
528         }
529
530         if (c == '(' )
531             while (((c = getc(fd)) != ')') && (c != EOF));
532
533         if (!i)
534         {
535             /* flush to start of next */
536             while (((c = getc(fd)) != '#') && (c != EOF));
537
538             if (c == EOF)
539             {
540                 return -1;
541             }
542             else
543             {
544                 ungetc(c, fd);
545                 return i;
546             }
547         }
548
549         return i;
550     }
551 }
552
553
554 static struct gdxadmin ADMIN;
555 struct gdxadmin B;
556 static struct gdxdata DATA;
557
558 /* lts(l) returns most significant 16 bits of l */
559
560 #if SIZEOF_LONG == 8  /* 64-bit long i.e. 8 bytes */
561 #  define lts(x) (USHORT)(((x >> 48) & 0xfffe) | side)
562 #else
563 #  if defined USE_LTSIMP
564 static USHORT ltsimp(long x)
565 {
566     USHORT n;
567     n = (((x >> 16) & 0xfffe));
568     return n;
569 }
570 #    define lts(x) (USHORT)(ltsimp(x) | side)
571 #  else
572 #    define lts(x) (USHORT)(((x >> 16)&0xfffe) | side)
573 #  endif
574 #endif
575
576
577 /* #define HashValue(l) lts(l) */
578 #define HashValue(l) (USHORT)(l & 0xffff)
579
580
581 static int gfd;
582 static ULONG currentoffset;
583
584
585 #define MAXOFFSET(B) ((B.booksize - 1) * sizeof_gdxdata + sizeof_gdxadmin)
586
587 #define HashOffset(hashkey, B) \
588 { \
589   currentoffset = ((ULONG)hashkey % B.booksize) \
590     * sizeof_gdxdata + sizeof_gdxadmin; \
591 }
592
593
594 #define NextOffset(B) \
595 { \
596   currentoffset += sizeof_gdxdata; \
597   if (currentoffset > B.maxoffset) \
598     currentoffset = sizeof_gdxadmin; \
599 }
600
601
602 #define WriteAdmin() \
603 { \
604   lseek(gfd, 0, 0); \
605   write(gfd, (char *)&ADMIN, sizeof_gdxadmin); \
606 }
607
608 #define WriteData() \
609 { \
610   if (mustwrite ) \
611   { \
612     lseek(gfd, currentoffset, 0); \
613     write(gfd, (char *)&DATA, sizeof_gdxdata); \
614     mustwrite = false; \
615   } \
616 }
617
618 static int ReadAdmin(void)
619 {
620     lseek(gfd, 0, 0);
621     return (sizeof_gdxadmin == read(gfd, (char *)&ADMIN, sizeof_gdxadmin));
622 }
623
624 static int ReadData(struct gdxdata *DATA)
625 {
626     lseek(gfd, currentoffset, 0);
627     return (sizeof_gdxdata == read(gfd, (char *)DATA, sizeof_gdxdata));
628 }
629
630
631 /*
632  * GetOpenings()
633  *
634  * CHECKME: is this still valid esp. wrt gnushogi.book?
635  *
636  * Read in the Opening Book file and parse the algebraic notation for a move
637  * into an unsigned integer format indicating the from and to square. Create
638  * a linked list of opening lines of play, with entry->next pointing to the
639  * next line and entry->move pointing to a chunk of memory containing the
640  * moves. More Opening lines of up to 100 half moves may be added to
641  * gnushogi.book. But now it's a hashed table by position which yields a move
642  * or moves for each position. It no longer knows about openings per se only
643  * positions and recommended moves in those positions.
644  *
645  */
646
647 void
648 GetOpenings(void)
649 {
650     short i;
651     int mustwrite = false, first;
652     unsigned short side;
653     short c;
654     USHORT mv, flags;
655     unsigned int x;
656     unsigned int games = 0;
657     LONG collisions = 0;
658     char msg[80];
659
660     FILE *fd;
661
662     if ((fd = fopen(bookfile, "r")) == NULL)
663         fd = fopen("gnushogi.tbk", "r");
664
665     if (fd != NULL)
666     {
667         /* yes add to book */
668         /* open book as writer */
669         gfd = open(binbookfile, O_RDONLY | O_BINARY);
670
671         if (gfd >= 0)
672         {
673             if (ReadAdmin())
674             {
675                 B.bookcount = ADMIN.bookcount;
676                 B.booksize = ADMIN.booksize;
677                 B.maxoffset = ADMIN.maxoffset;
678
679                 if (B.booksize && !(B.maxoffset == MAXOFFSET(B)))
680                 {
681                     printf("bad format %s\n", binbookfile);
682                     exit(1);
683                 }
684             }
685             else
686             {
687                 printf("bad format %s\n", binbookfile);
688                 exit(1);
689             }
690             close(gfd);
691             gfd = open(binbookfile, O_RDWR | O_BINARY);
692
693         }
694         else
695         {
696             gfd = open(binbookfile, O_RDWR | O_CREAT | O_BINARY, 0644);
697
698             ADMIN.bookcount = B.bookcount = 0;
699             ADMIN.booksize = B.booksize = booksize;
700             B.maxoffset = ADMIN.maxoffset = MAXOFFSET(B);
701             DATA.hashbd = 0;
702             DATA.hashkey = 0;
703             DATA.bmove = 0;
704             DATA.flags = 0;
705             DATA.hint = 0;
706             DATA.count = 0;
707             write(gfd, (char *)&ADMIN, sizeof_gdxadmin);
708             printf("creating bookfile %s %ld %ld\n",
709                     binbookfile, B.maxoffset, B.booksize);
710
711             for (x = 0; x < B.booksize; x++)
712             {
713                 write(gfd, (char *)&DATA, sizeof_gdxdata);
714             }
715         }
716
717         if (gfd >= 0)
718         {
719             /* setvbuf(fd, buffr, _IOFBF, 2048); */
720             side = black;
721             hashbd = hashkey = 0;
722             i = 0;
723
724             while ((c = Vparse(fd, &mv, &flags, i)) >= 0)
725             {
726                 if (c == 1)
727                 {
728                     /*
729                      * If this is not the first move of an opening and
730                      * if it's the first time we have seen it then
731                      * save the next move as a hint.
732                      */
733                     i++;
734
735                     if (i < bookmaxply + 2)
736                     {
737                         if (i > 1 && !(flags & BADMOVE))
738                             DATA.hint = mv;
739
740                         if (i < bookmaxply + 1)
741                         {
742                             /*
743                              * See if this position and move already
744                              * exist from some other opening.
745                              */
746
747                             WriteData();
748                             HashOffset(bhashkey, B);
749                             first = true;
750
751                             while (true)
752                             {
753                                 if (!ReadData(&DATA))
754                                     break; /* corrupted binbook file */
755
756                                 if (DATA.bmove == 0)
757                                     break;  /* free entry */
758
759                                 if (DATA.hashkey == HashValue(bhashkey)
760                                     && DATA.hashbd == bhashbd)
761                                 {
762                                     if (DATA.bmove == mv)
763                                     {
764                                         /*
765                                          * Yes, so just bump count - count
766                                          * is used to choose the opening
767                                          * move in proportion to its
768                                          * presence in the book.
769                                          */
770
771                                         DATA.count++;
772                                         DATA.flags |= flags;
773                                         mustwrite = true;
774                                         break;
775                                     }
776                                     else
777                                     {
778                                         if (first)
779                                             collisions++;
780
781                                         if (DATA.flags & LASTMOVE)
782                                         {
783                                             DATA.flags &= (~LASTMOVE);
784                                             mustwrite = true;
785                                             WriteData();
786                                         }
787                                     }
788                                 }
789
790                                 NextOffset(B);
791                                 first = false;
792                             }
793
794                             /*
795                              * Doesn't exist so add it to the book.
796                              */
797
798                             if (!mustwrite)
799                             {
800                                 B.bookcount++;
801
802                                 if ((B.bookcount % 1000) == 0)
803                                 {
804                                     /* CHECKME: may want to get rid of this,
805                                      * especially for xshogi. */
806                                     printf("%ld rec %d openings "
807                                            "processed\n",
808                                            B.bookcount, games);
809                                 }
810
811                                 /* initialize a record */
812                                 DATA.hashbd = bhashbd;
813                                 DATA.hashkey = HashValue(bhashkey);
814                                 DATA.bmove = mv;
815                                 DATA.flags = flags | LASTMOVE;
816                                 DATA.count = 1;
817                                 DATA.hint = 0;
818                                 mustwrite = true;
819                             }
820                         }
821                     }
822
823                     computer = opponent;
824                     opponent = computer ^ 1;
825
826                     side = side ^ 1;
827                 }
828                 else if (i > 0)
829                 {
830                     /* reset for next opening */
831                     games++;
832                     WriteData();
833                     RESET();
834                     i = 0;
835                     side = black;
836                 }
837             }
838
839             WriteData();
840             fclose(fd);
841             /* write admin rec with counts */
842             ADMIN.bookcount = B.bookcount;
843             WriteAdmin();
844
845             close(gfd);
846         }
847     }
848
849     if (binbookfile != NULL)
850     {
851         /* open book as reader */
852         gfd = open(binbookfile, O_RDONLY | O_BINARY);
853
854         if (gfd >= 0)
855         {
856             if (ReadAdmin() && (!ADMIN.booksize
857                                 || (ADMIN.maxoffset == MAXOFFSET(ADMIN))))
858             {
859                 B.bookcount = ADMIN.bookcount;
860                 B.booksize  = ADMIN.booksize;
861                 B.maxoffset = ADMIN.maxoffset;
862             }
863             else
864             {
865                 printf("bad format %s\n", binbookfile);
866                 exit(1);
867             }
868
869         }
870         else
871         {
872             B.bookcount = 0;
873             B.booksize = booksize;
874
875         }
876
877         sprintf(msg, "Book used %lu(%lu).", B.bookcount, B.booksize);
878         dsp->ShowMessage(msg);
879     }
880
881     /* Set everything back to start the game. */
882     Book = BOOKFAIL;
883     RESET();
884
885     /* Now get ready to play .*/
886     if (!B.bookcount)
887     {
888         dsp->ShowMessage("Can't find book.");
889         Book = 0;
890     }
891 }
892
893
894
895 /*
896  * OpeningBook(hint)
897  *
898  * Go through each of the opening lines of play and check for a match with
899  * the current game listing. If a match occurs, generate a random
900  * number. If this number is the largest generated so far then the next
901  * move in this line becomes the current "candidate".  After all lines are
902  * checked, the candidate move is put at the top of the Tree[] array and
903  * will be played by the program.  Note that the program does not handle
904  * book transpositions.
905  */
906
907 int
908 OpeningBook(unsigned short *hint)
909 {
910     unsigned short r, m;
911     int possibles = TrPnt[2] - TrPnt[1];
912
913     gsrand((unsigned int) time((long *) 0));
914     m = 0;
915
916     /*
917      * Find all the moves for this position  - count them and get their
918      * total count.
919      */
920
921     {
922         USHORT i, x;
923         USHORT rec = 0;
924         USHORT summ = 0;
925         USHORT h = 0, b = 0;
926         struct gdxdata OBB[128];
927
928         if (B.bookcount == 0)
929         {
930             Book--;
931             return false;
932         }
933
934         x = 0;
935         HashOffset(hashkey, B);
936 #ifdef BOOKTEST
937         printf("looking for book move, bhashbd = 0x%lx bhashkey = 0x%x\n",
938                (ULONG)hashbd, HashValue(hashkey));
939 #endif
940         while (true)
941         {
942             if (!ReadData(&OBB[x]))
943                 break;
944
945             if (OBB[x].bmove == 0)
946                 break;
947
948 #ifdef BOOKTEST
949             printf("compare with bhashbd = 0x%lx bhashkey = 0x%x\n",
950                    OBB[x].hashbd, OBB[x].hashkey);
951 #endif
952             if ((OBB[x].hashkey == HashValue(hashkey))
953                 && (OBB[x].hashbd == (ULONG)hashbd))
954             {
955                 x++;
956
957                 if (OBB[x-1].flags & LASTMOVE)
958                     break;
959             }
960
961             NextOffset(B);
962         }
963
964 #ifdef BOOKTEST
965         printf("%d book move(s) found.\n", x);
966 #endif
967
968         if (x == 0)
969         {
970             Book--;
971             return false;
972         }
973
974         for (i = 0; i < x; i++)
975         {
976             if (OBB[i].flags & BADMOVE)
977             {
978                 m = OBB[i].bmove;
979
980                 /* Is the move in the MoveList? */
981                 for (b = TrPnt[1]; b < (unsigned) TrPnt[2]; b++)
982                 {
983                     if (((Tree[b].f << 8) | Tree[b].t) == m)
984                     {
985                         if (--possibles)
986                             Tree[b].score = DONTUSE;
987                         break;
988                     }
989                 }
990             }
991             else
992             {
993 #if defined BOOKTEST
994                 char s[20];
995                 movealgbr(m = OBB[i].bmove, s);
996                 printf("finding book move: %s\n", s);
997 #endif
998                 summ += OBB[i].count;
999             }
1000         }
1001
1002         if (summ == 0)
1003         {
1004             Book--;
1005             return false;
1006         }
1007
1008         r = (urand() % summ);
1009
1010         for (i = 0; i < x; i++)
1011         {
1012             if (!(OBB[i].flags & BADMOVE))
1013             {
1014                 if (r < OBB[i].count)
1015                 {
1016                     rec = i;
1017                     break;
1018                 }
1019                 else
1020                 {
1021                     r -= OBB[i].count;
1022                 }
1023             }
1024         }
1025
1026         h = OBB[rec].hint;
1027         m = OBB[rec].bmove;
1028
1029         /* Make sure the move is in the MoveList. */
1030         for (b = TrPnt[1]; b < (unsigned) TrPnt[2]; b++)
1031         {
1032             if (((Tree[b].f << 8) | Tree[b].t) == m)
1033             {
1034                 Tree[b].flags |= book;
1035                 Tree[b].score = 0;
1036                 break;
1037             }
1038         }
1039
1040         /* Make sure it's the best. */
1041
1042         pick(TrPnt[1], TrPnt[2] - 1);
1043
1044         if (Tree[TrPnt[1]].score)
1045         {
1046             /* no! */
1047             Book--;
1048             return false;
1049         }
1050
1051         /* Ok, pick up the hint and go. */
1052         *hint = h;
1053         return true;
1054     }
1055
1056     Book--;
1057     return false;
1058 }
1059
1060
1061