code cleanup: make function definition confirm to GNU coding style
[xboard.git] / parser.c
1 /*
2  * parser.c --
3  *
4  * Copyright 2011, 2012 Free Software Foundation, Inc.
5  * ------------------------------------------------------------------------
6  *
7  * GNU XBoard is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or (at
10  * your option) any later version.
11  *
12  * GNU XBoard is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see http://www.gnu.org/licenses/.  *
19  *
20  *------------------------------------------------------------------------
21  ** See the file ChangeLog for a revision history.  */
22
23 #include "config.h"
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <string.h>
27 #include "common.h"
28 #include "backend.h"
29 #include "frontend.h"
30 #include "parser.h"
31 #include "moves.h"
32
33
34 extern Board    boards[MAX_MOVES];
35 extern int      PosFlags(int nr);
36 int             yyboardindex;
37 int             yyskipmoves = FALSE;
38 char            currentMoveString[4096]; // a bit ridiculous size?
39 char *yy_text;
40
41 #define PARSEBUFSIZE 10000
42
43 static FILE *inputFile;
44 static char *inPtr, *parsePtr, *parseStart;
45 static char inputBuf[PARSEBUFSIZE];
46 static char yytext[PARSEBUFSIZE];
47 static char fromString = 0, lastChar = '\n';
48
49 #define NOTHING 0
50 #define NUMERIC 1
51 #define ALPHABETIC 2
52 #define BADNUMBER (-2000000000)
53
54 int
55 ReadLine ()
56 {   // Read one line from the input file, and append to the buffer
57     char c, *start = inPtr;
58     if(fromString) return 0; // parsing string, so the end is a hard end
59     if(!inputFile) return 0;
60     while((c = fgetc(inputFile)) != EOF) {
61         *inPtr++ = c;
62         if(c == '\n') { *inPtr = NULLCHAR; return 1; }
63         if(inPtr - inputBuf > PARSEBUFSIZE-2) inPtr--; //prevent crash on overflow
64     }
65     if(inPtr == start) return 0;
66     *inPtr++ = '\n', *inPtr = NULLCHAR; // repair missing linefeed at EOF
67     return 1;
68 }
69
70 int
71 Scan (char c, char **p)
72 {   // line-spanning skip to mentioned character or EOF
73     do {
74         while(**p) if(*(*p)++ == c) return 0;
75     } while(ReadLine());
76     // no closing bracket; force match for entire rest of file.
77     return 1;
78 }
79
80 int
81 SkipWhite (char **p)
82 {   // skip spaces tabs and newlines; return 1 if anything was skipped
83     char *start = *p;
84     do{
85         while(**p == ' ' || **p == '\t' || **p == '\n' || **p == '\r') (*p)++;
86     } while(**p == NULLCHAR && ReadLine()); // continue as long as ReadLine reads something
87     return *p != start;
88 }
89
90 inline int
91 Match (char *pattern, char **ptr)
92 {
93     char *p = pattern, *s = *ptr;
94     while(*p && (*p == *s++ || s[-1] == '\r' && *p--)) p++;
95     if(*p == 0) {
96         *ptr = s;
97         return 1;
98     }
99     return 0; // no match, no ptr update
100 }
101
102 inline int
103 Word (char *pattern, char **p)
104 {
105     if(Match(pattern, p)) return 1;
106     if(*pattern >= 'a' && *pattern <= 'z' && *pattern - **p == 'a' - 'A') { // capitalized
107         (*p)++;
108         if(Match(pattern + 1, p)) return 1;
109         (*p)--;
110     }
111     return 0;
112 }
113
114 int
115 Verb (char *pattern, char **p)
116 {
117     int res = Word(pattern, p);
118     if(res && !Match("s", p)) Match("ed", p); // eat conjugation suffix, if any
119     return res;
120 }
121
122 int
123 Number (char **p)
124 {
125     int val = 0;
126     if(**p < '0' || **p > '9') return BADNUMBER;
127     while(**p >= '0' && **p <= '9') {
128         val = 10*val + *(*p)++ - '0';
129     }
130     return val;
131 }
132
133 int
134 RdTime (char c, char **p)
135 {
136     char *start = ++(*p), *sec; // increment *p, as it was pointing to the opening ( or {
137     if(Number(p) == BADNUMBER) return 0;
138     sec = *p;
139     if(Match(":", p) && Number(p) != BADNUMBER && *p - sec == 3) { // well formed
140         sec = *p;
141         if(Match(".", p) && Number(p) != BADNUMBER && *(*p)++ == c) return 1; // well-formed fraction
142         *p = sec;
143         if(*(*p)++ == c) return 1; // matching bracket without fraction
144     }
145     *p = start; // failure
146     return 0;
147 }
148
149 char
150 PromoSuffix (char **p)
151 {
152     char *start = *p;
153     if(**p == 'e' && (Match("ep", p) || Match("e.p.", p))) { *p = start; return NULLCHAR; } // non-compliant e.p. suffix is no promoChar!
154     if(**p == '+' && gameInfo.variant == VariantShogi) { (*p)++; return '+'; } 
155     if(**p == '=' || (gameInfo.variant == VariantSChess) && **p == '/') (*p)++; // optional = (or / for Seirawan gating)
156     if(**p == '(' && (*p)[2] == ')' && isalpha( (*p)[1] )) { (*p) += 3; return (*p)[-2]; }
157     if(isalpha(**p)) return *(*p)++;
158     if(*p != start) return '='; // must be the optional =
159     return NULLCHAR; // no suffix detected
160 }
161
162 int
163 NextUnit (char **p)
164 {       // Main parser routine
165         int coord[4], n, result, piece, i;
166         char type[4], promoted, separator, slash, *oldp, *commentEnd, c;
167         int wom = quickFlag ? quickFlag&1 : WhiteOnMove(yyboardindex);
168
169         // ********* try white first, because it is so common **************************
170         if(**p == ' ' || **p == '\n' || **p == '\t') { parseStart = (*p)++; return Nothing; }
171
172
173         if(**p == NULLCHAR) { // make sure there is something to parse
174             if(fromString) return 0; // we are parsing string, so the end is really the end
175             *p = inPtr = inputBuf;
176             if(!ReadLine()) return 0; // EOF
177         }
178         parseStart = oldp = *p; // remember where we begin
179
180
181         // ********* attempt to recognize a SAN move in the leading non-blank text *****
182         piece = separator = promoted = slash = n = 0;
183         for(i=0; i<4; i++) coord[i] = -1, type[i] = NOTHING;
184         if(**p == '+') (*p)++, promoted++;
185         if(**p >= 'a' && **p <= 'z' && (*p)[1]== '@') piece =*(*p)++ + 'A' - 'a'; else
186         if(**p >= 'A' && **p <= 'Z') {
187              piece = *(*p)++; // Note we could test for 2-byte non-ascii names here
188              if(**p == '/') slash = *(*p)++;
189         }
190         while(n < 4) {
191             if(**p >= 'a' && **p < 'x') coord[n] = *(*p)++ - 'a', type[n++] = ALPHABETIC;
192             else if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
193             else break;
194             if(n == 2 && type[0] == type[1]) { // if two identical types, the opposite type in between must have been missing
195                 type[2] = type[1]; coord[2] = coord[1];
196                 type[1] = NOTHING; coord[1] = -1; n++;
197             }
198         }
199         // we always get here, and might have read a +, a piece, and upto 4 potential coordinates
200         if(n <= 2) { // could be from-square or disambiguator, when -:xX follow, or drop with @ directly after piece, but also to-square
201              if(**p == '-' || **p == ':' || **p == 'x' || **p == 'X' || // these cannot be move suffix, so to-square must follow
202                  (**p == '@' || **p == '*') && n == 0 && !promoted && piece) { // P@ must also be followed by to-square
203                 separator = *(*p)++;
204                 if(n == 1) coord[1] = coord[0]; // must be disambiguator, but we do not know which yet
205                 n = 2;
206                 while(n < 4) { // attempt to read to-square
207                     if(**p >= 'a' && **p < 'x') coord[n] = *(*p)++ - 'a', type[n++] = ALPHABETIC;
208                     else if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
209                     else break;
210                 }
211             } else if((**p == '+' || **p == '=') && n == 1 && piece && type[0] == NUMERIC) { // can be traditional Xiangqi notation
212                 separator = *(*p)++;
213                 n = 2;
214                 if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
215             } else if(n == 2) { // only one square mentioned, must be to-square
216                 while(n < 4) { coord[n] = coord[n-2], type[n] = type[n-2], coord[n-2] = -1, type[n-2] = NOTHING; n++; }
217             }
218         } else if(n == 3 && type[1] != NOTHING) { // must be hyphenless disambiguator + to-square
219             for(i=3; i>0; i--) coord[i] = coord[i-1], type[i] = type[i-1]; // move to-square to where it belongs
220             type[1] = NOTHING; // disambiguator goes in first two positions
221             n = 4;
222         }
223 if(appData.debugMode)fprintf(debugFP, "trial %d,%d,%d,%d  type %d%d%d%d\n", coord[0], coord[1], coord[2], coord[3], type[0], type[1], type[2], type[3]);
224         // we always get here; move must be completely read now, with to-square coord(s) at end
225         if(n == 3) { // incomplete to-square. Could be Xiangqi traditional, or stuff like fxg
226             if(piece && type[1] == NOTHING && type[0] == NUMERIC && type[2] == NUMERIC && 
227                 (separator == '+' || separator == '=' || separator == '-')) {
228                      // Xiangqi traditional
229
230                 return ImpossibleMove; // for now treat as invalid
231             }
232             // fxg stuff, but also things like 0-0, 0-1 and 1-0
233             if(!piece && type[1] == NOTHING && type[0] == ALPHABETIC && type[2] == ALPHABETIC
234                  && (coord[0] != 14 || coord[2] != 14) /* reserve oo for castling! */ ) {
235                 piece = 'P'; n = 4; // kludge alert: fake full to-square
236             }
237         } else if(n == 1 && type[0] == NUMERIC && coord[0] > 1) { while(**p == '.') (*p)++; return Nothing; } // fast exit for move numbers
238         if(n == 4 && type[2] != type[3] && // we have a valid to-square (kludge: type[3] can be NOTHING on fxg type move)
239                      (piece || !promoted) && // promoted indicator only valid on named piece type
240                      (type[2] == ALPHABETIC || gameInfo.variant == VariantShogi)) { // in Shogi also allow alphabetic rank
241             DisambiguateClosure cl;
242             int fromX, fromY, toX, toY;
243
244             if(slash && (!piece || type[1] == NOTHING)) goto badMove; // slash after piece only in ICS long format
245             if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
246
247             if(type[2] == NUMERIC) { // alpha-rank
248                 coord[2] = BOARD_RGHT - BOARD_LEFT - coord[2];
249                 coord[3] = BOARD_HEIGHT - coord[3];
250                 if(coord[0] >= 0) coord[0] = BOARD_RGHT - BOARD_LEFT - coord[0];
251                 if(coord[1] >= 0) coord[1] = BOARD_HEIGHT - coord[1];
252             }
253             toX = cl.ftIn = (currentMoveString[2] = coord[2] + 'a') - AAA;
254             toY = cl.rtIn = (currentMoveString[3] = coord[3] + '0') - ONE;
255             if(type[3] == NOTHING) cl.rtIn = -1; // for fxg type moves ask for toY disambiguation
256             else if(toY >= BOARD_HEIGHT || toY < 0)   return ImpossibleMove; // vert off-board to-square
257             if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return ImpossibleMove;
258             if(piece) {
259                 cl.pieceIn = CharToPiece(wom ? piece : ToLower(piece));
260                 if(cl.pieceIn == EmptySquare) return ImpossibleMove; // non-existent piece
261                 if(promoted) cl.pieceIn = (ChessSquare) (PROMOTED cl.pieceIn);
262             } else cl.pieceIn = EmptySquare;
263             if(separator == '@' || separator == '*') { // drop move. We only get here without from-square or promoted piece
264                 fromY = DROP_RANK; fromX = cl.pieceIn;
265                 currentMoveString[0] = piece;
266                 currentMoveString[1] = '@';
267                 return LegalityTest(boards[yyboardindex], PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, fromY, fromX, toY, toX, NULLCHAR);
268             }
269             if(type[1] == NOTHING && type[0] != NOTHING) { // there is a disambiguator
270                 if(type[0] != type[2]) coord[0] = -1, type[1] = type[0], type[0] = NOTHING; // it was a rank-disambiguator
271             }
272             if(  type[1] != type[2] && // means fromY is of opposite type as ToX, or NOTHING
273                 (type[0] == NOTHING || type[0] == type[2]) ) { // well formed
274
275                 fromX = (currentMoveString[0] = coord[0] + 'a') - AAA;
276                 fromY = (currentMoveString[1] = coord[1] + '0') - ONE;
277                 currentMoveString[4] = cl.promoCharIn = PromoSuffix(p);
278                 currentMoveString[5] = NULLCHAR;
279                 if(type[0] != NOTHING && type[1] != NOTHING && type[3] != NOTHING) { // fully specified.
280                     // Note that Disambiguate does not work for illegal moves, but flags them as impossible
281                     if(piece) { // check if correct piece indicated
282                         ChessSquare realPiece = boards[yyboardindex][fromY][fromX];
283                         if(PieceToChar(realPiece) == '~') realPiece = (ChessSquare) (DEMOTED realPiece);
284                         if(!(appData.icsActive && PieceToChar(realPiece) == '+') && // trust ICS if it moves promoted pieces
285                            piece && realPiece != cl.pieceIn) return ImpossibleMove;
286                     }
287                     result = LegalityTest(boards[yyboardindex], PosFlags(yyboardindex), fromY, fromX, toY, toX, cl.promoCharIn);
288                     if (currentMoveString[4] == NULLCHAR) { // suppy missing mandatory promotion character
289                       if(result == WhitePromotion  || result == BlackPromotion) {
290                         switch(gameInfo.variant) {
291                           case VariantCourier:
292                           case VariantShatranj: currentMoveString[4] = PieceToChar(BlackFerz); break;
293                           case VariantGreat:    currentMoveString[4] = PieceToChar(BlackMan); break;
294                           case VariantShogi:    currentMoveString[4] = '+'; break;
295                           default:              currentMoveString[4] = PieceToChar(BlackQueen);
296                         }
297                       } else if(result == WhiteNonPromotion  || result == BlackNonPromotion) {
298                                                 currentMoveString[4] = '=';
299                       }
300                     } else if(appData.testLegality && gameInfo.variant != VariantSChess && // strip off unnecessary and false promo characters
301                        !(result == WhitePromotion  || result == BlackPromotion ||
302                          result == WhiteNonPromotion || result == BlackNonPromotion)) currentMoveString[4] = NULLCHAR;
303                     return result;
304                 } else if(cl.pieceIn == EmptySquare) cl.pieceIn = wom ? WhitePawn : BlackPawn;
305                 cl.ffIn = type[0] == NOTHING ? -1 : coord[0] + 'a' - AAA;
306                 cl.rfIn = type[1] == NOTHING ? -1 : coord[1] + '0' - ONE;
307
308                 Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
309
310                 if(cl.kind == ImpossibleMove && !piece && type[1] == NOTHING // fxg5 type
311                         && toY == (wom ? 4 : 3)) { // could be improperly written e.p.
312                     cl.rtIn += wom ? 1 : -1; // shift target square to e.p. square
313                     Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
314                     if((cl.kind != WhiteCapturesEnPassant && cl.kind != BlackCapturesEnPassant))
315                         return ImpossibleMove; // nice try, but no cigar
316                 }
317
318                 currentMoveString[0] = cl.ff + AAA;
319                 currentMoveString[1] = cl.rf + ONE;
320                 currentMoveString[3] = cl.rt + ONE;
321                 currentMoveString[4] = cl.promoChar;
322
323                 if((cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) && (Match("ep", p) || Match("e.p.", p)));
324
325                 return (int) cl.kind;
326             }
327         }
328 badMove:// we failed to find algebraic move
329         *p = oldp;
330
331
332         // Next we do some common symbols where the first character commits us to things that cannot possibly be a move
333
334         // ********* PGN tags ******************************************
335         if(**p == '[') {
336             oldp = ++(*p);
337             if(Match("--", p)) { // "[--" could be start of position diagram
338                 if(!Scan(']', p) && (*p)[-3] == '-' && (*p)[-2] == '-') return PositionDiagram; 
339                 *p = oldp;
340             }
341             SkipWhite(p);
342             if(isdigit(**p) || isalpha(**p)) {
343                 do (*p)++; while(isdigit(**p) || isalpha(**p) || **p == '+' ||
344                                 **p == '-' || **p == '=' || **p == '_' || **p == '#');
345                 SkipWhite(p);
346                 if(**p == '"') {
347                     (*p)++;
348                     while(**p != '\n' && (*(*p)++ != '"'|| (*p)[-2] == '\\')); // look for unescaped quote
349                     if((*p)[-1] !='"') { *p = oldp; Scan(']', p); return Comment; } // string closing delimiter missing
350                     SkipWhite(p); if(*(*p)++ == ']') return PGNTag;
351                 }
352             }
353             Scan(']', p); return Comment;
354         }
355
356         // ********* SAN Castings *************************************
357         if(**p == 'O' || **p == 'o' || **p == '0') {
358             int castlingType = 0;
359             if(Match("O-O-O", p) || Match("o-o-o", p) || Match("0-0-0", p) || 
360                Match("OOO", p) || Match("ooo", p) || Match("000", p)) castlingType = 2;
361             else if(Match("O-O", p) || Match("o-o", p) || Match("0-0", p) ||
362                     Match("OO", p) || Match("oo", p) || Match("00", p)) castlingType = 1;
363             if(castlingType) { //code from old parser, collapsed for both castling types, and streamlined a bit
364                 int rf, ff, rt, ft; ChessSquare king;
365                 char promo=NULLCHAR;
366
367                 if(gameInfo.variant == VariantSChess) promo = PromoSuffix(p);
368
369                 if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
370
371                 if (wom) {
372                     rf = 0;
373                     rt = 0;
374                     king = WhiteKing;
375                 } else {
376                     rf = BOARD_HEIGHT-1;
377                     rt = BOARD_HEIGHT-1;
378                     king = BlackKing;
379                 }
380                 ff = (BOARD_WIDTH-1)>>1; // this would be d-file
381                 if (boards[yyboardindex][rf][ff] == king) {
382                     /* ICS wild castling */
383                     ft = castlingType == 1 ? BOARD_LEFT+1 : (gameInfo.variant == VariantJanus ? BOARD_RGHT-2 : BOARD_RGHT-3);
384                 } else {
385                     ff = BOARD_WIDTH>>1; // e-file
386                     ft = castlingType == 1 ? BOARD_RGHT-2 : BOARD_LEFT+2;
387                 }
388                 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
389                     if (wom) {
390                         ff = initialRights[2];
391                         ft = initialRights[castlingType-1];
392                     } else {
393                         ff = initialRights[5];
394                         ft = initialRights[castlingType+2];
395                     }
396                     if (appData.debugMode) fprintf(debugFP, "Parser FRC (type=%d) %d %d\n", castlingType, ff, ft);
397                     if(ff == NoRights || ft == NoRights) return ImpossibleMove;
398                 }
399                 sprintf(currentMoveString, "%c%c%c%c%c",ff+AAA,rf+ONE,ft+AAA,rt+ONE,promo);
400                 if (appData.debugMode) fprintf(debugFP, "(%d-type) castling %d %d\n", castlingType, ff, ft);
401
402                 return (int) LegalityTest(boards[yyboardindex],
403                               PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: e.p.!
404                               rf, ff, rt, ft, promo);
405             }
406         }
407
408
409         // ********* variations (nesting) ******************************
410         if(**p =='(') {
411             if(RdTime(')', p)) return ElapsedTime;
412             return Open;
413         }
414         if(**p ==')') { (*p)++; return Close; }
415         if(**p == ';') { while(**p != '\n') (*p)++; return Comment; }
416
417
418         // ********* Comments and result messages **********************
419         *p = oldp; commentEnd = NULL; result = 0;
420         if(**p == '{') {
421             if(RdTime('}', p)) return ElapsedTime;
422             if(lastChar == '\n' && Match("--------------\n", p)) {
423                 char *q;
424                 i = Scan ('}', p); q = *p - 16;
425                 if(Match("\n--------------}\n", &q)) return PositionDiagram;
426             } else i = Scan('}', p);
427             commentEnd = *p; if(i) return Comment; // return comment that runs to EOF immediately
428         }
429         if(commentEnd) SkipWhite(p);
430         if(Match("*", p)) result = GameUnfinished;
431         else if(**p == '0') {
432             if( Match("0-1", p) || Match("0/1", p) || Match("0:1", p) ||
433                 Match("0 - 1", p) || Match("0 / 1", p) || Match("0 : 1", p)) result = BlackWins;
434         } else if(**p == '1') {
435             if( Match("1-0", p) || Match("1/0", p) || Match("1:0", p) ||
436                 Match("1 - 0", p) || Match("1 / 0", p) || Match("1 : 0", p)) result = WhiteWins;
437             else if(Match("1/2 - 1/2", p) || Match("1/2:1/2", p) || Match("1/2 : 1/2", p) || Match("1 / 2 - 1 / 2", p) ||
438                     Match("1 / 2 : 1 / 2", p) || Match("1/2", p) || Match("1 / 2", p)) result = GameIsDrawn;
439         }
440         if(result) {
441             if(Match(" (", p) && !Scan(')', p) || Match(" {", p) && !Scan('}', p)) { // there is a comment after the PGN result!
442                 if(commentEnd) { *p = commentEnd; return Comment; } // so comment before it is normal comment; return that first
443             }
444             return result; // this returns a possible preceeding comment as result details
445         }
446         if(commentEnd) { *p = commentEnd; return Comment; } // there was no PGN result following, so return as normal comment
447
448
449         // ********* Move numbers (after castlings or PGN results!) ***********
450         if((i = Number(p)) != BADNUMBER) { // a single number was read as part of our attempt to read a move
451             char *numEnd = *p;
452             if(**p == '.') (*p)++; SkipWhite(p);
453             if(**p == '+' || isalpha(**p) || gameInfo.variant == VariantShogi && *p != numEnd && isdigit(**p)) {
454                 *p = numEnd;
455                 return i == 1 ? MoveNumberOne : Nothing;
456             }
457             *p = numEnd; return Nothing;
458         }
459
460
461         // ********* non-compliant game-result indicators *********************
462         if(Match("+-+", p) || Word("stalemate", p)) return GameIsDrawn;
463         if(Match("++", p) || Verb("resign", p) || (Word("check", p) || 1) && Word("mate", p) )
464             return (wom ? BlackWins : WhiteWins);
465         c = ToUpper(**p);
466         if(Word("w", p) && (Match("hite", p) || 1) || Word("b", p) && (Match("lack", p) || 1) ) {
467             if(**p != ' ') return Nothing;
468             ++*p;
469             if(Verb("disconnect", p)) return GameUnfinished;
470             if(Verb("resign", p) || Verb("forfeit", p) || Word("mated", p) || Word("lost", p) || Word("loses", p))
471                 return (c == 'W' ? BlackWins : WhiteWins);
472             if(Word("mates", p) || Word("wins", p) || Word("won", p))
473                 return (c != 'W' ? BlackWins : WhiteWins);
474             return Nothing;
475         }
476         if(Word("draw", p)) {
477             if(**p == 'n') (*p)++;
478             if(**p != ' ') return GameIsDrawn;
479             oldp = ++*p;
480             if(Word("agreed", p)) return GameIsDrawn;
481             if(Match("by ", p) && (Word("repetition", p) || Word("agreement", p)) ) return GameIsDrawn;
482             *p = oldp;
483             if(*(*p)++ == '(') {
484                 while(**p != '\n') if(*(*p)++ == ')') break;
485                 if((*p)[-1] == ')')  return GameIsDrawn;
486             }
487             *p = oldp - 1; return GameIsDrawn;
488         }
489
490
491         // ********* Numeric annotation glyph **********************************
492         if(**p == '$') { (*p)++; if(Number(p) != BADNUMBER) return NAG; return Nothing; }
493
494
495         // ********** by now we are getting down to the silly stuff ************
496         if(Word("gnu", p) || Match("GNU", p)) {
497             if(**p == ' ') (*p)++;
498             if(Word("chess", p) || Match("CHESS", p)) {
499                 char *q;
500                 if((q = strstr(*p, "game")) || (q = strstr(*p, "GAME")) || (q = strstr(*p, "Game"))) {
501                     (*p) = q + 4; return GNUChessGame;
502                 }
503             }
504             return Nothing;
505         }
506         if(lastChar == '\n' && (Match("# ", p) || Match("; ", p) || Match("% ", p))) {
507             while(**p != '\n' && **p != ' ') (*p)++;
508             if(**p == ' ' && (Match(" game file", p) || Match(" position file", p))) {
509                 while(**p != '\n') (*p)++; // skip to EOLN
510                 return XBoardGame;
511             }
512             *p = oldp; // we might need to re-match the skipped stuff
513         }
514
515         if(Match("@@@@", p) || Match("--", p) || Match("Z0", p) || Match("pass", p) || Match("null", p)) {
516             strncpy(currentMoveString, "@@@@", 5);
517             return yyboardindex & F_WHITE_ON_MOVE ? WhiteDrop : BlackDrop;
518         }
519
520         // ********* Efficient skipping of (mostly) alphabetic chatter **********
521         while(isdigit(**p) || isalpha(**p) || **p == '-') (*p)++;
522         if(*p != oldp) {
523             if(**p == '\'') {
524                 while(isdigit(**p) || isalpha(**p) || **p == '-' || **p == '\'') (*p)++;
525                 return Nothing; // random word
526             }
527             if(lastChar == '\n' && Match(": ", p)) { // mail header, skip indented lines
528                 do {
529                     while(**p != '\n') (*p)++;
530                     if(!ReadLine()) return Nothing; // append next line if not EOF
531                 } while(Match("\n ", p) || Match("\n\t", p));
532             }
533             return Nothing;
534         }
535
536
537         // ********* Could not match to anything. Return offending character ****
538         (*p)++;
539         return Nothing;
540 }
541
542 /*
543     Return offset of next pattern in the current file.
544 */
545 int
546 yyoffset ()
547 {
548     return ftell(inputFile) - (inPtr - parsePtr); // subtract what is read but not yet parsed
549 }
550
551 void
552 yynewfile (FILE *f)
553 {   // prepare parse buffer for reading file
554     inputFile = f;
555     inPtr = parsePtr = inputBuf;
556     fromString = 0;
557     lastChar = '\n';
558     *inPtr = NULLCHAR; // make sure we will start by reading a line
559 }
560
561 void
562 yynewstr P((char *s))
563 {
564     parsePtr = s;
565     inputFile = NULL;
566     fromString = 1;
567 }
568
569 int
570 yylex ()
571 {   // this replaces the flex-generated parser
572     int result = NextUnit(&parsePtr);
573     char *p = parseStart, *q = yytext;
574     while(p < parsePtr) *q++ = *p++; // copy the matched text to yytext[]
575     *q = NULLCHAR;
576     lastChar = q[-1];
577     return result;
578 }
579
580 int
581 Myylex ()
582 {   // [HGM] wrapper for yylex, which treats nesting of parentheses
583     int symbol, nestingLevel = 0, i=0;
584     char *p;
585     static char buf[256*MSG_SIZ];
586     buf[0] = NULLCHAR;
587     do { // eat away anything not at level 0
588         symbol = yylex();
589         if(symbol == Open) nestingLevel++;
590         if(nestingLevel) { // save all parsed text between (and including) the ()
591             for(p=yytext; *p && i<256*MSG_SIZ-2;) buf[i++] = *p++;
592             buf[i] = NULLCHAR;
593         }
594         if(symbol == 0) break; // ran into EOF
595         if(symbol == Close) symbol = Comment, nestingLevel--;
596     } while(nestingLevel || symbol == Nothing);
597     yy_text = buf[0] ? buf : (char*)yytext;
598     return symbol;
599 }
600
601 ChessMove
602 yylexstr (int boardIndex, char *s, char *buf, int buflen)
603 {
604     ChessMove ret;
605     char *savPP = parsePtr;
606     fromString = 1;
607     yyboardindex = boardIndex;
608     parsePtr = s;
609     ret = (ChessMove) Myylex();
610     strncpy(buf, yy_text, buflen-1);
611     buf[buflen-1] = NULLCHAR;
612     parsePtr = savPP;
613     fromString = 0;
614     return ret;
615 }