]> git.sesse.net Git - pgn-extract/blob - main.c
eb25da5abcc7d48eda11d48125c676d025ee78cb
[pgn-extract] / main.c
1 /*
2  *  Program: pgn-extract: a Portable Game Notation (PGN) extractor.
3  *  Copyright (C) 1994-2012 David Barnes
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 1, or (at your option)
7  *  any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *
18  *  David Barnes may be contacted as D.J.Barnes@kent.ac.uk
19  *  http://www.cs.kent.ac.uk/people/staff/djb/
20  *
21  */
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <limits.h>
27 #include "bool.h"
28 #include "mymalloc.h"
29 #include "defs.h"
30 #include "typedef.h"
31 #include "tokens.h"
32 #include "taglist.h"
33 #include "lex.h"
34 #include "moves.h"
35 #include "map.h"
36 #include "lists.h"
37 #include "output.h"
38 #include "end.h"
39 #include "grammar.h"
40 #include "hashing.h"
41 #include "argsfile.h"
42
43 /* The maximum length of an output line.  This is conservatively
44  * slightly smaller than the PGN export standard of 80.
45  */
46 #define MAX_LINE_LENGTH 75
47
48 /* Define a file name relative to the current directory representing
49  * a file of ECO classificiations.
50  */
51 #ifndef DEFAULT_ECO_FILE
52 #define DEFAULT_ECO_FILE "eco.pgn"
53 #endif
54
55     /* This structure holds details of the program state
56      * available to all parts of the program.
57      * This goes against the grain of good structured programming
58      * principles, but most of these fields are set from the program's
59      * arguments and are read-only thereafter. If I had done this in
60      * C++ there would have been a cleaner interface!
61      */
62 StateInfo GlobalState = {
63     FALSE,                /* skipping_current_game */
64     FALSE,                /* check_only (-r) */
65     TRUE,                 /* verbose (-s) */
66     TRUE,                 /* keep_NAGs (-N) */
67     TRUE,                 /* keep_comments (-C) */
68     TRUE,                 /* keep_variations (-V) */
69     ALL_TAGS,             /* tag_output_form (-7, --notags) */
70     TRUE,                 /* match_permutations (-v) */
71     FALSE,                /* positional_variations (-x) */
72     FALSE,                /* use_soundex (-S) */
73     FALSE,                /* suppress_duplicates (-D) */
74     FALSE,                /* suppress_originals (-U) */
75     FALSE,                /* fuzzy_match_duplicates (--fuzzy) */
76     0,                    /* fuzzy_match_depth (--fuzzy) */
77     FALSE,                /* check_tags */
78     FALSE,                /* add_ECO (-e) */
79     FALSE,                /* parsing_ECO_file (-e) */
80     DONT_DIVIDE,          /* ECO_level (-E) */
81     SAN,                  /* output_format (-W) */
82     MAX_LINE_LENGTH,      /* max_line_length (-w) */
83     FALSE,                /* use_virtual_hash_table (-Z) */
84     FALSE,                /* check_move_bounds (-b) */
85     FALSE,                /* match_only_checkmate (-M) */
86     FALSE,                /* match_only_stalemate (--stalemate) */
87     TRUE,                 /* keep_move_numbers (--nomovenumbers) */
88     TRUE,                 /* keep_results (--noresults) */
89     TRUE,                 /* keep_checks (--nochecks) */
90     FALSE,                /* output_evaluation (--evaluation) */
91     FALSE,                /* keep_broken_games (--keepbroken) */
92     0,                    /* depth_of_positional_search */
93     0,                    /* num_games_processed */
94     0,                    /* num_games_matched */
95     0,                    /* games_per_file (-#) */
96     1,                    /* next_file_number */
97     0,                    /* lower_move_bound */
98     10000,                /* upper_move_bound */
99     -1,                   /* output_ply_limit (--plylimit) */
100     0,                    /* matching_game_number */
101     FALSE,                /* output_FEN_string */
102     FALSE,                /* add_FEN_comments (--fencomments) */
103     FALSE,                /* add_position_match_comments (--markmatches) */
104     FALSE,                /* output_total_plycount (--totalplycount) */
105     FALSE,                /* add_hashcode_tag (--addhashcode) */
106     FALSE,                /* dump-eco (--dumpeco) */
107     "MATCH",              /* position_match_comment (--markpositionmatches) */
108     (char *)NULL,         /* current_input_file */
109     NORMALFILE,           /* current_file_type */
110     -1,                   /* current_file_number */
111     0,                    /* start_file_number */
112     0,                    /* start_position */
113     LONG_MAX,             /* end_position */
114     DEFAULT_ECO_FILE,     /* eco_file (-e) */
115     (FILE *)NULL,         /* outputfile (-o, -a). Default is stdout */
116     (char *)NULL,         /* output_filename (-o, -a) */
117     (FILE *)NULL,         /* logfile (-l). Default is stderr */
118     (FILE *)NULL,         /* duplicate_file (-d) */
119     (FILE *)NULL,         /* non_matching_file (-n) */
120 };
121
122          /* Prepare the output file handles in GlobalState. */
123 static void
124 init_default_global_state(void)
125 {
126     GlobalState.outputfile = stdout;
127     GlobalState.logfile = stderr;
128     set_output_line_length(MAX_LINE_LENGTH);
129 }
130
131 int
132 main(int argc, char *argv[])
133 {   int argnum;
134
135     /* Prepare global state. */
136     init_default_global_state();
137     /* Prepare the Game_Header. */
138     init_game_header();
139     /* Prepare the tag lists for -t/-T matching. */
140     init_tag_lists();
141     /* Prepare the hash tables for transposition detection. */
142     init_hashtab();
143     /* Initialise the lexical analyser's tables. */
144     init_lex_tables();
145     /* Allow for some arguments. */
146     for(argnum = 1; argnum < argc; ){
147         const char *argument = argv[argnum];
148         if(argument[0] == '-'){
149             switch(argument[1]){
150                 /* Arguments with no additional component. */
151                 case SEVEN_TAG_ROSTER_ARGUMENT:
152                 case DONT_KEEP_COMMENTS_ARGUMENT:
153                 case DONT_KEEP_DUPLICATES_ARGUMENT:
154                 case DONT_KEEP_VARIATIONS_ARGUMENT:
155                 case DONT_KEEP_NAGS_ARGUMENT:
156                 case DONT_MATCH_PERMUTATIONS_ARGUMENT:
157                 case CHECK_ONLY_ARGUMENT:
158                 case KEEP_SILENT_ARGUMENT:
159                 case USE_SOUNDEX_ARGUMENT:
160                 case MATCH_CHECKMATE_ARGUMENT:
161                 case SUPPRESS_ORIGINALS_ARGUMENT:
162                 case OUTPUT_FEN_STRING_ARGUMENT:
163                 case USE_VIRTUAL_HASH_TABLE_ARGUMENT:
164                     process_argument(argument[1], "");
165                     argnum++;
166                     break;
167
168                 /* Argument rewritten as a different one. */
169                 case ALTERNATIVE_HELP_ARGUMENT:
170                     process_argument(HELP_ARGUMENT, "");
171                     argnum++;
172                     break;
173
174                 /* Arguments where an additional component is required.
175                  * It must be adjacent to the argument and not separated from it.
176                  */
177                 case TAG_EXTRACTION_ARGUMENT:
178                     process_argument(argument[1], &(argument[2]));
179                     argnum++;
180                     break;
181
182                 /* Arguments where an additional component is optional.
183                  * If it is present, it must be adjacent to the argument
184                  * letter and not separated from it.
185                  */
186                 case USE_ECO_FILE_ARGUMENT:
187                 case OUTPUT_FORMAT_ARGUMENT:
188                 case HELP_ARGUMENT:
189                     process_argument(argument[1], &(argument[2]));
190                     argnum++;
191                     break;
192
193                 /* Long form arguments. */
194                 case LONG_FORM_ARGUMENT:
195                     {  
196                       /* How many args (1 or 2) are processed. */
197                       int args_processed;
198                       /* This argument might need the following argument
199                        * as an associated value.
200                        */
201                       const char *possible_associated_value = "";
202                       if(argnum + 1 < argc) {
203                           possible_associated_value = argv[argnum+1];
204                       }
205                       /* Find out how many arguments were consumed
206                        * (1 or 2).
207                        */
208                       args_processed =
209                           process_long_form_argument(&argument[2],
210                                                      possible_associated_value);
211                       argnum += args_processed;
212                     }
213                     break;
214
215                 /* Arguments with a required filename component. */
216                 case FILE_OF_ARGUMENTS_ARGUMENT:
217                 case APPEND_TO_OUTPUT_FILE_ARGUMENT:
218                 case CHECK_FILE_ARGUMENT:
219                 case DUPLICATES_FILE_ARGUMENT:
220                 case FILE_OF_FILES_ARGUMENT:
221                 case WRITE_TO_LOG_FILE_ARGUMENT:
222                 case APPEND_TO_LOG_FILE_ARGUMENT:
223                 case NON_MATCHING_GAMES_ARGUMENT:
224                 case WRITE_TO_OUTPUT_FILE_ARGUMENT:
225                 case TAG_ROSTER_ARGUMENT:
226                     {   /* We require an associated file argument. */
227                         const char argument_letter = argument[1];
228                         const char *filename = &(argument[2]);
229                         if(*filename == '\0'){
230                              /* Try to pick it up from the next argument. */
231                              argnum++;
232                              if(argnum < argc){
233                                  filename = argv[argnum];
234                                  argnum++;
235                              }
236                             /* Make sure the associated_value does not look
237                              * like the next argument.
238                              */
239                             if((*filename == '\0') || (*filename == '-')){
240                                 fprintf(GlobalState.logfile,
241                                         "Usage: -%c filename\n",
242                                         argument_letter);
243                                 exit(1);
244                             }
245                         }
246                         else {
247                             argnum++;
248                         }
249                         process_argument(argument[1], filename);
250                     }
251                     break;
252
253                 /* Arguments with a required following value. */
254                 case BOUNDS_ARGUMENT:
255                 case ECO_OUTPUT_LEVEL_ARGUMENT:
256                 case LINE_WIDTH_ARGUMENT:
257                 case GAMES_PER_FILE_ARGUMENT:
258                     {   /* We require an associated file argument. */
259                         const char argument_letter = argument[1];
260                         const char *associated_value = &(argument[2]);
261                         if(*associated_value == '\0'){
262                              /* Try to pick it up from the next argument. */
263                              argnum++;
264                              if(argnum < argc){
265                                  associated_value = argv[argnum];
266                                  argnum++;
267                              }
268                             /* Make sure the associated_value does not look
269                              * like the next argument.
270                              */
271                             if((*associated_value == '\0') ||
272                                        (*associated_value == '-')){
273                                 fprintf(GlobalState.logfile,
274                                         "Usage: -%c value\n",
275                                         argument_letter);
276                                 exit(1);
277                             }
278                         }
279                         else {
280                             argnum++;
281                         }
282                         process_argument(argument[1], associated_value);
283                     }
284                     break;
285
286                 /* Argument that require different treatment because they
287                  * are present on the command line rather than an argsfile.
288                  */
289                 case TAGS_ARGUMENT:
290                 case MOVES_ARGUMENT:
291                 case POSITIONS_ARGUMENT:
292                 case ENDINGS_ARGUMENT:
293                     {   /* From the command line, we require an
294                          * associated file argument.
295                          * Check this here, as it is not the case
296                          * when reading arguments from an argument file.
297                          */
298                         const char *filename =  &(argument[2]);
299                         const char argument_letter = argument[1];
300                         if(*filename == '\0'){
301                              /* Try to pick it up from the next argument. */
302                              argnum++;
303                              if(argnum < argc){
304                                  filename = argv[argnum];
305                                  argnum++;
306                              }
307                             /* Make sure the filename does not look
308                              * like the next argument.
309                              */
310                             if((*filename == '\0') || (*filename == '-')){
311                                 fprintf(GlobalState.logfile,
312                                         "Usage: -%cfilename or -%c filename\n",
313                                         argument_letter,argument_letter);
314                                 exit(1);
315                             }
316                         }
317                         else{
318                             argnum++;
319                         }
320                         process_argument(argument_letter,filename);
321                     }
322                     break;
323                 default:
324                     fprintf(GlobalState.logfile,
325                             "Unknown flag %s. Use -%c for usage details.\n",
326                             argument,HELP_ARGUMENT);
327                     exit(1);
328                     break;
329             }
330         }
331         else{
332             /* Should be a file name containing games. */
333             add_filename_to_source_list(argument,NORMALFILE);
334             argnum++;
335         }
336     }
337     /* Prepare the hash tables for duplicate detection. */
338     init_duplicate_hash_table();
339
340     if(GlobalState.add_ECO){
341         /* Read in a list of ECO lines in order to classify the games. */
342         if(open_eco_file(GlobalState.eco_file)){
343             /* Indicate that the ECO file is currently being parsed. */
344             GlobalState.parsing_ECO_file = TRUE;
345             yyparse(ECOFILE);
346             reset_line_number();
347             GlobalState.parsing_ECO_file = FALSE;
348         }
349         else{
350             fprintf(GlobalState.logfile,"Unable to open the ECO file %s.\n",
351                         GlobalState.eco_file);
352             exit(1);
353         }
354     }
355
356     /* Open up the first file to act as Lex's source of input. */
357     if(!open_first_file()){
358         exit(1);
359     }
360     yyparse(GlobalState.current_file_type);
361     /* Remove any temporary files. */
362     clear_duplicate_hash_table();
363     if(GlobalState.verbose){
364         fprintf(GlobalState.logfile,"%lu game%s matched out of %lu.\n",
365                         GlobalState.num_games_matched,
366                         GlobalState.num_games_matched == 1?"":"s",
367                         GlobalState.num_games_processed);
368     }
369     if((GlobalState.logfile != stderr) && (GlobalState.logfile != NULL)){
370         (void) fclose(GlobalState.logfile);
371     }
372     return 0;
373 }