Source

Tarrasch Chess GUI / src / GameDocument.cpp

Full commit
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
/****************************************************************************
 * Full game representation
 *  Author:  Bill Forster
 *  Licence: See licencing information in ChessPosition.cpp
 *  Copyright 2010, Triple Happy Ltd.  All rights reserved.
 ****************************************************************************/
#define _CRT_SECURE_NO_DEPRECATE
#include "Appdefs.h"
#include "Canvas.h"
#include "Repository.h"
#include "Objects.h"
#include "DebugPrintf.h"
#include "ChessRules.h"
#include "GameLogic.h"
#include "Lang.h"
#include "GameDocument.h"
using namespace std;
using namespace thc;

GameDocument::GameDocument( GameLogic *gl )
                : gv(gl)
{
    this->gl = gl;
    ChessPosition initial_position;
    Init(initial_position);
}

GameDocument::GameDocument()
{
    this->gl = objs.gl;
    ChessPosition initial_position;
    Init(initial_position);
}

void GameDocument::Init( const ChessPosition &start_position )
{
    game_details_edited = false;
    modified            = false;
    current_game        = false;
    in_memory  = false;
    focus      = false;
    selected   = false;
    pgn_handle = 0;
    game_nbr   = 0;
    sort_idx   = 0;
    white     = "";
    black     = "";
    event     = "";
    site      = "";
    date      = "";
    round     = "";
    result    = "";
    eco       = "";
    white_elo = "";
    black_elo = "";
    this->start_position = start_position;
    this->master_position = start_position;
    fposn1 = 0;
    fposn2 = 0;
    fposn3 = 0;
    moves_txt = "";
    tree.Init( this->start_position );
    Rebuild();
}

void GameDocument::FleshOutDate()
{
    if( date=="" )
    {
        time_t timer = time(NULL);
        struct tm *ptime = localtime( &timer );
        int yyyy = ptime->tm_year+1900;
        int mm   = ptime->tm_mon+1;
        int dd   = ptime->tm_mday;
        char buf[20];
        sprintf( buf, "%04d.%02d.%02d", yyyy, mm, dd );
        date = buf;
    }
}

void GameDocument::FleshOutMoves()
{
    std::string str;
    ToFileTxtGameBody( str );
    int idx = str.find_first_of("\r\n");
    if( idx != std::string::npos )
        str = str.substr(0,idx);
    moves_txt = str;
    LangLine(moves_txt,NULL,LangGet());    // File line is always English, convert to current language
}

int NagAlternative( const char *s )
{
    int nag = 0;
    if( *s == '!' )
    {
        if( 0 == strcmp(s,"!") )        nag=1;  // $1   
        else if( 0 == strcmp(s,"!!") )  nag=3;  // $3   
        else if( 0 == strcmp(s,"!?") )  nag=5;  // $5   
    }
    else if( *s == '?' )
    {
        if( 0 == strcmp(s,"?") )        nag=2;  // $2   
        else if( 0 == strcmp(s,"??") )  nag=4;  // $4   
        else if( 0 == strcmp(s,"?!") )  nag=6;  // $6   
    }
    else if( *s == '=' )
    {
        if( 0 == strcmp(s,"=") )        nag=10;  // $10  
        else if( 0 == strcmp(s,"=+") )  nag=15;  // $15  
    }
    else if( *s == '+' )
    {
        if( 0 == strcmp(s,"+=") )       nag=14;  // $14  
        else if( 0 == strcmp(s,"+/-") ) nag=16;  // $16  
        else if( 0 == strcmp(s,"+-")  ) nag=18;  // $18  
    }
    else if( *s == '-' )
    {
        if( 0 == strcmp(s,"-/+") )      nag=17;  // $17  
        else if( 0 == strcmp(s,"-+") )  nag=19;  // $19  
    }
    return nag;
}


bool PgnTestResult( const char *s )
{
    bool is_pgn_result = false;
    if( 0 == strcmp(s,"1-0") )
        is_pgn_result = true;
    else if( 0 == strcmp(s,"0-1") )
        is_pgn_result = true;
    else if( 0 == strcmp(s,"1/2-1/2") )
        is_pgn_result = true;
    else if( 0 == strcmp(s,"*") )
        is_pgn_result = true;
    return is_pgn_result;    
}

/*
bool PgnTestResult( const char *s, PGN_RESULT &pgn_result )
{
    bool is_pgn_result = false;
    pgn_result = PGN_RESULT_NULL;
    if( 0 == strcmp(s,"1-0") )
    {
        pgn_result = PGN_RESULT_WHITE_WIN;
        is_pgn_result = true;
    }
    else if( 0 == strcmp(s,"0-1") )
    {
        pgn_result = PGN_RESULT_BLACK_WIN;
        is_pgn_result = true;
    }
    else if( 0 == strcmp(s,"1/2-1/2") )
    {
        pgn_result = PGN_RESULT_DRAW;
        is_pgn_result = true;
    }
    else if( 0 == strcmp(s,"*") )
    {
        pgn_result = PGN_RESULT_NULL;
        is_pgn_result = true;
    }
    return is_pgn_result;    
}

*/

std::string RemoveLineEnds( std::string &s )
{
    std::string t;
    int len=s.length();
    bool in_white=false;
    for( int i=0; i<len; i++ )
    {
        char c = s[i];
        if( c=='\n' || c=='\r' )
        {
            if( !in_white )
                t += ' ';
            in_white = true;
        }
        else
        {
            t += c;
            in_white = (c==' ');
        }
    }
    return t;
}

bool GameDocument::PgnParse( bool use_semi, int &nbr_converted, const std::string str, thc::ChessRules &cr, VARIATION *pvar, bool use_current_language, int imove )
{

    // Main state machine has these states
    enum PSTATE
    {
        BETWEEN_MOVES,
        IN_COMMENT,
        IN_DOLLAR,
        IN_NUMBER,
        IN_MISC,
        IN_STAR,
        IN_MOVE
    };

    // Key state variables
 // VARIATION   *pvar;          // the current variation, within this->tree
 // ChessRules   cr;            // the current chess position
    PSTATE       state;         // the current state machine state

    // Allow stacking of the key state variables    
    const int MAX_DEPTH=20;
    struct STACK_ELEMENT
    {
        PSTATE     state;
        VARIATION  *pvar;
        ChessRules cr;

        // these vars are for locating starting point in tree only
        ChessRules cr_variation_start;
        vector<VARIATION>::iterator v;
        vector<VARIATION>::iterator vend;
        vector<MoveTree>::iterator m;
        vector<MoveTree>::iterator mend;
    };
    STACK_ELEMENT stk_array[MAX_DEPTH+1];
    int stk_idx = 0;
    STACK_ELEMENT *stk = &stk_array[stk_idx];

    // Misc
    #define Error(x)
    std::string move_str;
    std::string comment_str;
    std::string buffered_comment;
    std::string prefix;
    char comment_ch='\0', previous_ch='\0';
    int nag_value=0;
    PSTATE old_state, save_state=BETWEEN_MOVES;
    char ch, push_back='\0';
    int str_idx=0;
    bool was_empty = false;
    nbr_converted = 0;
    MoveTree *add_error_comment_here = NULL;
    if( pvar && imove>=0 )
        add_error_comment_here = &(*pvar)[imove];

    // If not starting within the tree, start at the root of the tree
    if( pvar==NULL || imove==-1 )
    {
        was_empty = true;
        tree.Init( start_position );
        pvar = &tree.variations[0]; // set pointer to current main variation
        cr = start_position;
    }

    // Else locate our position in the tree
    else
    {
        stk->v      = tree.variations.begin();
        stk->vend   = tree.variations.end();
        stk->cr_variation_start = *tree.root;
        stk->state  = BETWEEN_MOVES;
        stk->m      = stk->v->begin();
        stk->mend   = stk->v->end();
        stk->cr     = stk->cr_variation_start;
        bool done=false;
        bool error=false;
        while( !done )
        {

            // Move loop
            while( stk->m != stk->mend )
            {
                VARIATION &v1 = *pvar;
                VARIATION &v2 = *(stk->v);
                stk->pvar = &v2;
                MoveTree  &m1 =  (*pvar)[imove];
                MoveTree  &m2 = *(stk->m);
                DebugPrintf(( "%s\n", stk->cr.squares ));
                DebugPrintf(( "%d [%s%s]\n", stk_idx, stk->cr.white?"":"...", stk->m->game_move.move.NaturalOut( &stk->cr ).c_str() ));
                stk->cr.PushMove( stk->m->game_move.move );
                if( &v1==&v2 && &m1==&m2 )
                {
                    done = true;
                    break;
                }
                if( stk->m->variations.size() == 0 )
                    stk->m++;
                else if( stk_idx+1 >= MAX_DEPTH )
                {
                    error = true;
                    done = true;
                    break;
                }
                else
                {
                    vector<MoveTree>::iterator m = stk->m++;
                    stk = &stk_array[++stk_idx];
                    stk->v      = m->variations.begin();
                    stk->vend   = m->variations.end();
                    stk->m      = stk->v->begin();
                    stk->mend   = stk->v->end();
                    stk->state  = BETWEEN_MOVES;
                    stk->cr     = stk_array[stk_idx-1].cr;
                    stk->cr.PopMove( m->game_move.move );
                    stk->cr_variation_start = stk->cr;
                }
            }

            // End of move loop
            if( !done )
            {

                // If there is another variation, start it
                stk->v++;
                if( stk->v != stk->vend )
                {
                    stk->m      = stk->v->begin();
                    stk->mend   = stk->v->end();
                    stk->cr     = stk->cr_variation_start;
                }

                // Else if in variation, return to mainline
                else
                {
                    if( stk_idx == 0 )
                        done = true;
                    else
                        stk = &stk_array[--stk_idx];
                }
            }
        }
        if( error )
        {
            stk = &stk_array[stk_idx=0];
            tree.Init( start_position );
            pvar = &tree.variations[0]; // set pointer to current main variation
            cr = start_position;
        }
        else
        {
            pvar = stk->pvar;
            cr = stk->cr;
        }
    }
    state = BETWEEN_MOVES;      // state machine
    old_state = BETWEEN_MOVES;

    // Start loop
    bool okay=true;
    bool eof=false;
    ch = ' ';   // dummy to start loop
    while( okay && !eof )
    {
        push_back = '\0';
        old_state = state;
        if( ch == '\x96' )  // something that looks a lot like a '-', sometimes used instead of '-'
            ch = '-';
        bool in_number = isascii(ch) && isdigit(ch);
        bool in_move   = isascii(ch) && isalnum(ch);
        bool in_misc   = (ch=='.'||ch=='?'||ch=='!'||ch=='+'||ch=='-'||ch=='='||ch=='/');
        bool in_star   = (ch=='*');
        switch( state )
        {

            // In a comment
            case IN_COMMENT:
            {

                // End of the comment ?
                if(  (comment_ch=='{' && ch=='}') ||
                     (comment_ch==';' && ch!=';' && ch!='\n' && ch!='\r' && (previous_ch=='\n'||previous_ch=='\r') )
                  )
                {
                    if( comment_ch == ';' )
                        push_back = ch;
                    if( (*pvar).size() == 0 )
                    {
                        if( 0 == buffered_comment.length() )
                            buffered_comment = comment_str;
                        else
                        {
                            buffered_comment += " ";
                            buffered_comment += comment_str;
                        }
                    }
                    else
                    {
                        MoveTree *plast_move = &(*pvar)[(*pvar).size()-1];
                        if( 0 == plast_move->game_move.comment.length() )
                            plast_move->game_move.comment = comment_str;
                        else
                        {
                            plast_move->game_move.comment += " ";
                            plast_move->game_move.comment += comment_str;
                        }
                    }
                    state = save_state;
                }

                // Else continue comment
                else
                {
                    bool skip = (comment_ch==';' && ch==';' && (previous_ch=='\n'||previous_ch=='\r') );
                    if( !skip )
                    {
                        if( ch == '\n' )
                            comment_str += ' ';
                        else if( ch != '\r' )
                            comment_str += (char)ch;
                    }
                }
                break;
            }

            // Creating NAG value
            case IN_DOLLAR:
            {
                if( isascii(ch) && isdigit(ch) )
                    nag_value = nag_value*10+(ch-'0');
                else
                {
                    /*
                    const char *nag_array[] =
                    {
                        "",
                        " !",     // $1   
                        " ?",     // $2   
                        " !!",    // $3   
                        " ??",    // $4   
                        " !?",    // $5   
                        " ?!",    // $6   
                        "",       // $7   
                        "",       // $8   
                        " ??",    // $9   
                        " =",     // $10  
                        " =",     // $11  
                        " =",     // $12  
                        "",       // $13  
                        " +=",    // $14  
                        " =+",    // $15  
                        " +/-",   // $16  
                        " -/+",   // $17  
                        " +-",    // $18  
                        " -+",    // $19  
                        " +-",    // $20  
                        " -+"     // $21
                    };  */
                    if( 1<=nag_value && nag_value<=9 && (*pvar).size() != 0 )
                    {
                        MoveTree *plast_move = &(*pvar)[(*pvar).size()-1];
                        plast_move->game_move.nag_value1 = nag_value;
                    }
                    else if( 10<=nag_value && nag_value<=21 && (*pvar).size() != 0 )
                    {
                        MoveTree *plast_move = &(*pvar)[(*pvar).size()-1];
                        plast_move->game_move.nag_value2 = nag_value;
                    }
                    push_back = ch;
                    state = save_state;
                }
                break;
            }

            // Waiting for something to happen
            case BETWEEN_MOVES:
            {

                // NAG token ?
                if( ch == '$' )
                {
                    save_state = state;
                    state = IN_DOLLAR;
                    nag_value = 0;
                }

                // Start {comment} style comment ?
                else if( ch == '{' )
                {
                    save_state = state;
                    comment_ch = '{';
                    state = IN_COMMENT;
                    comment_str = "";
                }

                // Start ;comment style comment ?
                else if( use_semi && ch == ';' )
                {
                    save_state = state;
                    comment_ch = ';';
                    state = IN_COMMENT;
                    comment_str = "";
                }

                // Start new variation ?
                else if( ch == '(' )
                {

                    // Push current state onto a stack
                    stk->pvar  = pvar;
                    stk->cr    = cr;
                    stk->state = state;
                    if( stk_idx+1 >= MAX_DEPTH )
                    {
                        Error("Too deep");
                        okay = false;
                    }
                    else
                    {
                        stk_idx++;
                        stk = &stk_array[stk_idx];
                        imove = (imove==-1 ? (*pvar).size()-1 : imove); 
                        if( imove < 0 )
                        {
                            Error("Cannot branch from empty variation");
                            okay = false;
                        }
                        if( okay )
                        {
                            MoveTree *pnode = &(*pvar)[imove];
                            imove = -1;

                            // Undo the last move to start the new branch
                            cr.PopMove( (*pnode).game_move.move );    

                            // Start a new, currently empty, variation
                            VARIATION variation;
                            variation.clear();
                            (*pnode).variations.push_back(variation);

                            // Set that as the current variation
                            int vlen = (*pnode).variations.size();
                            pvar = &(*pnode).variations[vlen-1];
                        }
                    }
                }

                // End variation ?
                else if( ch == ')' )
                {
                    imove = -1;     // end start in middle feature

                    // Pop old state off stack
                    if( stk_idx == 0 )
                    {
                        Error("Mismatched )");
                        okay = false;
                    }
                    else
                    {
                        stk_idx--;
                        stk   = &stk_array[stk_idx];
                        cr    = stk->cr;
                        state = stk->state;
                        VARIATION  *pvar_just_added = pvar;
                        pvar  = stk->pvar;

                        // If variation we added was empty, remove it
                        int idx = (*pvar).size()-1;
                        if( idx >= 0 )
                        {
                            MoveTree *pnode = &(*pvar)[idx];
                            int vlen = (*pnode).variations.size();
                            if( vlen > 1 )
                            {
                                VARIATION *pvar_end = &(*pnode).variations[vlen-1];
                                if( pvar_just_added==pvar_end && (*pvar_just_added).size()==0 )
                                    (*pnode).variations.pop_back();
                            }
                        }
                    }
                }

                // Else go into token if possible
                else
                {
                    if( in_number || in_misc || in_star || in_move )
                    {
                        move_str = "";
                        push_back = ch;
                        if( in_number )
                            state = IN_NUMBER;
                        else if( in_move )
                            state = IN_MOVE;
                        else if( in_misc )
                            state = IN_MISC;
                        else if( in_star )
                            state = IN_STAR;
                    }
                }
                break;
            }

            // Collect a token
            case IN_NUMBER:
            case IN_MISC:
            case IN_STAR:
            case IN_MOVE:
            {
                bool keep_buffering=false;
                if( state == IN_NUMBER )
                    keep_buffering = in_number || ch=='-' || ch=='/';   // eg 0-1 or 1/2-1/2
                else if( state == IN_MISC )
                    keep_buffering = in_misc;
                else if( state == IN_STAR )
                    keep_buffering = in_star;
                else if( state == IN_MOVE )
                {
                    if( ch=='=' || ch=='+' || ch=='#' || ch=='-' )  // can also be in moves
                        keep_buffering = true;
                    else
                        keep_buffering = in_move;
                }
                if( keep_buffering )
                    move_str += (char)ch;
                else
                {
                    push_back = ch;
                    bool was_in_move = (state==IN_MOVE);
                    bool do_nothing_move = false;

                    // Support some popular variants
                    if( state == IN_NUMBER )
                    {
                        if( move_str == "0-0" )
                        {
                            move_str = "O-O";
                            was_in_move = true;
                        }
                        else if( move_str=="0-0-0" )
                        {
                            move_str = "O-O-O";
                            was_in_move = true;
                        }
                    }
                    else if( state == IN_MISC )
                    {
                        if( move_str == "--" )     // do nothing or pass move
                        {
                            do_nothing_move = true;
                            was_in_move = true;
                        }

                        // Support '?', '!!' etc as text rather than only as NAG codes        
                        int nag_value = NagAlternative(move_str.c_str());
                        if( 1<=nag_value && nag_value<=9 && (*pvar).size() != 0 )
                        {
                            MoveTree *plast_move = &(*pvar)[ imove==-1 ? (*pvar).size()-1 : imove ];
                            plast_move->game_move.nag_value1 = nag_value;
                            prefix = "";
                            nbr_converted++;    // so just a lone ! for example counts
                        }
                        else if( 10<=nag_value && nag_value<=21 && (*pvar).size() != 0 )
                        {
                            MoveTree *plast_move = &(*pvar)[ imove==-1 ? (*pvar).size()-1 : imove ];
                            plast_move->game_move.nag_value2 = nag_value;
                            prefix = "";
                            nbr_converted++;    // so just a lone += for example counts
                        }
                    }
                    state = BETWEEN_MOVES;
                    if( PgnTestResult(move_str.c_str()) )
                    {
                        eof = true;     // just stop (a bit simplistic)
                    }
                    else if( was_in_move )
                    {
                        bool adding_from_middle_to_end_bug = false;
                        if( imove!=-1 && imove!=(*pvar).size()-1 )
                            adding_from_middle_to_end_bug = true;
                        if( adding_from_middle_to_end_bug )
                            okay = false;
                        else
                        {
                            imove = -1;     // end start in middle feature

                            // Try to add move to current variation
                            MoveTree node;
                            std::string temp = move_str;
                            if( use_current_language )
                                LangToEnglish(temp);
                            if( !do_nothing_move )
                                okay = node.game_move.move.NaturalIn(&cr,temp.c_str());
                            else
                            {   // Nasty little hack - support "--" = do nothing, create a move from one empty square
                                //  to same empty square, capturing empty - chess engine will "play" that okay
                                okay = false;
                                for( int i=63; i>=0; i-- )  // start search at h1 to avoiding a8a8 which is Invalid move
                                {   // found an empty square yet ?
                                    if( cr.squares[i]==' ' || cr.squares[i]=='.' )  // plan to change empty from ' ' to '.', so be prepared
                                    {   // C++ can't cast into the bitfield, so do this, aaaaaaaargh
                                        static thc::Square lookup[] = { thc::a8,thc::b8,thc::c8,thc::d8,thc::e8,thc::f8,thc::g8,thc::h8,
                                                                        thc::a7,thc::b7,thc::c7,thc::d7,thc::e7,thc::f7,thc::g7,thc::h7,
                                                                        thc::a6,thc::b6,thc::c6,thc::d6,thc::e6,thc::f6,thc::g6,thc::h6,
                                                                        thc::a5,thc::b5,thc::c5,thc::d5,thc::e5,thc::f5,thc::g5,thc::h5,
                                                                        thc::a4,thc::b4,thc::c4,thc::d4,thc::e4,thc::f4,thc::g4,thc::h4,
                                                                        thc::a3,thc::b3,thc::c3,thc::d3,thc::e3,thc::f3,thc::g3,thc::h3,
                                                                        thc::a2,thc::b2,thc::c2,thc::d2,thc::e2,thc::f2,thc::g2,thc::h2,
                                                                        thc::a1,thc::b1,thc::c1,thc::d1,thc::e1,thc::f1,thc::g1,thc::h1
                                                                      };
                                        node.game_move.move.src =
                                        node.game_move.move.dst = lookup[i];
                                        node.game_move.move.capture = cr.squares[i];  // empty
                                        node.game_move.move.special = NOT_SPECIAL;
                                        okay = true;
                                        break;
                                    }
                                }
                            }        
                            if( !okay )
                            {
                                Error("Illegal move");
                                //prefix += move_str;
                                //prefix += push_back;
                            }
                            else
                            {
                                prefix = "";
                                nbr_converted++;
                                cr.PushMove(node.game_move.move);
                                if( buffered_comment.length() )
                                {
                                    node.game_move.pre_comment = buffered_comment;
                                    buffered_comment.clear();
                                }
                                node.game_move.nag_value1 = 0;
                                node.game_move.nag_value2 = 0;
                                (*pvar).push_back( node );
                                add_error_comment_here = &(*pvar)[(*pvar).size()-1];
                            }
                        }
                    }
                }                        
                break;
            }
        }

        // State changes
        if( state != old_state )
        {
            //fprintf( debug_log_file(), "State change %s->%s\n", ShowState(old_state), ShowState(state) );
        }

        // Error handling, append the rest of the string as a comment
        if( !okay )
        {
            std::string comment = prefix;
            if( str_idx < str.length() )
            {
                std::string temp( str.begin()+str_idx, str.end() );
                int len = temp.length();
                if( len>0 && temp[len-1]==')' )
                    temp = temp.substr(0,len-1);
                comment += temp;
            }
            comment = RemoveLineEnds(comment);
            if( comment != "" )
            {
                if( add_error_comment_here==NULL )
                {
                    int nmoves_mainline = tree.variations[0].size();
                    if( nmoves_mainline == 0 )
                        add_error_comment_here = &tree;
                    else
                        add_error_comment_here = &tree.variations[0][nmoves_mainline-1];
                }

                // If there is an orphaned variation at end, remove it
                if( add_error_comment_here->variations.size() && add_error_comment_here!=&tree )
                    add_error_comment_here->variations.clear();
                if( add_error_comment_here->game_move.comment != "" )
                    add_error_comment_here->game_move.comment += " ";
                add_error_comment_here->game_move.comment += comment;
            }
        }

        // Next character
        else if( !eof )
        {
            if( push_back )
                ch = push_back;
            else
            {
                previous_ch = ch;
                if( str_idx < str.length() )
                {
                    ch = str[str_idx];
                    prefix += ch;
                }
                else
                {
                    ch  = ' ';  // add trailing padding to terminate last token
                    if( str_idx > str.length()+2 )
                        eof = true;   // after a trailing ' ' or so, stop
                }
                str_idx++;
            }
        }
    }
    if( was_empty && okay && buffered_comment!="" )
        tree.game_move.comment = buffered_comment;  // just a comment
    Rebuild();
    gl->atom.Undo();
    in_memory = true;
    gbl_plast_move = NULL;
    if( (*pvar).size() > 0 )
        gbl_plast_move = &(*pvar)[(*pvar).size()-1];
    return okay;
}

// Return ptr to move played if any
MoveTree *GameDocument::MakeMove( GAME_MOVE game_move, bool allow_overwrite )
{
    MoveTree *move_played=NULL;
    unsigned long pos = GetInsertionPoint();
    ChessRules cr = start_position;
    std::string title;
    bool at_move0=true;
    bool empty_with_comment = (!HaveMoves() && tree.game_move.comment!="");
    MoveTree *found = Locate( pos, cr, title, at_move0 );
    int ivar=0;
    int imove=0;
    MoveTree *parent;
    if( found && found!=&tree )
        parent = tree.Parent( found, cr, ivar, imove );
    else
    {
        parent = &tree;
        at_move0 = true;
    }
    if( parent )
    {
        VARIATION &variation = parent->variations[ivar];

        // If making a move from before start in existing main line
        bool special_case = (at_move0 && parent==&tree && variation.size()>0 );

        // Get into position
        for( int i=0; i<imove; i++ )
            cr.PlayMove( variation[i].game_move.move );
        if( !at_move0 )
            cr.PlayMove( variation[imove].game_move.move );
        master_position = cr;

        // Handle special case first
        if( special_case )
        {
            VARIATION new_variation;
            MoveTree node;
            if( game_move.flag_ingame )
            {
                game_move.pre_comment =  objs.repository->player.m_white;
                game_move.pre_comment += "-";
                game_move.pre_comment += objs.repository->player.m_black;
            }
            node.game_move = game_move;
            new_variation.push_back(node);
            variation[imove].variations.push_back( new_variation );
            VARIATION &inplace_variation = variation[imove].variations[variation[imove].variations.size()-1];
            move_played = &inplace_variation[inplace_variation.size()-1];                
        }            

        // New variation for parent
        else if( at_move0 && parent!= &tree )
        {
            VARIATION new_variation;
            MoveTree node;
            if( game_move.flag_ingame )
            {
                game_move.pre_comment =  objs.repository->player.m_white;
                game_move.pre_comment += "-";
                game_move.pre_comment += objs.repository->player.m_black;
            }
            node.game_move = game_move;
            new_variation.push_back(node);
            parent->variations.push_back( new_variation );
            VARIATION &inplace_variation = parent->variations[parent->variations.size()-1];
            move_played = &inplace_variation[inplace_variation.size()-1];                
        }            

        // New variation    
        else if( variation.size() > imove+1 )
        {
            bool last_move_of_main_line = false;
            if( parent==&tree && variation.size()>1 )
            {
                if( imove == variation.size()-2 )
                    last_move_of_main_line = true;  // make a new variation at last move, even if it's the same
                                                    //  move, so you can create a variation indicating rest of game
            }
            if( !last_move_of_main_line && game_move.move==variation[imove+1].game_move.move && allow_overwrite )
                move_played = &variation[imove+1];                
            else
            {
                VARIATION new_variation;
                MoveTree node;
                if( game_move.flag_ingame )
                {
                    game_move.pre_comment =  objs.repository->player.m_white;
                    game_move.pre_comment += "-";
                    game_move.pre_comment += objs.repository->player.m_black;
                }
                node.game_move = game_move;
                new_variation.push_back( node );                
                MoveTree &existing_node = variation[ imove + (at_move0?0:1) ];
                existing_node.variations.push_back( new_variation );
                VARIATION &inplace_variation = existing_node.variations[existing_node.variations.size()-1];
                move_played = &inplace_variation[inplace_variation.size()-1];                
            }
        }            

        // Append
        else if( variation.size() <= imove+1 )
        {
            MoveTree node;
            if( game_move.flag_ingame && variation.size()>0 && !variation[variation.size()-1].game_move.flag_ingame  )
            {
                game_move.pre_comment =  objs.repository->player.m_white;
                game_move.pre_comment += "-";
                game_move.pre_comment += objs.repository->player.m_black;
            }
            node.game_move = game_move;
            variation.push_back( node );
            move_played = &variation[variation.size()-1];                
        }            
        if( empty_with_comment && move_played )
        {
            move_played->game_move.pre_comment = tree.game_move.comment;
            tree.game_move.comment = "";
        }
        Rebuild();
        gl->atom.Undo();
        unsigned long pos = gv.GetMoveOffset( move_played );
        gl->atom.Display( pos );
    }
    return move_played;
}    


// Are we at the end of the main line ?
bool GameDocument::AtEndOfMainLine()
{
    VARIATION &variation = tree.variations[0];
    int nbr_moves = variation.size();
    bool at_end = (nbr_moves==0);
    ChessRules cr;
    std::string move_txt;
    GAME_MOVE *move_ptr = GetSummary( cr, move_txt );
    if( move_ptr && nbr_moves>0 && move_txt.substr(0,15)!="Position before" )
        at_end = (move_ptr == &variation[nbr_moves-1].game_move);
    return at_end;

    #if 0
    bool at_end=false;
    unsigned long pos = GetInsertionPoint();
    ChessRules cr = start_position;
    MoveTree *found = Locate( pos, cr );
    int ivar=0;
    int imove=0;
    MoveTree *parent;
    if( found && found!=&tree )
        parent = tree.Parent( found, cr, ivar, imove );
    else
        parent = &tree;
    if( parent )
    {
        VARIATION &variation = parent->variations[ivar];
        if( parent==&tree && ivar==0 && imove==variation.size() )
            at_end = true;
    }
    return at_end;
    #endif
}    


bool GameDocument::AreWeInMain()
{
    bool is_main=false;
    unsigned long pos = GetInsertionPoint();
    ChessRules cr = start_position;
    MoveTree *found = Locate( pos, cr );
    int ivar=0;
    int imove=0;
    MoveTree *parent;
    if( found && found!=&tree )
        parent = tree.Parent( found, cr, ivar, imove );
    else
        parent = &tree;
    if( parent )
    {
        if( parent==&tree && ivar==0 )
            is_main = true;
    }
    return is_main;
}    

// Where are we in the document
unsigned long GameDocument::GetInsertionPoint()
{
    return gl->atom.GetInsertionPoint();
}

// Where are we in the document
void GameDocument::SetInsertionPoint(unsigned long pos)
{
    gl->atom.SetInsertionPoint(pos);
}

void GameDocument::RedisplayRequest( MoveTree *found )
{
    unsigned long pos = gv.GetMoveOffset( found );
    gl->atom.Redisplay( pos );
}

void GameDocument::Redisplay( unsigned long pos )
{
    std::string title;
    bool at_move0;
    MoveTree *mt = Locate(pos,master_position,title,at_move0);
    if( !mt )
    {
        pos = 0;
        mt = Locate(pos,master_position,title,at_move0);
    }
    if( objs.canvas )
    {
        Display( pos );
        objs.canvas->SetPosition( master_position );
        objs.frame->SetTitle(title.c_str());
    }
}

MoveTree *GameDocument::KibitzCaptureStart( const char *engine_name, const char *txt, std::vector<thc::Move> &var,
        bool &use_repeat_one_move,
        GAME_MOVE &repeat_one_move     // eg variation = e4,c5 new_variation = Nf3,Nc6 etc.
                                       //  must make new_variation = c5,Nf3,Nc6 etc.
    )
{
    use_repeat_one_move = false;
    MoveTree *insertion_point = NULL;
    unsigned long pos = GetInsertionPoint();
    unsigned long pos_restore = pos;
    ChessRules cr = start_position;
    std::string title;
    bool at_move0=true;

    MoveTree *found = Locate( pos, cr, title, at_move0 );
    int ivar=0;
    int imove=0;
    MoveTree *parent;
    if( found && found!=&tree )
        parent = tree.Parent( found, cr, ivar, imove );
    else
    {
        parent = &tree;
        at_move0 = true;
    }
    VARIATION &variation = parent->variations[ivar];
    for( int i=0; i<imove; i++ )
        cr.PlayMove( variation[i].game_move.move );
    if( !at_move0 )
        cr.PlayMove( variation[imove].game_move.move );
    if( cr == master_position )
    {
        VARIATION &variation = parent->variations[ivar];
        if( at_move0 && parent!= &tree )
            ;
        else if( !at_move0 && variation.size()==imove+1 )
        {
            use_repeat_one_move=true;
            repeat_one_move = variation[variation.size()-1].game_move;
        }

        // Create new variation
        VARIATION new_variation;
        for( int i=0; i<var.size(); i++ )
        {
            MoveTree node;
            node.game_move.move = var[i];
            if( i == 0 )
            {
                std::string tmp = txt;
                int idx = tmp.find_first_of(')');
                if( idx != std::string::npos )
                    tmp = tmp.substr(0,idx+1);
                std::string s(engine_name);
                s += " ";            
                s += tmp;            
                node.game_move.pre_comment = s;
                if( use_repeat_one_move )
                {
                    MoveTree mt;
                    mt.game_move = repeat_one_move;
                    new_variation.push_back(mt);
                }
            }
            new_variation.push_back(node);
        }
     
        // New variation for parent
        if( at_move0 ) 
        {
            if( parent == &tree )
            {
                if( parent->variations[0].size() == 0 )
                {
                    parent->variations[0] = new_variation;
                    insertion_point = &parent->variations[0][0];
                }
                else
                {
                    insertion_point = &parent->variations[0][0];
                    insertion_point->variations.push_back( new_variation );
                }
            }
            else
            {
                insertion_point = parent;
                insertion_point->variations.push_back( new_variation );
            }
        }

        // New variation    
        else if( variation.size() > imove+1 )
        {
            MoveTree &existing_node = variation[imove+1];
            insertion_point = &existing_node;
            insertion_point->variations.push_back( new_variation );
        }            

        // Need our repeat move
        else if( use_repeat_one_move )
        {
            MoveTree &existing_node = variation[variation.size()-1];
            insertion_point = &existing_node;
            insertion_point->variations.push_back( new_variation );
        }            

        // Rebuild
        Rebuild();
        gl->atom.Undo();
        pos = pos_restore;
        gl->atom.Redisplay( pos );
    }
    return insertion_point;
}

void GameDocument::KibitzCapture( MoveTree *node, const char *txt, std::vector<thc::Move> &var,
            bool use_repeat_one_move,
            GAME_MOVE &repeat_one_move    // eg variation = e4,c5 new_variation = Nf3,Nc6 etc.
            )                             //  must make new_variation = c5,Nf3,Nc6 etc.
{
/*
    unsigned long pos = GetInsertionPoint();
    unsigned long pos_restore = pos;
    ChessRules cr = start_position;
    std::string title;
    bool at_move0=true;
    MoveTree *found = Locate( pos, cr, title, at_move0 );
    int ivar=0;
    int imove=0;
    MoveTree *parent;
    if( found && found!=&tree )
        parent = tree.Parent( found, cr, ivar, imove );
    else
    {
        parent = &tree;
        at_move0 = true;
    }
    if( parent )
    {
        // New variation for parent
        VARIATION &variation = parent->variations[ivar];
        if( at_move0 && parent!= &tree )
            parent->variations.push_back( new_variation );

        // New variation    
        else if( variation.size() > imove+1 )
        {
            MoveTree &existing_node = variation[imove+1];
            existing_node.variations.push_back( new_variation );
        }            
    }
*/

    if( node )
    {

        VARIATION new_variation;
        if( use_repeat_one_move )
        {
            MoveTree mt;
            mt.game_move =  repeat_one_move;
            new_variation.push_back(mt);
        }
        for( int i=0; i<var.size(); i++ )
        {
            MoveTree node;
            node.game_move.move = var[i];
            if( i == 0 )
            {
                std::string tmp = txt;
                int idx = tmp.find_first_of(')');
                if( idx != std::string::npos )
                    tmp = tmp.substr(0,idx+1);
                node.game_move.pre_comment = tmp;
            }
            new_variation.push_back(node);
        }

        unsigned long pos = GetInsertionPoint();
        node->variations.push_back( new_variation );

        // Rebuild
        Rebuild();
        gl->atom.Undo();
        gl->atom.Redisplay( pos );
    }
}

void GameDocument::Promote()
{
    unsigned long pos = GetInsertionPoint();
    ChessRules cr;
    MoveTree *found = Locate( pos, cr );
    if( found )
    {
        found = tree.Promote( found );
        if( found )
        {
            Rebuild();
            gl->atom.Undo();
            RedisplayRequest( found );
        }
    }
}

void GameDocument::Demote()
{
    unsigned long pos = GetInsertionPoint();
    ChessRules cr;
    MoveTree *found = Locate( pos, cr );
    if( found )
    {
        found = tree.Demote( found );
        if( found )
        {
            Rebuild();
            gl->atom.Undo();
            RedisplayRequest( found );
        }
    }
}

void GameDocument::PromoteRestToVariation()
{
    unsigned long pos = GetInsertionPoint();
    unsigned long offset_within_comment;
    bool in_comment = gv.GetOffsetWithinComment( pos, offset_within_comment );
    if( in_comment )
        PromoteToVariation(offset_within_comment);
}

bool GameDocument::PromotePaste( std::string &str )
{
    unsigned long pos = GetInsertionPoint();
    ChessRules cr;
    std::string title;
    MoveTree save=tree;
    bool changes = false;
    if( pos==0 && !HaveMoves() && tree.game_move.comment.length()==0 )
    {
        MoveTree candidate_a;
        MoveTree candidate_b;
        int nbr_converted_a = 0;
        int nbr_converted_b = 0;

        // Scenario a, use current language
        ChessRules cr = *tree.root;
        VARIATION &variation = tree.variations[0];
        PgnParse( false, nbr_converted_a, str, cr, &variation, true );
        if( nbr_converted_a > 0 )
            candidate_a = tree;

        // Scenario b, use English
        tree = save;
        Rebuild();
        {
            ChessRules cr = *tree.root;
            VARIATION &variation = tree.variations[0];
            Rebuild();
            PgnParse( false, nbr_converted_b, str, cr, &variation, false );
        }
        if( nbr_converted_b > 0 )
            candidate_b = tree;

        // Select one or the scenarios (or none if nothing worked)
        if( nbr_converted_a==0  && nbr_converted_b==0 )
        {
            tree = save;
        }
        else if( nbr_converted_a >= nbr_converted_b &&
                 nbr_converted_a >= 2 )
        {
            tree = candidate_a;
            changes = true;
        }
        else if( nbr_converted_b >= nbr_converted_a &&
                 nbr_converted_b >= 2 )
        {
            tree = candidate_b;
            changes = true;
        }
    }

    // Rebuild
    Rebuild();
    if( changes )
        gl->atom.Undo();
    gl->atom.Redisplay( pos );
    return changes;
}

void GameDocument::PromoteToVariation( unsigned long offset_within_comment )
{
    unsigned long pos = GetInsertionPoint();
    unsigned long pos_restore = pos;
    ChessRules cr;
    std::string title;
    bool at_move0;
    MoveTree save=tree;
    bool no_changes=false;

    // First cope with an empty document with a lone comment
    if( !HaveMoves() && tree.game_move.comment.length()>offset_within_comment )
    {
        MoveTree candidate_a;
        MoveTree candidate_b;
        unsigned long pos_restore_a = pos_restore;
        unsigned long pos_restore_b = pos_restore;
        int nbr_converted_a = 0;
        int nbr_converted_b = 0;

        // Scenario a, use current language
        ChessRules cr = *tree.root;
        std::string str = tree.game_move.comment.substr(offset_within_comment);
        tree.game_move.comment = tree.game_move.comment.substr(0,offset_within_comment);
        VARIATION &variation = tree.variations[0];
        Rebuild();
        PgnParse( false, nbr_converted_a, str, cr, &variation, true );
        if( nbr_converted_a > 0 )
        {
            candidate_a = tree;
            pos_restore_a = gv.GetMoveOffset( gbl_plast_move ); // where to end up pointing
        }

        // Scenario b, use English
        tree = save;
        Rebuild();
        {
            ChessRules cr = *tree.root;
            std::string str = tree.game_move.comment.substr(offset_within_comment);
            tree.game_move.comment = tree.game_move.comment.substr(0,offset_within_comment);
            VARIATION &variation = tree.variations[0];
            Rebuild();
            PgnParse( false, nbr_converted_b, str, cr, &variation, false );
        }
        if( nbr_converted_b > 0 )
        {
            candidate_b = tree;
            pos_restore_b = gv.GetMoveOffset( gbl_plast_move ); // where to end up pointing
        }

        // Select one or the scenarios (or none if nothing worked)
        if( nbr_converted_a==0  && nbr_converted_b==0 )
        {
            tree = save;
            no_changes = true;
        }
        else if( nbr_converted_a >= nbr_converted_b )
        {
            tree = candidate_a;
            pos_restore = pos_restore_a;
        }
        else if( nbr_converted_b >= nbr_converted_a )
        {
            tree = candidate_b;
            pos_restore = pos_restore_b;
        }
    }
    else
    {
        MoveTree candidate_scenario_1a;
        MoveTree candidate_scenario_1b;
        MoveTree candidate_scenario_2a;
        MoveTree candidate_scenario_2b;
        unsigned long pos_restore_scenario1 = pos_restore;
        unsigned long pos_restore_scenario2 = pos_restore;
        int nbr_converted_scenario_1a=0;
        int nbr_converted_scenario_1b=0;
        int nbr_converted_scenario_2a=0;
        int nbr_converted_scenario_2b=0;
        
        // Try scenario 1;
        //   Comment extends from current move, eg 1.e4 e5 2.Nf3 {2...Nc6 3.Bb5}
        //   OR is a well formed variation already, eg 1.e4 e5 2.Nf3 {(2.Nc3 Nf6 3.f4)}
        //   (Scenario 1a, use current language)
        MoveTree *found = Locate( pos, cr, title, at_move0 );
        if( found && found->game_move.comment.length()>offset_within_comment  )
        {
            pos_restore_scenario1 = gv.GetMoveOffset( found ); // where to end up pointing
            ChessRules cr2;
            int ivar;
            int imove;
            MoveTree *parent = tree.Parent( found, cr2, ivar, imove );
            if( parent )
            {
                VARIATION &variation = parent->variations[ivar];
                std::string str = found->game_move.comment.substr(offset_within_comment);
                found->game_move.comment = found->game_move.comment.substr(0,offset_within_comment);
                Rebuild();
                PgnParse( false, nbr_converted_scenario_1a, str, cr, &variation, true, imove );
                if( nbr_converted_scenario_1a > 0 )
                    candidate_scenario_1a = tree;
            }
        }   

        // Scenario 1b, use English
        tree = save;
        Rebuild();
        found = Locate( pos, cr, title, at_move0 );
        if( found && found->game_move.comment.length()>offset_within_comment  )
        {
            ChessRules cr2;
            int ivar;
            int imove;
            MoveTree *parent = tree.Parent( found, cr2, ivar, imove );
            if( parent )
            {
                VARIATION &variation = parent->variations[ivar];
                std::string str = found->game_move.comment.substr(offset_within_comment);
                found->game_move.comment = found->game_move.comment.substr(0,offset_within_comment);
                Rebuild();
                PgnParse( false, nbr_converted_scenario_1b, str, cr, &variation, false, imove );
                if( nbr_converted_scenario_1b > 0 )
                    candidate_scenario_1b = tree;
            }
        }   

        // Try scenario 2;
        //   Comment works as a variation, but is not yet parenthesised,
        //   eg 1.e4 e5 2.Nf3 {2.Nc3 Nf6 3.f4}
        //   (Scenario 2a, use current language)
        tree = save;
        Rebuild();
        found = Locate( pos, cr, title, at_move0 );
        if( found && found->game_move.comment.length()>offset_within_comment && found->game_move.comment[offset_within_comment]!='(' )
        {
            pos_restore_scenario2 = gv.GetMoveOffset( found ); // where to end up pointing
            ChessRules cr2;
            int ivar;
            int imove;
            MoveTree *parent = tree.Parent( found, cr2, ivar, imove );
            if( parent )
            {
                VARIATION &variation = parent->variations[ivar];
                std::string str;
                str = "(";
                str += found->game_move.comment.substr(offset_within_comment);
                str += ")";
                found->game_move.comment = found->game_move.comment.substr(0,offset_within_comment);
                Rebuild();
                PgnParse( false, nbr_converted_scenario_2a, str, cr, &variation, true, imove );
                if( nbr_converted_scenario_2a > 0 )
                    candidate_scenario_2a = tree;
            }
        }

        // Scenario 2b, use English
        tree = save;
        Rebuild();
        found = Locate( pos, cr, title, at_move0 );
        if( found && found->game_move.comment.length()>offset_within_comment && found->game_move.comment[offset_within_comment]!='(' )
        {
            ChessRules cr2;
            int ivar;
            int imove;
            MoveTree *parent = tree.Parent( found, cr2, ivar, imove );
            if( parent )
            {
                VARIATION &variation = parent->variations[ivar];
                std::string str;
                str = "(";
                str += found->game_move.comment.substr(offset_within_comment);
                str += ")";
                found->game_move.comment = found->game_move.comment.substr(0,offset_within_comment);
                Rebuild();
                PgnParse( false, nbr_converted_scenario_2b, str, cr, &variation, false, imove );
                if( nbr_converted_scenario_2b > 0 )
                    candidate_scenario_2b = tree;
            }
        }

        // Select one or the scenarios (or none if nothing worked)
        if( nbr_converted_scenario_1a==0  && nbr_converted_scenario_1b==0 && 
            nbr_converted_scenario_2a==0  && nbr_converted_scenario_2b==0 )
        {
            tree = save;
            no_changes = true;
        }

        // Current language trumps English, less importantly scenario 1 trumps scenario 2
        else if( nbr_converted_scenario_1a>=nbr_converted_scenario_1b &&
                 nbr_converted_scenario_1a>=nbr_converted_scenario_2a &&
                 nbr_converted_scenario_1a>=nbr_converted_scenario_2b
               )
        {
            tree = candidate_scenario_1a;
            pos_restore = pos_restore_scenario1;
        }
        else if( nbr_converted_scenario_2a>=nbr_converted_scenario_2b &&
                 nbr_converted_scenario_2a>=nbr_converted_scenario_1a &&
                 nbr_converted_scenario_2a>=nbr_converted_scenario_1b
               )
        {
            tree = candidate_scenario_2a;
            pos_restore = pos_restore_scenario2;
        }
        else if( nbr_converted_scenario_1b>=nbr_converted_scenario_1a &&
                 nbr_converted_scenario_1b>=nbr_converted_scenario_2a &&
                 nbr_converted_scenario_1b>=nbr_converted_scenario_2b
               )
        {
            tree = candidate_scenario_1b;
            pos_restore = pos_restore_scenario1;
        }
        else if( nbr_converted_scenario_2b>=nbr_converted_scenario_2a &&
                 nbr_converted_scenario_2b>=nbr_converted_scenario_1a &&
                 nbr_converted_scenario_2b>=nbr_converted_scenario_1b
               )
        {
            tree = candidate_scenario_2b;
            pos_restore = pos_restore_scenario2;
        }
    }

    // Rebuild
    Rebuild();
    if( !no_changes )
        gl->atom.Undo();
    pos = pos_restore;
    gl->atom.Redisplay( pos );
}

void GameDocument::DemoteToComment()
{
    unsigned long pos = GetInsertionPoint();
    ChessRules cr;
    std::string title;
    bool at_move0;
    MoveTree *found = Locate( pos, cr, title, at_move0 );
    if( found )
    {
        ChessRules cr;
        int ivar;
        int imove;
        MoveTree *parent = tree.Parent( found, cr, ivar, imove );
        if( parent )
        {
            VARIATION &variation = parent->variations[ivar];
            if( imove+1 < variation.size()+at_move0?1:0 )
            {
                std::string str;
                if( at_move0 )
                {
                    pos = gv.GetMoveOffset(parent);
                    MoveTree *move = &variation[0];
                    int begin = gv.GetInternalOffset(move);
                    int end   = gv.GetInternalOffsetEndOfVariation(begin);
                    gv.ToCommentString(str,begin,end);
                    std::string existing_comment = variation[0].game_move.pre_comment;
                    if( parent == &tree )
                        variation.clear();
                    else
                        tree.DeleteVariation(found);
                    if( existing_comment == "" )
                        parent->game_move.comment = str;
                    else
                    {
                        std::string str2;
                        str2 = "{";
                        str2 += existing_comment;
                        str2 += "} ";
                        str2 += str;
                        parent->game_move.comment = str2;
                    }
                }
                else
                {
                    pos = gv.GetMoveOffset( found );
                    MoveTree *next_move = &variation[imove+1];
                    int begin = gv.GetInternalOffset(next_move);
                    int end   = gv.GetInternalOffsetEndOfVariation(begin);
                    gv.ToCommentString(str,begin,end);
                    tree.DeleteRestOfVariation(found);
                    if( found->game_move.comment == "" )
                        found->game_move.comment = str;
                    else
                    {
                        std::string str2;
                        str2 = "{";
                        str2 += found->game_move.comment;
                        str2 += "} ";
                        str2 += str;
                        found->game_move.comment = str2;
                    }
                }
                Rebuild();
                gl->atom.Undo();
                gl->atom.Redisplay( pos );
            }
        }
    }
}

void GameDocument::DeleteRestOfVariation()
{
    unsigned long pos = GetInsertionPoint();
    ChessRules cr;
    std::string title;
    bool at_move0;
    MoveTree *found = Locate( pos, cr, title, at_move0 );
    if( found )
    {
        ChessRules cr;
        int ivar;
        int imove;
        MoveTree *parent = tree.Parent( found, cr, ivar, imove );
        if( parent )
        {
            VARIATION &variation = parent->variations[ivar];
            if( imove+1 < variation.size()+at_move0?1:0 )
            {
                std::string str;
                if( at_move0 )
                {
                    tree.DeleteVariation(found);
                    pos = gv.GetMoveOffset(parent);
                }
                else
                {
                    tree.DeleteRestOfVariation(found);
                    pos = gv.GetMoveOffset( found );
                }
                if( tree.variations.size() == 0 ) // deleted main variation ?
                {
                    VARIATION empty_variation;
                    tree.variations.push_back( empty_variation );
                }
                Rebuild();
                gl->atom.Undo();
                gl->atom.Redisplay( pos );
            }
        }
    }
}

// A start position, a vector of moves, leading to a final position    
void GameDocument::GetSummary( thc::ChessPosition &start_position, std::vector<GAME_MOVE> &game_moves, thc::ChessPosition &end_pos )
{
    unsigned long pos = GetInsertionPoint();
    start_position = this->start_position;
    end_pos = start_position;
    std::string title;
    bool at_move0=false;
    ChessRules cr;

    // Locate the node in the tree corresponding to this position, also get the position
    //  on the board, a text title, and the at_move0 flag (true if pointing before the node)
    MoveTree *found = Locate( pos, cr, title, at_move0 );
    int ivar=0;
    int imove=0;
    vector<GAME_MOVE> temp;
    if( found )
    {
        bool leaf = true;   // start at the leaf and iterate back
        MoveTree *parent = tree.Parent( found, cr, ivar, imove );
        while( parent )
        {
            VARIATION &variation = parent->variations[ivar];
            if( leaf )
            {
                for( int i=0; i<imove; i++ )
                    cr.PlayMove( variation[i].game_move.move );
                if( !at_move0 )
                    cr.PlayMove( variation[imove].game_move.move );
                end_pos = cr;
            }

            // Add moves in reverse order
            if( !at_move0 )
            {
                for( int i=(leaf?imove:imove-1); i>=0; i-- )
                {
                    GAME_MOVE game_move;
                    game_move = variation[i].game_move; 
                    temp.push_back( game_move );
                }
            }
            leaf = false;
            at_move0 = false;
            parent = tree.Parent( parent, cr, ivar, imove );
        }
    }
    game_moves.clear();
    int nbr = temp.size();
    for( int i=nbr-1; i>=0; i-- )
    {
        GAME_MOVE game_move = temp[i];
        game_moves.push_back( game_move );
    }
}

// The current position, title text for the last move played eg "Position after 23...Nxd5"
//  Return ptr to the last move played,  NULL if no last move OR if nbr_half_moves_lag
GAME_MOVE *GameDocument::GetSummary( thc::ChessRules &cr, std::string &title_txt, int nbr_half_moves_lag )
{
    MoveTree *found = NULL; 
    if( nbr_half_moves_lag )
    {
        ChessPosition end;
        std::vector<GAME_MOVE> game_moves;
        GetSummary( cr, game_moves, end );
        int nbr = game_moves.size();
        if( nbr == 0 )
            title_txt = "Initial position";
        else
        {
            if( nbr > nbr_half_moves_lag )
                nbr -= nbr_half_moves_lag;
            else
                nbr = 0;
            char buf[80];
            if( nbr == 0 )
            {
                std::string s = game_moves[0].move.NaturalOut(&cr);
                LangOut(s);
                sprintf( buf, "Position before %d%s%s",
                    cr.full_move_count,
                    cr.white?".":"...",
                    s.c_str() );
            }
            else
            {
                for( int i=0; i<nbr-1; i++ )
                    cr.PlayMove( game_moves[i].move );
                std::string s = game_moves[nbr==0?0:nbr-1].move.NaturalOut(&cr);
                LangOut(s);
                sprintf( buf, "Position after %d%s%s",
                        cr.full_move_count,
                        cr.white?".":"...",
                        s.c_str() );
                cr.PlayMove( game_moves[nbr-1].move );  //play the move
            }
            title_txt = buf;
        }
    }
    else
    {
        unsigned long pos = GetInsertionPoint();
        cr = this->start_position;
        bool at_move0=false;
        found = Locate( pos, cr, title_txt, at_move0 );
    }
    return( found ? &found->game_move : NULL );
}

//  We should define and use some simple recipes like this
MoveTree *GameDocument::GetSummary()
{
    MoveTree *found = NULL; 
    unsigned long pos = GetInsertionPoint();
    ChessRules cr;
    found = Locate( pos, cr );
    return( found );
}

// The current position, move text for the last move played eg "23...Nxd5"
//  Return ptr to the last move played,  NULL if no last move OR if nbr_half_moves_lag
GAME_MOVE *GameDocument::GetSummaryMove( thc::ChessRules &cr, std::string &move_txt )
{
    MoveTree *found = NULL; 
    unsigned long pos = GetInsertionPoint();
    cr = this->start_position;
    bool at_move0=false;
    move_txt = "";
    std::string title_txt;
    found = Locate( pos, cr, title_txt, at_move0 );
    if( title_txt.substr(0,15) == "Position after " ) 
        move_txt = title_txt.substr(15);
    return( found && !found->root ? &found->game_move : NULL );
}


bool GameDocument::HaveMoves()
{
    return( tree.variations.size()>0 && tree.variations[0].size()>0 );
}

bool GameDocument::IsAtEnd()
{
    unsigned long pos = GetInsertionPoint();
    return( gv.IsAtEnd(pos) );
}

void GameDocument::ToFileTxtGameDetails( std::string &str )
{
    #ifdef _WINDOWS
    #define EOL "\r\n"
    #else
    #define EOL "\n"
    #endif
    string str1;
    str1 += "[Event \"";
    str1 += (event=="" ? "?" : event);
    str1 += "\"]" EOL;
    str1 += "[Site \"";
    str1 += (site=="" ? "?" : site);
    str1 += "\"]" EOL;
    str1 += "[Date \"";
    str1 += (date=="" ? "????.??.??" : date);
    str1 += "\"]" EOL;
    str1 += "[Round \"";
    str1 += (round=="" ? "?": round);
    str1 += "\"]" EOL;
    str1 += "[White \"";
    str1 += (white=="" ? "?": white);
    str1 += "\"]" EOL;
    str1 += "[Black \"";
    str1 += (black=="" ? "?": black);
    str1 += "\"]" EOL;
    str1 += "[Result \"";
    str1 += (result=="" ? "*" : result);
    str1 += "\"]" EOL;
    if( eco != "" )
    {
        str1 += "[ECO \"";
        str1 += eco;
        str1 += "\"]" EOL;
    }
    if( white_elo != "" )
    {
        str1 += "[WhiteElo \"";
        str1 += white_elo;
        str1 += "\"]" EOL;
    }
    if( black_elo != "" )
    {
        str1 += "[BlackElo \"";
        str1 += black_elo;
        str1 += "\"]" EOL;
    }
    ChessPosition tmp;
    bool needs_fen = (tmp!=start_position);
    if( needs_fen )
    {
        str1 += "[FEN \"";
        str1 += start_position.ForsythPublish();
        str1 += "\"]" EOL;
    }
    str1 += EOL;
    str = str1;
}

void GameDocument::ToFileTxtGameBody( std::string &str )
{
    string str1;
    gv.ToString( str1 );
    str1 += "\n";
    str1 += "\n";
    #ifndef _WINDOWS
    str = str1;
    #else
    string str2;
    int len = str1.length();
    for( int i=0; i<len; i++ )
    {
        if( str1[i] == '\n' )
            str2 += "\r\n";  // Windows filesystem in binary mode, so '\n' -> '\r','\n'
        else
            str2 += str1[i];
    }
    str = str2;
    #endif
}

// Is other GameDocument different to this one ?
bool GameDocument::IsDiff( GameDocument &other )
{
    std::string s1;
    std::string s2;
    gv.ToString( s1 );
    other.gv.ToString( s2 );
    bool diff = (s1!=s2);
    if( !diff )   // if main part not different ...
    {
        ToFileTxtGameDetails( s1 ); // ... test header
        other.ToFileTxtGameDetails( s2 );
        diff = (s1!=s2);
    }
    return diff;
}

/*
void GameDocument::Temp()
{
    // Allow stacking of the key state variables    
    const int MAX_DEPTH=20;
    struct STACK_ELEMENT
    {
        VARIATION  *pvar;
        ChessRules cr;
        vector<VARIATION>::iterator v;
        vector<VARIATION>::iterator vend;
        vector<MoveTree>::iterator m;
        vector<MoveTree>::iterator mend;
    };
    STACK_ELEMENT stk_array[MAX_DEPTH+1];
    int stk_idx = 0;
    STACK_ELEMENT *stk = &stk_array[stk_idx];


    stk->v      = tree.variations.begin();
    stk->vend   = tree.variations.end();
    stk->m      = stk->v->begin();
    stk->mend   = stk->v->end();
    stk->cr     = *tree.root;
    bool done=false;
    bool error=false;
    while( !done && !error )
    {
        for( ; stk->v != stk->vend; stk->v++ )
        {
            while( stk->m != stk->mend )
            {
                stk->cr.PushMove( stk->m->game_move.move );
                if( stk->m->variations.size() == 0 )
                    stk->m++;
                else if( stk_idx+1 >= MAX_DEPTH )
                {
                    done = true;
                    error = true;
                }
                else
                {
                    vector<MoveTree>::iterator m = stk->m;
                    stk = &stk_array[++stk_idx];
                    stk->v      = m->variations.begin();
                    stk->vend   = m->variations.end();
                    stk->m      = stk->v->begin();
                    stk->mend   = stk->v->end();
                    stk->cr     = stk_array[stk_idx-1].cr;
                    stk->cr.PopMove( m->game_move.move );
                }
            }
        }
        if( done || stk_idx==0 )
            break;
        else
            stk = &stk_array[--stk_idx];
    }
}
  */