-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
2715 lines (2535 loc) · 93.4 KB
/
main.cpp
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
/*
PGN2LINE Bill Forster, October 2018
A chess PGN file management system based on the idea of converting PGN file(s)
to a new and highly convenient one game per line text format. The system makes
it easy to collect massive collections of disparate pgn files into a large,
neatly ordered and consolidated pgn file (or files). Along the way exact
duplicate games will be discarded and problematic missing blank lines (between
headers and moves, and between games) will be fixed. Whitelist, blacklist and
fixuplist facilities make it easy to filter tournaments and harmonise
tournament naming.
Why is a one game per line format convenient? An example should make the concept
clear. Consider using grep (i.e. search) on a one game per line file searching
for the text (say) "Forster". The grep output will be a valid one game per line
file comprising all games featuring that text - which includes all games played
by anyone named Forster.
Another example, in a Nakamura-Carlsen game, the format includes the text
"Nakamura-Carlsen". Search for all lines with that text and you get all such
games ready for immediate conversion back into PGN.
Usage:
pgn2line [-l] [-z] [-d] [-n] [-r] [-p]
[-y year_before] [+y year_after] [-w whitelist | -b blacklist]
[-f fixuplist] input output
-l indicates input is a text file that lists input pgn files (else input is a pgn file)
-z indicates don't include zero length games (BYEs are unaffected)
-Z indicates don't include zero length games, including BYEs
-d indicates smart game de-duplication (eliminates more dups)
-n indicates no sorting or de-duping
-r specifies smart reverse sort - yields most recent games first, smart because higher
rounds/boards are adjusted to come first both here and in the conventional sort
order
-p indicates create a .pgn from output (filename is ".pgn" appended to output)
-y discard games unless they are played in year_before or earlier
+y discard games unless they are played in year_after or later
-w specifies a whitelist list of tournaments, discard games not from these tournaments
-b specifies a blacklist list of tournaments, discard games from these tournaments
-f specifies a list of tournament name fixups
-2 flag removes games unless both players have been fixed up (useful for
cleaning online PGNs with a list of some but not all player handles)
Output is all games found in one game per line format, sorted for maxium utility.
Program line2pgn (or option -p) converts back to PGN format.
Whitelist, blacklist and fixuplist are all text files listing tournaments in the
following format;
yyyy Event@Site
For example;
2018 German Open@Berlin
Fixuplist must have an even number of lines as it is interpreted as before/after pairs.
For example
2018 German Open@Berlin
2018 23rd German Open@Berlin, Germany
This will apply the simple transformation Event->"23rd German Open" and Site->"Berlin, Germany"
For the moment Events and/or Sites with embedded @ characters are not accommodated.
Pairs of before and after player names are now allowed in the fixup file,
player names are identified as those strings NOT in yyyy Event@Site format.
Also line2pgn, a program to convert back to pgn.
And tournaments, a program to convert the line format into a tournament list. This list can be
in the same format as the whitelist/blacklist/fixuplist greatly simplifying preparation of
such lists.
Games are represented on a single line as follows;
Prefix@Hheader1@Hheader2...@Mmoves1@Mmoves2...
The header1, header2 etc. are the PGN header lines, moves1, moves2 etc. are the PGN
moves lines
The prefix to the line serves two purposes
1) readable summary of the game
2) allows simple string sort to order games effectively
Example for Smith v Jones, Event=Acme Open, Site=Gotham, round 3.2.1 on 2001-12-31 prefix is;
2001-12-28 Acme Open, Gotham # 2001-12-31 003.002.001 000000001 Smith-Jones
The first date is the tournament date (first day in tournament), the second date is the
game date.
Note: I have added a 9 digit tie breaker after the round information. It's a game idx,
1 for first game read, 2 for second etc. and serves to order the games in the original
source order if everything else matches. The first release of this suite lacked this
feature.
Note 2: I am now updating the program for Release 3.0, and I am going to remove the tie
breaker as a final stage of pgn2line because it makes the .lpgn files dramatically less useful
for comparisons - the smallest changes anywhere make for a completely different .lpgn file
line by line, only because of the presence of this field. In other words, it is still used
internally for intermediate processing (it's very useful) but discarded in a different stage
at the end. So externally we are back to the V1.0 format;
2001-12-28 Acme Open, Gotham # 2001-12-31 003.002.001 Smith-Jones
The net result is that all games in the tournament are grouped together in date/round
order. Tournaments are sorted by start date of tournament. This can reasonably be
considered optimum game ordering.
When processing game by game we don't actually know the start date of the tournament,
so we set the tournament date to the game date (so 2001-12-31 here). That allows a
useful stage one disk sort.
Later on in the "refined sort" stage we group together tournament games that share
the same Event and Site in any 6 month window. The tournament date is easily determined
as the first game date encountered for the tournament after the stage 1 sort, allowing
us to replace the proxy start date with the real start date.
TODO - Events and/or Sites with embedded @ characters are not accommodated by the
whitelist, blacklist and fixuplist files, extend the tournament list syntax used by
those files with an appropriate extension to allow that
eg "@#2008 [email protected] Open#Berlin" -> if the first character is a '@' then the 2nd
character replaces @ as the Event/Site separator.
*/
/*
Define (only) one of the following options to select which program to build
*/
#define PGN2LINE // Convert one or more PGN files into a single file in our new format
//#define LINE2PGN // Convert back to PGN
//#define TOURNAMENTS // A simple utility for extracting tournament names from line file
//#define PLAYERS // A utility for extracting player names from line file
//#define DISKSORT // Just for testing our disksort()
//#define WORDSEARCH // A poor man's grep -w
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <set>
#include <algorithm>
#include "disksort.h"
#include "util.h"
static bool pgn2line( std::string fin, std::string fout, std::string diag_fout,
bool &utf8_bom,
bool append,
bool reverse_order,
bool remove_zero_length,
bool remove_zero_length_allow_bye,
bool remove_unfixed_players_flag,
int year_before,
int year_after,
const std::set<std::string> &whitelist,
const std::set<std::string> &blacklist,
const std::map<std::string,std::string> &fixups,
const std::map<std::string,std::string> &name_fixups );
static void line2pgn( std::string fin, std::string fout );
static void tournaments( std::string fin, std::string fout, bool bare=false );
static void players( std::string fin, std::string fout, bool bare, bool dups_only );
static bool read_tournament_list( std::string fin, std::vector<std::string> &tournaments, std::vector<std::string> *names=NULL );
static bool test_date_format( const std::string &date, char separator );
static bool parse_date_format( const std::string &date, char separator, int &yyyy, int &mm, int &dd );
static bool refine_sort( std::string fin, std::string fout );
static void word_search( bool case_insignificant, std::string word, std::string fin, std::string fout );
static void remove_tie_breaker_and_dups( std::string fin, std::string fout, bool add_utf8_bom_to_output, std::ofstream *p_smart_uniq, bool no_deduping_at_all=false );
static void postponed_dedup_filter( bool flush, const std::string &line, std::ofstream &out, std::ofstream *p_smart_uniq );
#ifdef _DEBUG // for debugging / testing
#define remove(filename) do { remove_nulled_out(filename); } while(false)
void remove_nulled_out( const char *filename )
{
printf( "DEBUG: Temp file %s not removed\n", filename );
}
#endif
int main( int argc, const char *argv[] )
{
util::tests();
#ifdef DISKSORT
bool ok = (argc==3);
if( !ok )
{
printf(
"Simple text file sort\n"
"Usage:\n"
" sort input.txt output.txt\n"
);
return -1;
}
disksort(argv[1],argv[2]);
return 0;
#endif
#ifdef WORDSEARCH
int arg_idx=1;
bool case_insignificant=false;
bool ok = true;
if( argc>1 && std::string(argv[1]) == "-i" )
{
case_insignificant = true;
argc--;
arg_idx=2;
}
if( argc<3 || argc>4 )
ok = false;
if( !ok )
{
printf(
"wordsearch V3.02 (from Github.com/billforsternz/pgn2line)\n"
"Simple text file search for words. Useful for filtering .lpgn files for\n"
"specific players, events etc.\n"
"Usage:\n"
" wordsearch [-i] word input.txt [output.txt]\n"
"-i flag requests a case insignificant search\n"
);
return -1;
}
word_search( case_insignificant, argv[arg_idx],argv[arg_idx+1],argc==4?argv[arg_idx+2]:"");
return 0;
#endif
#ifdef TOURNAMENTS
int arg_idx=1;
bool bare=false;
bool ok = true;
if( argc>1 && std::string(argv[1]) == "-b" )
{
bare = true;
argc--;
arg_idx=2;
}
if( argc<2 || argc>3 )
ok = false;
if( !ok )
{
printf(
"tournaments V3.02 (from Github.com/billforsternz/pgn2line)\n"
"Extract tournament descriptions from files created by pgn2line\n"
"Usage:\n"
" tournaments [-b] input.lpgn [output.txt]\n"
"\n"
"-b requests bare format suitable for use as a whitelist/blacklist file\n"
);
return -1;
}
tournaments( argv[arg_idx], argc==2?"":argv[arg_idx+1], bare );
return 0;
#endif
#ifdef PLAYERS
int arg_idx=1;
bool bare=false;
bool dups_only=false;
bool ok = true;
while( ok && argc>2 )
{
if( std::string(argv[arg_idx]) == "-b" )
bare = true;
else if( std::string(argv[arg_idx]) == "-d" )
dups_only = true;
else
break;
argc--;
arg_idx++;
}
if( argc<2 || argc>3 )
ok = false;
if( !ok )
{
printf(
"players V3.02 (from Github.com/billforsternz/pgn2line)\n"
"Extract player names from pgn files (or lpgn files created by pgn2line)\n"
"Usage:\n"
" players [-b] [-d] input.pgn|lpgn [output.txt]\n"
"\n"
"-b requests bare format suitable for use in a pgn2line fixup file\n"
"-d requests only names with duplicate surnames present\n"
"\n"
"Output is sorted, format is name : count (or just name if -b flag)\n"
"Names without commas are highlighted by adding a \"@ \" prefix\n"
);
return -1;
}
players( argv[arg_idx], argc==2?"":argv[arg_idx+1], bare, dups_only );
return 0;
#endif
#ifdef LINE2PGN
bool ok = (argc==3);
if( !ok )
{
printf(
"line2pgn V3.02 (from Github.com/billforsternz/pgn2line)\n"
"Convert one game per line files generated by companion program pgn2line to pgn\n"
"Usage:\n"
" line2pgn input.lpgn output.pgn\n"
);
return -1;
}
std::string fin(argv[1]);
std::string fout(argv[2]);
if( fin == fout )
{
printf( "Error: input and output filenames are the same.\n" );
return -1;
}
line2pgn(fin,fout);
return 0;
#endif
#ifdef PGN2LINE
// Command line processing
bool remove_zero_length = false;
bool remove_zero_length_allow_bye = false;
bool list_flag = false;
bool reverse_flag = false;
bool pgn_create_flag = false;
bool remove_unfixed_players_flag = false;
bool whitelist_flag = false;
bool smart_uniq = false;
bool no_sort = false;
std::string whitelist_file;
bool blacklist_flag = false;
std::string blacklist_file;
bool fixup_flag = false;
std::string fixup_file;
bool ok = true;
// Unless one or both of these are set on the command line
// yyyy>=year_after && yyyy<=year_before is true
int year_after=-10000, year_before=10000;
#ifdef _DEBUG // for debugging / testing
//smart_uniq = true;
//pgn_create_flag = true;
//list_flag = true;
std::string fin("test-in.pgn");
std::string fout("test-out.lpgn");
#else
int arg_idx=1;
while( ok && argc>1 )
{
if( std::string(argv[arg_idx]) == "-l" )
list_flag = true;
else if( std::string(argv[arg_idx]) == "-r" )
reverse_flag = true;
else if( std::string(argv[arg_idx]) == "-Z" )
remove_zero_length = true;
else if( std::string(argv[arg_idx]) == "-z" )
remove_zero_length_allow_bye = true;
else if( std::string(argv[arg_idx]) == "-d" )
smart_uniq = true;
else if( std::string(argv[arg_idx]) == "-n" )
no_sort = true;
else if( std::string(argv[arg_idx]) == "-p" )
pgn_create_flag = true;
else if( std::string(argv[arg_idx]) == "-2" )
remove_unfixed_players_flag = true;
else if( util::prefix( std::string(argv[arg_idx]),"-f") )
{
fixup_flag = true;
if( std::string(argv[arg_idx]) == "-f" )
{
argc--;
arg_idx++;
fixup_file = std::string(argv[arg_idx]);
}
else
{
fixup_file = std::string(argv[arg_idx]).substr(2);
}
}
else if( util::prefix( std::string(argv[arg_idx]),"-w") )
{
whitelist_flag = true;
if( std::string(argv[arg_idx]) == "-w" )
{
argc--;
arg_idx++;
whitelist_file = std::string(argv[arg_idx]);
}
else
{
whitelist_file = std::string(argv[arg_idx]).substr(2);
}
}
else if( util::prefix( std::string(argv[arg_idx]),"-b") )
{
blacklist_flag = true;
if( std::string(argv[arg_idx]) == "-b" )
{
argc--;
arg_idx++;
blacklist_file = std::string(argv[arg_idx]);
}
else
{
blacklist_file = std::string(argv[arg_idx]).substr(2);
}
}
else if( util::prefix( std::string(argv[arg_idx]),"-y") )
{
if( std::string(argv[arg_idx]) == "-y" )
{
argc--;
arg_idx++;
year_before = atoi(argv[arg_idx]);
}
else
{
year_before = atoi(argv[arg_idx]+2);
}
if( year_before == 0 )
ok = false;
}
else if( util::prefix( std::string(argv[arg_idx]),"+y") )
{
if( std::string(argv[arg_idx]) == "+y" )
{
argc--;
arg_idx++;
year_after = atoi(argv[arg_idx]);
}
else
{
year_after = atoi(argv[arg_idx]+2);
}
if( year_after == 0 )
ok = false;
}
else
break;
argc--;
arg_idx++;
}
if( argc != 3 )
ok = false;
if( !ok || (whitelist_flag&&blacklist_flag) )
{
/*
pgn2line [-l] [-z] [-d] [-n] [-r] [-p]
[-y year_before] [+y year_after] [-w whitelist | -b blacklist]
[-f fixuplist] input output
-l indicates input is a text file that lists input pgn files (else input is a pgn file)
-z indicates don't include zero length games (BYEs are unaffected)
-Z indicates don't include zero length games, including BYEs
-d indicates smart game de-duplication (eliminates more dups)
-n indicates no sorting or de-duping
-r specifies smart reverse sort - yields most recent games first, smart because higher
rounds/boards are adjusted to come first both here and in the conventional sort
order
-p indicates create a .pgn from output (filename is ".pgn" appended to output)
-y discard games unless they are played in year_before or earlier
+y discard games unless they are played in year_after or later
-w specifies a whitelist list of tournaments, discard games not from these tournaments
-b specifies a blacklist list of tournaments, discard games from these tournaments
-f specifies a list of tournament name fixups
-2 flag removes games unless both players have been fixed up (useful for
cleaning online PGNs with a list of some but not all player handles)
*/
printf(
"pgn2line V3.04 (from Github.com/billforsternz/pgn2line)\n"
"Convert pgn file(s) to an intermediate format, one line per game, sorted\n"
"\n"
"Usage:\n"
" pgn2line [-l] [-z] [-d] [-n] [-r] [-p] [-y year_before] [+y year_after]\n"
" [-w whitelist | -b blacklist]\n"
" [-f fixuplist] input output.lpgn\n"
"\n"
"-l indicates input is a text file that lists input pgn files\n"
" (otherwise input is a single pgn file)\n"
"-z indicates don't include zero length games (BYEs are unaffected)\n"
"-Z indicates don't include zero length games, including BYEs\n"
"-d indicates smart game de-duplication (eliminates more dups)\n"
"-n indicates no sorting or de-duping\n"
"-r specifies smart reverse sort - yields most recent games first, smart\n"
" because higher rounds/boards are adjusted to come first both here and\n"
" in the conventional sort order\n"
"-p indicates create a .pgn from output (filename is \".pgn\" appended to\n"
" output)\n"
"-y discard games unless they are played in year_before or earlier\n"
"+y discard games unless they are played in year_after or later\n"
"-w specifies a whitelist list of tournaments, discard games not from one\n"
" of these tournaments\n"
"-b specifies a blacklist list of tournaments, discard games from any of\n"
" these tournaments\n"
"-f specifies a list of tournament name fixups\n"
"\n"
"-w -b and -f files are all lists of tournaments in the following format\n"
"\n"
"yyyy Event@Site\n"
"\n"
"In the case of the fixuplist there must be an even number of lines in the\n"
"file because the file is interpreted as a list of before and after pairs\n"
"\n"
"Pairs of before and after player names are now allowed in the fixup file,\n"
"player names are identified as those strings NOT in yyyy Event@Site format\n"
"\n"
"-2 flag removes games unless both players have been fixed up (useful for\n"
" cleaning online PGNs with a list of some but not all player handles)\n"
"\n"
"Output is all games found in one game per line format, sorted. The .lpgn\n"
"extension shown is just a suggested convention\n"
"\n"
"See also companion programs line2pgn, wordsearch, tournaments and players\n"
);
return -1;
}
std::string fin(argv[arg_idx]);
std::string fout(argv[arg_idx+1]);
#endif
if( fin == fout )
{
printf( "Error: input and output filenames are the same.\n" );
return -1;
}
// Read tournament files
std::set<std::string> whitelist;
std::set<std::string> blacklist;
std::map<std::string,std::string> fixups;
std::map<std::string,std::string> name_fixups;
if( whitelist_flag )
{
std::vector<std::string> temp;
ok = read_tournament_list( whitelist_file, temp );
for( unsigned int i=0; ok && i<temp.size(); i++ )
whitelist.insert(temp[i]);
}
if( ok && blacklist_flag )
{
std::vector<std::string> temp;
ok = read_tournament_list( blacklist_file, temp );
for( unsigned int i=0; ok && i<temp.size(); i++ )
blacklist.insert(temp[i]);
}
std::string diag_fout;
if( ok && fixup_flag )
{
std::vector<std::string> temp;
std::vector<std::string> names;
ok = read_tournament_list( fixup_file, temp, &names );
if( ok && temp.size()%2 != 0 )
{
printf( "Error; Odd number of tournaments in fixup table, should be before and after pairs\n" );
ok = false;
}
else
{
for( unsigned int i=0; ok && i<temp.size(); i+=2 )
fixups.insert( std::pair<std::string,std::string>(temp[i],temp[i+1]) );
}
if( ok && names.size()%2 != 0 )
{
printf( "Error; Odd number of player names in fixup table, should be before and after pairs\n" );
ok = false;
}
else
{
if( names.size() > 0 )
{
diag_fout = fout + "-name-fixups.txt";
printf( "All player name fixups will be listed in file %s\n", diag_fout.c_str() );
}
for( unsigned int i=0; ok && i<names.size(); i+=2 )
name_fixups.insert( std::pair<std::string,std::string>(names[i],names[i+1]) );
}
}
if( !ok )
return -1;
unsigned int seed = static_cast<unsigned int>( time(NULL) );
srand(seed);
int r1=rand();
int r2=rand();
while( r1 == r2 )
r2=rand();
std::string temp1_fout = util::sprintf( "%s-temp-filename-pgn2line-presort-%05d.tmp", fout.c_str(), r1 );
std::string temp2_fout = util::sprintf( "%s-temp-filename-pgn2line-postsort-%05d.tmp", fout.c_str(), r2 );
ok = false;
printf( "pgn2line V3.04 (from Github.com/billforsternz/pgn2line)\n" );
bool all_utf8_bom = true;
if( !list_flag )
{
printf( "Processing 1 pgn file\n" );
ok = pgn2line( fin, temp1_fout, diag_fout,
all_utf8_bom,
false,
reverse_flag,
remove_zero_length,
remove_zero_length_allow_bye,
remove_unfixed_players_flag,
year_before,
year_after,
whitelist,
blacklist,
fixups,
name_fixups
);
}
else
{
std::ifstream in(fin);
if( !in )
{
printf( "Error; Cannot open list file %s\n", fin.c_str() );
return -1;
}
std::vector<std::string> pgn_files;
int line_number = 0;
for(;;)
{
std::string line;
if( !std::getline(in,line) )
break;
// Strip out UTF8 BOM mark (hex value: EF BB BF)
if( line_number==0 && line.length()>=3 && line[0]==-17 && line[1]==-69 && line[2]==-65)
line = line.substr(3);
line_number++;
util::ltrim(line);
util::rtrim(line);
if( line != "" )
pgn_files.push_back(line);
}
int nbr_files = pgn_files.size();
bool append=false;
int file_number=1;
ok = false;
for( std::string line : pgn_files )
{
printf( "Processing %d of %d pgn file%s\r", file_number++, nbr_files, nbr_files==1?"":"s" );
bool utf8_bom;
bool any = pgn2line( line, temp1_fout, diag_fout,
utf8_bom,
append,
reverse_flag,
remove_zero_length,
remove_zero_length_allow_bye,
remove_unfixed_players_flag,
year_before,
year_after,
whitelist,
blacklist,
fixups,
name_fixups );
if( any ) // don't give up unless none of the files are processed
{
ok = true;
if( !utf8_bom )
all_utf8_bom = false;
}
append = true;
}
}
if( !ok )
return -1;
bool add_utf8_bom_to_output = all_utf8_bom;
if( no_sort )
{
printf( "Removing tie breaker field\n");
remove_tie_breaker_and_dups( temp1_fout, fout, add_utf8_bom_to_output, NULL, true );
remove( temp1_fout.c_str() );
}
else
{
std::ofstream out_smart_uniq;
std::string smart_uniq_msg;
if( smart_uniq )
{
std::string dedup_fout = "dedup-" + fout;
smart_uniq_msg = util::sprintf( ", use file %s to review smart de-duplication decisions", dedup_fout.c_str() );
out_smart_uniq.open( dedup_fout.c_str() );
if( !out_smart_uniq )
{
printf( "Warning; Cannot open smart deduplication file %s for writing, so smart dedup disabled\n", dedup_fout.c_str() );
smart_uniq_msg = "";
}
}
std::ofstream *p_smart_uniq = (smart_uniq && out_smart_uniq) ? &out_smart_uniq : 0;
printf( "%sStarting sort\n", list_flag?"\n":"" ); // list_flag = newline needed
disksort( temp1_fout, temp2_fout );
remove( temp1_fout.c_str() );
printf( "Sort complete\n");
printf( "Starting refinement sort\n");
refine_sort( temp2_fout, temp1_fout );
printf( "Refinement sort complete\n");
remove( temp2_fout.c_str() );
if( reverse_flag )
{
printf( "Starting reversal sort\n");
disksort( temp1_fout, temp2_fout, true );
printf( "Reversal sort complete\n");
remove( temp1_fout.c_str() );
printf( "Removing tie breaker field and dups%s\n", smart_uniq_msg.c_str() );
remove_tie_breaker_and_dups( temp2_fout, fout, add_utf8_bom_to_output, p_smart_uniq );
remove( temp2_fout.c_str() );
}
else
{
printf( "Removing tie breaker field and dups%s\n", smart_uniq_msg.c_str() );
remove_tie_breaker_and_dups( temp1_fout, fout, add_utf8_bom_to_output, p_smart_uniq );
remove( temp1_fout.c_str() );
}
}
if( pgn_create_flag )
line2pgn( fout, fout + ".pgn" );
return 0;
#endif
}
class Game
{
public:
static unsigned int game_count;
Game() {clear();}
void clear();
void process_header_line( const std::string &line );
void process_moves_line( const std::string &line );
bool is_game_non_zero_length();
bool is_game_non_zero_length_or_BYE();
bool is_both_players_fixed();
std::string get_game_as_line(bool reverse_order);
void fixup_tournament( const std::map<std::string,std::string> &fixup_list );
void fixup_names( const std::map<std::string,std::string> &fixup_list, std::ofstream *p_out_diag );
std::string get_yyyy_event_at_site();
std::string get_prefix(bool reverse_order);
std::string get_description();
int yyyy = 2000;
private:
std::string get_event_header();
std::string get_site_header();
std::string headers;
std::string moves;
std::string eventx;
std::string site;
std::string white;
std::string black;
std::string date;
std::string year;
std::string month;
std::string day;
std::string round;
std::string result;
bool both_players_fixed;
int move_txt_len;
unsigned int game_idx;
};
unsigned int Game::game_count = 0;
void Game::clear()
{
headers.clear();
moves.clear();
eventx.clear();
site.clear();
white.clear();
black.clear();
date.clear();
yyyy = 0;
year = "0000";
month = "00";
day = "00";
round.clear();
result.clear();
both_players_fixed = false;
move_txt_len = 0;
game_idx = 0;
}
std::string Game::get_game_as_line(bool reverse_order)
{
std::string s=get_prefix(reverse_order);
s += "@H";
s += get_event_header();
s += "@H";
s += get_site_header();
s += headers;
s += moves;
return s;
}
std::string Game::get_yyyy_event_at_site()
{
std::string s = year;
s += ' ';
s += eventx;
s += '@';
s += site;
return s;
}
void Game::fixup_tournament( const std::map<std::string,std::string> &fixup_list )
{
std::string t = get_yyyy_event_at_site();
bool found=false;
auto it = fixup_list.find(t);
if( it != fixup_list.end() )
{
std::string to = it->second;
auto offset = to.find('@');
assert( offset != std::string::npos );
eventx = to.substr(5,offset-5);
site = to.substr(offset+1);
}
}
void Game::fixup_names( const std::map<std::string,std::string> &fixup_list, std::ofstream *p_out_diag )
{
std::string t = get_yyyy_event_at_site();
int nbr_changes=0;
auto it1 = fixup_list.find(white);
auto it2 = fixup_list.find(black);
if( it1 != fixup_list.end() || it2 != fixup_list.end() )
{
std::string before = get_description();
if( it1 != fixup_list.end() )
{
nbr_changes++;
std::string new_white = it1->second;
std::string from = "@H[White \"" + white + "\"]";
std::string to = "@H[White \"" + new_white + "\"]";
util::replace_once( headers, from, to );
white = new_white;
}
if( it2 != fixup_list.end() )
{
nbr_changes++;
std::string new_black = it2->second;
std::string from = "@H[Black \"" + black + "\"]";
std::string to = "@H[Black \"" + new_black + "\"]";
util::replace_once( headers, from, to );
black = new_black;
}
std::string after = get_description();
if( p_out_diag )
{
std::string
s = util::sprintf( "Name change%s; %s", nbr_changes>1?"s":"", before.c_str() );
util::putline(*p_out_diag,s);
s = util::sprintf( "%s -> %s", nbr_changes>1?" ":"", after.c_str() );
util::putline(*p_out_diag,s);
}
}
both_players_fixed = (nbr_changes==2);
}
std::string Game::get_prefix(bool reverse_order)
{
std::string event_site = eventx;
event_site += ", ";
event_site += site;
util::replace_all( event_site, "#", "##" ); // very important the event and/or site don't happen to contain string " # "
std::string s = year;
s += '-';
s += month;
s += '-';
s += day;
s += ' ';
s += event_site;
s += " # ";
s += year;
s += '-';
s += month;
s += '-';
s += day;
s += ' ';
// eg Round = "3" -> "003" or if reverse order "997"
// eg Round = "3.1" -> "003.001" or if reverse order "997.999"
// eg Round = "3.1.2" -> "003.001.002" or if reverse order "997.999.998"
// The point is to make the text as usefully sortable as possible
std::string sround = round;
size_t offset = sround.find_first_of('.');
while( offset != std::string::npos )
{
std::string temp = sround.substr(0,offset);
int iround = atoi(temp.c_str());
if( reverse_order )
iround = 1000-iround;
temp = util::sprintf("%03d",iround);
s += temp;
s += '.';
sround = sround.substr(offset+1);
offset = sround.find_first_of('.');
}
int iround = atoi(sround.c_str());
if( reverse_order )
iround = 1000-iround;
std::string temp = util::sprintf("%03d",iround);
s += temp;
// New feature, append the game idx in original file as a sort tie breaker,
// in case round doesn't have a board number. Eg in a tournament you might
// have Round 3.1, 3.2, 3.3 etc (great). But if you just have Round 3 for
// all these games, without this tie breaker the games end up sorted
// according to White's Surname (not very helpful). The tie breaker means
// that the sort order will be the same as in the original .pgn, which is
// likely to be an improvement over White's surname.
s += ' ';
std::string sgame_idx = util::sprintf("%09u", game_idx);
s += sgame_idx;
// Add " White-Black"
s += ' ';
offset = white.find_first_of(",");
std::string one_word;
if( offset != std::string::npos )
one_word = white.substr(0,offset);
else
one_word = white;
util::replace_all( one_word, " ", "_" );
s += one_word;
s += "-";
offset = black.find_first_of(",");
if( offset != std::string::npos )
one_word = black.substr(0,offset);
else
one_word = black;
util::replace_all( one_word, " ", "_" );
s += one_word;
return s;
}
std::string Game::get_description()
{
std::string s;
s = white;
s += " - ";
s += black;
s += " - ";
s += eventx;
s += ", ";
s += site;
s += ", ";
s += year;
s += '-';
s += month;
s += '-';
s += day;
return s;
}
bool Game::is_game_non_zero_length()
{
return( move_txt_len > static_cast<int>(result.length()) );
}
bool Game::is_game_non_zero_length_or_BYE()
{
if( move_txt_len > static_cast<int>(result.length()) )
return true;
std::string w = util::toupper(white);
std::string b = util::toupper(black);
return( w=="BYE" || b=="BYE" );
}
bool Game::is_both_players_fixed()
{
return both_players_fixed;
}
void Game::process_header_line( const std::string &line )
{
if (game_idx == 0)
game_idx = ++game_count;
bool event_site=false;
bool white_black=false;
std::string key, value;
int from = line.find_first_not_of(' ',1);
int to = line.find_first_of(' ');
if( std::string::npos != from && std::string::npos != to && to>from )
{
key = line.substr( from, to-from );
from = line.find_first_of('\"');
to = line.find_last_of('\"');
if( std::string::npos != from && std::string::npos != to && to>from )
{
value = line.substr( from+1, (to-from)-1 );
if( key == "Event" )
{
event_site = true;
util::trim(value);
eventx = value;
}