-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.cpp
2050 lines (1914 loc) · 68.6 KB
/
core.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
//
// Core of PGN2LINE, to allow creation of PGN rather than LPGN utilities
//
#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::vector<std::string> &vout,
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 );
bool core_pgn2line( std::string fin, std::vector<std::string> &vout )
{
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;
bool utf8_bom = false;
bool append = false;
bool reverse_order = false;
bool remove_zero_length = false;
bool remove_zero_length_allow_bye = false;
bool remove_unfixed_players_flag = false;
int year_before = INT_MAX;
int year_after = INT_MIN;
bool ok = pgn2line( fin, vout,
utf8_bom,
append,
reverse_order,
remove_zero_length,
remove_zero_length_allow_bye,
remove_unfixed_players_flag,
year_before,
year_after,
whitelist,
blacklist,
fixups,
name_fixups );
return ok;
}
static void line2pgn( std::vector<std::string> &vin, std::string fout );
bool core_line2pgn( std::vector<std::string> &vin, std::string fout )
{
line2pgn( vin, fout );
return true;
}
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
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;
}
else if( key == "Site" )
{
event_site = true;
util::trim(value);
site = value;
}
else if( key == "White" )
{
white_black = true;
headers += "@H";
if( util::trim(value) )
{
headers += "[White \"";
headers += value;
headers += "\"]";
}
else
headers += line;
white = value;
}
else if( key == "Black" )
{
white_black = true;
headers += "@H";
if( util::trim(value) )
{
headers += "[Black \"";
headers += value;
headers += "\"]";
}
else
headers += line;
black = value;
}
else if( key == "Date" )
{
bool ok=false;
date = value;
int y,m,d;
ok = parse_date_format( date, '.', y, m, d );
if( ok )
{
yyyy = y;
year = util::sprintf( "%04d", y );
month = util::sprintf( "%02d", m );
day = util::sprintf( "%02d", d );
}
}
else if( key == "Round" )
round = value;
else if( key == "Result" )
result = value;
}
}
if( !event_site && !white_black )
{
headers += "@H";
headers += line;
}
}
void Game::process_moves_line( const std::string &line )
{
move_txt_len += line.length();
moves += "@M";
moves += line;
}
std::string Game::get_event_header()
{
std::string s = "[Event ";
s += '\"';
s += eventx;
s += '\"';
s += ']';
return s;
}
std::string Game::get_site_header()
{
std::string s = "[Site ";
s += '\"';
s += site;
s += '\"';
s += ']';
return s;
}
static bool pgn2line( std::string fin, std::vector<std::string> &vout,
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 )
{
Game game;
utf8_bom = false;
std::ifstream in(fin.c_str());
if( !in )
{
printf( "Error; Cannot open file %s for reading\n", fin.c_str() );
return false;
}
std::ofstream *p_out_diag = NULL;
int line_number=0;
enum {search_for_header,start_header,in_header,process_header,
search_for_moves,in_moves,process_game,
process_game_and_exit,done} state=search_for_header;
std::string line;
bool next_line=true;
while( state != done )
{
// Get next line (unless we haven't fully processed current line)
if( next_line )
{
if( !std::getline(in, line) )
{
if( state == in_moves )
{
state = process_game_and_exit;
printf( "Warning; File: %s, No empty line at end\n", fin.c_str() );
}
else
state = done;
}
else
{
// 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);
utf8_bom = true;
}
util::ltrim(line);
util::rtrim(line);
line_number++;
// Escape out existing '@' characters
if( std::string::npos != line.find('@') ) // a little optimisation, '@' chars are rare
util::replace_all(line, "@", "@$"); // if it is there transform "@" -> "@$"
// line2pgn reverts it back
// (this avoids possible trouble with
// false @H and @M special markers)
}
}
next_line = false; // state machine often involves stepping through states before going to next line
// State machine
switch( state )
{
default:
case done:
{
state = done;
break;
}
case search_for_header:
{
if( util::prefix(line,"[") && util::suffix(line,"]") )
state = start_header;
else
next_line = true;
break;
}
case start_header:
{
game.clear();
state = in_header;
break;
}
case in_header:
{
if( util::prefix(line,"[") && util::suffix(line,"]") )
{
game.process_header_line(line);
next_line = true;
}
else
{
// All headers are in, apply fixups
if( fixups.size() > 0 )
game.fixup_tournament(fixups);
if( name_fixups.size() > 0 )
game.fixup_names(name_fixups,p_out_diag);
// Next get moves
state = search_for_moves;
if( line != "" )
printf( "Warning; File: %s Line: %d, No gap between header and moves\n", fin.c_str(), line_number );
}
break;
}
case search_for_moves:
{
if( util::prefix(line,"[") && util::suffix(line,"]") )
{
printf( "Warning; File: %s Line: %d, No moves to go with header\n", fin.c_str(), line_number );
state = search_for_header;
}
else if( line != "" )
{
state = in_moves;
}
else
{
next_line = true;
}
break;
}
case in_moves:
{
if( line == "" )
{
state = process_game;
}
else if( util::prefix(line,"[") && util::suffix(line,"\"]") )
{
state = process_game;
printf( "Warning; File: %s Line: %d, No gap between games\n", fin.c_str(), line_number );
}
else
{
game.process_moves_line( line );
next_line = true;
}
break;
}
case process_game:
case process_game_and_exit:
{
state = (state==process_game_and_exit ? done : search_for_header);
bool ok = (game.yyyy>=year_after && game.yyyy<=year_before);
if( ok && remove_zero_length_allow_bye )
ok = game.is_game_non_zero_length_or_BYE();
if( ok && remove_zero_length )
ok = game.is_game_non_zero_length();
if( ok && remove_unfixed_players_flag )
ok = game.is_both_players_fixed();
std::string t = game.get_yyyy_event_at_site();
if( ok && whitelist.size() > 0)
{
ok = false; // discard game unless tournament is in the white list
auto it = whitelist.find(t);
if( it != whitelist.end() )
ok = true; // tournament is in the whitelist
}
if( ok && blacklist.size() > 0 )
{
auto it = blacklist.find(t);
if( it != blacklist.end() )
ok = false; // tournament is in the blacklist
}
if( ok )
{
std::string line_out = game.get_game_as_line(reverse_order);
vout.push_back(line_out);
}
break;
}
}
}
return true;
}
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 )
{
/*
Line by line transformation
In: 2001-12-28 Acme Open, Gotham # 2001-12-31 003.002.001 000000001 Smith-Jones
Out: 2001-12-28 Acme Open, Gotham # 2001-12-31 003.002.001 Smith-Jones
*/
std::ifstream in(fin);
if( !in )
{
printf( "Error; Cannot open file %s for reading\n", fin.c_str() );
return;
}
std::ofstream out(fout);
if( !out )
{
printf( "Error; Cannot open file %s for writing\n", fout.c_str() );
return;
}
if( add_utf8_bom_to_output )
out.write( "\xef\xbb\xbf", 3 );
for(;;)
{
std::string line;
std::string line_out;
bool expected_format = false;
if( !std::getline(in,line) )
break;
std::string prefix_end = " # "; // we double up earlier '#' chars to make sure
// this doesn't occur earlier in prefix
size_t offset = line.find( prefix_end );
if( offset != std::string::npos )
{
offset += 3;
size_t offset2 = line.find( ' ', offset );
if( offset2!=std::string::npos && offset2==offset+10 )
{
offset2++;
size_t offset3 = line.find( ' ', offset2 );
if( offset3 != std::string::npos )
{
offset3++;
size_t offset4 = line.find( ' ', offset3 );
if( offset4!=std::string::npos && offset4==offset3+9 )
{
offset4++;
expected_format = true;
for( int i=0; expected_format && i<9; i++ )
{
char c = line[offset3+i];
expected_format = (isascii(c) && isdigit(c));
}
if( expected_format )
line_out = line.substr(0,offset3) + line.substr(offset4);
}
}
}
}
if( !expected_format )
line_out = line;
if( !no_deduping_at_all )
postponed_dedup_filter( false,line_out,out,p_smart_uniq );
else
util::putline( out,line_out ); // straight out without going through dedup filter
}
if( !no_deduping_at_all )
postponed_dedup_filter(true, "", out, p_smart_uniq );
}
static void line2pgn( std::vector<std::string> &vin, std::string fout )
{
Game game;
std::ofstream out(fout);
if( !out )
{
printf( "Error; Cannot open file %s for writing\n", fout.c_str() );
return;
}
enum {in_prefix1,in_prefix2,in_header1,in_header2,in_moves1,in_moves2,finished} state=in_prefix1, old_state=in_prefix2;
bool first_line = true;
for( std::string line: vin )
{
std::string line_out;
const char *p = line.c_str();
state=in_prefix1;
old_state=in_prefix2;
for(;;)
{
bool finished_header = false;
bool finished_moves = false;
char c = *p++;
old_state = state;
switch( state )
{
case in_prefix1:
{
if( c == '\0' )
state = finished;
else if( c == '@' )
state = in_prefix2;
break;
}
case in_prefix2:
{
if( c == '\0' )
state = finished;
else if( c == 'H' )
state = in_header1;
else
state = in_prefix1; //go back
break;
}
case in_header1:
{
if( c == '\0' )
{
finished_header = true;
state = finished;
}
else if( c == '@' )
state = in_header2;
else
line_out += c;
break;
}
case in_header2:
{
if( c == '\0' )
{
finished_header = true;
state = finished;
}
else if( c == 'H' )
{
finished_header = true;
state = in_header1;
}
else if( c == 'M' )
{
finished_header = true;
state = in_moves1;
}
else
{
state = in_header1; // @$ -> @ (normal @ character in data - not @H or @M),
line_out += '@'; // so we expect c == '$' but not much point checking
}
break;
}
case in_moves1:
{
if( c == '\0' )
{
finished_moves = true;
state = finished;
}
else if( c == '@' )
state = in_moves2;
else
line_out += c;
break;
}
case in_moves2:
{
if( c == '\0' )
{
finished_moves = true;
state = finished;
}
else if( c == 'M' )
{
finished_moves = true;
state = in_moves1;
}
else
{
state = in_moves1; // @$ -> @ (normal @ character in data - not @H or @M),
line_out += '@'; // so we expect c == '$' but not much point checking
}
break;
}
}
if( state != old_state )
{
if( finished_header )
{
util::putline(out,line_out);
line_out.clear();
if( state == in_moves1 )
util::putline(out,"");
}
if( finished_moves )
{
util::putline(out,line_out);
line_out.clear();
if( state == finished )
util::putline(out,"");
}
}
if( c == '\0' )
break;
}
}
}
static void tournaments( std::string fin, std::string fout, bool bare )
{
std::ifstream in(fin.c_str());
if( !in )
{
printf( "Error; Cannot open file %s for reading\n", fin.c_str() );
return;
}
std::ostream* fp = &std::cout;
std::ofstream out;
if( fout != "" )
{
out.open(fout);
if( out )
fp = &out;
else
{
printf( "Error; Cannot open file %s for writing\n", fout.c_str() );
return;
}
}
int nbr_games = 0;
int total_games = 0;
enum {first_time_thru,wait_for_tournament,in_tournament,new_tournament,
print_tournament,print_tournament_and_finish,finished
} state=first_time_thru;
bool have_tournament=false;
std::string line;
std::string line_tournament;
std::string tournament;
std::string tournament_list_form;
int line_number=0;
while( state != finished )
{
bool replay_line=false;
switch( state )
{
case first_time_thru:
{
state = wait_for_tournament;
break;
}
case wait_for_tournament:
{
if( have_tournament )
{
replay_line = true;
state = new_tournament;
}
break;
}
case new_tournament:
{
state = in_tournament;
tournament = line_tournament;
nbr_games = 1;
total_games++;
// Ironically, getting the "bare" tournament description is much harder
// because it's not just the prefix before " # "
tournament_list_form = tournament; // fallback
if( bare )
{
// Extract Event and Site from headers - pattern is; a Event b Site c
std::string a="@H[Event \"";
std::string b="\"]@H[Site \"";
std::string c="\"]@";
size_t a_offset = line.find(a);
if( a_offset != std::string::npos )
{
size_t b_offset = line.find(b,a_offset+a.length());
if( b_offset != std::string::npos )
{
size_t c_offset = line.find(c,b_offset+b.length());
if( c_offset != std::string::npos )
{
size_t event_offset = a_offset + a.length();
size_t event_length = b_offset-event_offset;
size_t site_offset = b_offset + b.length();
size_t site_length = c_offset-site_offset;
std::string eventx = line.substr(event_offset,event_length);
std::string site = line.substr(site_offset,site_length);
std::string yyyy = line.substr(0,4);
std::string s;
tournament_list_form = util::sprintf( "%s %s@%s", yyyy.c_str(), eventx.c_str(), site.c_str() );
}
}
}
}
break;
}
case in_tournament:
{
if( tournament == line_tournament )
{
nbr_games++;
total_games++;
}
else
{
replay_line = true;
state = print_tournament;
}
break;
}
case print_tournament:
case print_tournament_and_finish:
{
replay_line = true;
if( state == print_tournament_and_finish )
state = finished;
else
state = have_tournament ? new_tournament : wait_for_tournament;
std::string s;
if( bare )
s = util::sprintf( "%s", tournament_list_form.c_str() );
else
s = util::sprintf( "%s (%d game%s)", tournament.c_str(), nbr_games, nbr_games==1?"":"s" );
util::putline(*fp,s);
break;
}
}
if( !replay_line )
{
if( !std::getline(in,line) )
state = (state==in_tournament ? print_tournament_and_finish : finished);
else
{
// 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++;
std::string prefix_end = " # "; // we double up earlier '#' chars to make sure
// this doesn't occur earlier in prefix
size_t prefix_end_offset=0;
prefix_end_offset = line.find( prefix_end );
have_tournament = (prefix_end_offset != std::string::npos);
line_tournament = have_tournament ? line.substr(0,prefix_end_offset) : "";
}