File: makebearoff.c

package info (click to toggle)
gnubg 0.90-3
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 30,800 kB
  • ctags: 8,224
  • sloc: ansic: 92,884; xml: 13,338; sh: 9,675; makefile: 425; python: 392; yacc: 295; sql: 237; lex: 220; php: 102; cs: 81; awk: 25; sed: 16
file content (1826 lines) | stat: -rw-r--r-- 43,681 bytes parent folder | download
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
/*
 * makebearoff.c
 *
 * by Gary Wong <gary@cs.arizona.edu>, 1997-1999.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 3 or later of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: makebearoff.c,v 1.66 2008/03/18 22:51:34 c_anthon Exp $
 */

#include "config.h"

#include <glib.h>
#include <glib/gstdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <math.h>
#include <errno.h>
#include "eval.h"
#include "positionid.h"
#include "bearoff.h"
#include "util.h"
#include "backgammon.h"
#include "multithread.h"
#include <glib/gi18n.h>

#if WIN32
#include <windows.h>
#include <commctrl.h>
#define DLG_MAKEBEAROFF 100
BOOL CALLBACK
DlgProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam);

HWND hdlg;
int CancelPressed = FALSE;
#endif

#if USE_MULTITHREAD
extern int MT_GetThreadID(void)
{
  return (0);
}
extern void MT_Release(void)
{
  return;
}
extern void MT_Exclusive(void)
{
  return;
}
#else
extern void CallbackProgress(void)
{
}
#endif

typedef struct _xhashent {
  void *p;
  unsigned int iKey;
} xhashent;

typedef struct _xhash {
  unsigned long int nQueries, nHits, nEntries, nOverwrites;
  int nHashSize;
  xhashent *phe;
} xhash;


#if WIN32
static void
dlgprintf(int id, const char *fmt, ... ){

    va_list val;
    char buf[256]; /* FIXME allocate with malloc */
    
    va_start( val, fmt );
    vsprintf(buf, fmt, val);
    SendDlgItemMessage(hdlg, id, WM_SETTEXT, 0, (LPARAM) buf);
    
    va_end( val );
}
#endif

static void dsplerr ( const char *fmt, ... ){

    va_list val;

    char buf[256]; /* FIXME allocate with malloc */
    va_start( val, fmt );
    vsprintf(buf, fmt, val);
#if WIN32
    MessageBox (NULL, buf, "Makebearoff", MB_ICONERROR | MB_OK);
#else
    fprintf( stderr, "%s", buf);
#endif
    va_end( val );
}

static long cLookup;

static long int
XhashPosition ( xhash *ph, const int iKey ) {

  return iKey % ph->nHashSize;

}


static void
XhashStatus ( xhash *ph ) {

#if !WIN32
  fprintf ( stderr, "Xhash status:\n" );
  fprintf ( stderr, "Size:    %d elements\n", ph->nHashSize );
  fprintf ( stderr, "Queries: %lu (hits: %ld)\n", ph->nQueries, ph->nHits );
  fprintf ( stderr, "Entries: %lu (overwrites: %lu)\n",
            ph->nEntries, ph->nOverwrites );
#endif

}


static int
XhashCreate ( xhash *ph, const int nHashSize ) {

  int i;

  if ( ! ( ph->phe =
           (xhashent *) malloc ( nHashSize * sizeof ( xhashent ) ) ) ) {
    perror ( "xhashtable" );
    return -1;
  }

  ph->nQueries = 0;
  ph->nHits = 0;
  ph->nEntries = 0;
  ph->nOverwrites = 0;
  ph->nHashSize = nHashSize;

  for ( i = 0; i < nHashSize; ++i )
    ph->phe[ i ].p = NULL;

  return 0;

}


static void
XhashDestroy ( xhash *ph ) {

  int i;

  for ( i = 0; i < ph->nHashSize; ++i )
    if ( ph->phe[ i ].p )
      free ( ph->phe[ i ].p );

}


static void
XhashAdd ( xhash *ph, const unsigned int iKey,
          const void *data, const int size ) {

  int l = XhashPosition ( ph, iKey );

  if ( ph->phe[ l ].p ) {
    /* occupied */
    free ( ph->phe[ l ].p );
    ph->nOverwrites++;
  }
  else {

    /* free */
    ph->nEntries++;

  }

  ph->phe[ l ].iKey = iKey;
  ph->phe[ l ].p = malloc ( size );
  memcpy ( ph->phe[ l ].p, data, size );

}


static void *
XhashLookup ( xhash *ph, const unsigned int iKey ) {


  int l = XhashPosition ( ph, iKey );

  ++ph->nQueries;

  if ( ph->phe[ l ].p && ph->phe[ l ].iKey == iKey ) {
    /* hit */
    ++ph->nHits;
    return (ph->phe[ l].p);
  }
  else
    /* miss */
    return NULL;

}


static int
OSLookup ( const unsigned int iPos,
           const int nPoints,
           unsigned short int aProb[ 64 ],
           const int fGammon, const int fCompress,
           FILE *pfOutput, FILE *pfTmp ) {

  int i, j;
  unsigned char ac[ 128 ];

  g_assert ( pfOutput != stdin );

  if ( fCompress ) {

    unsigned char ac[ 128 ];
    unsigned int i, j;
    long iOffset;
    size_t nBytes;
    unsigned int ioff, nz, ioffg, nzg;
    unsigned short int us;

    /* find offsets and no. of non-zero elements */

    if ( fseek ( pfOutput, 40 + iPos * 8, SEEK_SET ) < 0 ) {
      perror ( "output file" );
      exit(-1);
    }

    if ( fread ( ac, 1, 8, pfOutput ) < 8 ) {
      if ( errno )
        perror ( "output file" );
      else
        dsplerr (  "error reading output file\n" );
      exit(-1);
    }

    iOffset = 
      ac[ 0 ] | 
      ac[ 1 ] << 8 |
      ac[ 2 ] << 16 |
      ac[ 3 ] << 24;
    
    nz = ac[ 4 ];
    ioff = ac[ 5 ];
    nzg = ac[ 6 ];
    ioffg = ac[ 7 ];

    /* re-position at EOF */

    if ( fseek ( pfOutput, 0L, SEEK_END ) < 0 ) {
      perror ( "output file" );
      exit(-1);
    }
      
    /* read distributions */

    iOffset = 2 * iOffset;

    nBytes = 2 * ( nz + nzg );

    if ( fseek ( pfTmp, iOffset, SEEK_SET ) < 0 ) {
      perror ( "fseek'ing temp file" );
      exit(-1);
    }

    /* read data */

    if ( fread ( ac, 1, nBytes, pfTmp ) < nBytes ) {
      if ( errno )
        perror ( "reading temp file" );
      else
        dsplerr ( "error reading temp file" );
      exit(-1);
    }
    
    memset ( aProb, 0, 128 );

    i = 0;
    for ( j = 0; j < nz; ++j, i += 2 ) {
      us = ac[ i ] | ac[ i + 1 ] << 8;
      aProb[ ioff + j ] = us;
    }

    if ( fGammon ) 
      for ( j = 0; j < nzg; ++j, i += 2 ) {
        us = ac[ i ] | ac[ i+1 ] << 8;
        aProb[ 32 + ioffg + j ] = us;
      }

    /* re-position at EOF */

    if ( fseek ( pfTmp, 0L, SEEK_END ) < 0 ) {
      perror ( "fseek'ing to EOF on temp file" );
      exit(-1);
    }

  }
  else {

    /* look up position by seeking */

    if ( fseek ( pfOutput, 
                 40 + iPos * ( fGammon ? 128 : 64 ), SEEK_SET ) < 0 ) {
      dsplerr (  "error seeking in pfOutput\n" );
      exit(-1);
    }

    /* read distribution */

    if ( fread ( ac, 1, fGammon ? 128 : 64, pfOutput ) < 
         ( fGammon ? 128 : 64 ) ) {
      dsplerr (  "error readung from pfOutput\n" );
      exit(-1);
    }

    /* save distribution */

    i = 0;
    for ( j = 0; j < 32; ++j, i+=2 )
      aProb[ j ] = ac[ i ] | ac[ i + 1 ] << 8;

    if ( fGammon )
      for ( j = 0; j < 32; ++j, i+=2 )
        aProb[ j + 32 ] = ac[ i ] | ac[ i + 1 ] << 8;

    /* position cursor at end of file */

    if ( fseek ( pfOutput, 0L, SEEK_END ) < 0 ) {
      dsplerr (  "error seeking to end!\n" );
      exit(-1);
    }

  }

  ++cLookup;

  return 0;

}


static void
CalcIndex ( const unsigned short int aProb[ 32 ],
            unsigned int *piIdx, unsigned int *pnNonZero ) {

  int i;
  int j = 32;


  /* find max non-zero element */

  for ( i = 31; i >= 0; --i )
    if ( aProb[ i ] ) {
      j = i;
      break;
    }

  /* find min non-zero element */

  *piIdx = 0;
  for ( i = 0; i <= j; ++i ) 
    if ( aProb[ i ] ) {
      *piIdx = i;
      break;
    }


  *pnNonZero = j - *piIdx + 1;

}


static unsigned int
RollsOS ( const unsigned short int aus[ 32 ] ) {

  int i;
  unsigned int j;

  for( j = 0, i = 1; i < 32; i++ )
    j += i * aus[ i ];

  return j;

}

static void BearOff( int nId, unsigned int nPoints, 
                     unsigned short int aOutProb[ 64 ],
                     const int fGammon,
                     xhash *ph, bearoffcontext *pbc,
                     const int fCompress, 
                     FILE *pfOutput, FILE *pfTmp ) {

    int iBest, iMode, j, anRoll[ 2 ], aProb[ 64 ];
    unsigned int i;
	TanBoard anBoard, anBoardTemp;
    movelist ml;
    int k;
    unsigned int us;
    unsigned int usBest;
    unsigned short int *pusj;
    unsigned short int ausj[ 64 ];
    unsigned short int ausBest[ 32 ];

    unsigned int usGammonBest;
    unsigned short int ausGammonBest[ 32 ];
    int iGammonBest;
    unsigned int nBack;

    /* get board for given position */

    PositionFromBearoff( anBoard[ 1 ], nId, nPoints, 15 );

    /* initialise probabilities */

    for( i = 0; i < 64; i++ )
        aProb[ i ] = aOutProb[ i ] = 0;

    /* all chequers off is easy :-) */

    if ( ! nId ) {
      aOutProb[  0 ] = 0xFFFF;
      aOutProb[ 32 ] = 0xFFFF;
      return;
    }

    /* initialise the remainder of the board */
    
    for( i = nPoints; i < 25; i++ )
	anBoard[ 1 ][ i ] = 0;
    
    for( i = 0; i < 25; i++ )
	anBoard[ 0 ][ i ] = 0;

    nBack = 0;
    for ( i = 0, k = 0; i < nPoints; ++i ) {
      if ( anBoard[ 1 ][ i ] )
         nBack = i;
      k += anBoard[ 1 ][ i ];
    }

    /* look for position in existing bearoff file */
    
    if ( pbc && nBack < pbc->nPoints ) {
      unsigned int nPosID = PositionBearoff ( anBoard[ 1 ], 
                                              pbc->nPoints, pbc->nChequers );
      BearoffDist ( pbc, nPosID, NULL, NULL, NULL, aOutProb, aOutProb + 32 );
      return;
    }
    
    if ( k < 15 )
      aProb[ 32 ] = 0xFFFF * 36;
	    
    for( anRoll[ 0 ] = 1; anRoll[ 0 ] <= 6; anRoll[ 0 ]++ )
	for( anRoll[ 1 ] = 1; anRoll[ 1 ] <= anRoll[ 0 ]; anRoll[ 1 ]++ ) {
	    GenerateMoves( &ml, (ConstTanBoard)anBoard, anRoll[ 0 ], anRoll[ 1 ], FALSE );

	    usBest = 0xFFFFFFFF; iBest = -1;
            usGammonBest = 0xFFFFFFFF; iGammonBest = -1;
	    
	    for( i = 0; i < ml.cMoves; i++ ) {
		PositionFromKey( anBoardTemp, ml.amMoves[ i ].auch );

		j = PositionBearoff( anBoardTemp[ 1 ], nPoints, 15 );

		g_assert( j >= 0 );
		g_assert( j < nId );


                if ( ! j ) {

                  memset ( pusj = ausj, 0, fGammon ? 128 : 64 );
                  pusj[  0 ] = 0xFFFF;
                  pusj[ 32 ] = 0xFFFF;

                }
                else if ( ! (pusj = XhashLookup ( ph, j))) {
                  /* look up in file generated so far */
		  pusj = ausj;
                  OSLookup ( j, nPoints, pusj, fGammon, fCompress,
                             pfOutput, pfTmp );

                  XhashAdd ( ph, j, pusj, fGammon ? 128 : 64 );
                }

                /* find best move to win */

                if ( ( us = RollsOS ( pusj ) ) < usBest ) {
                  iBest = j;
                  usBest = us;
                  memcpy ( ausBest, pusj, 64 );
                }

                /* find best move to save gammon */
                  
                if ( fGammon && 
                     ( ( us = RollsOS ( pusj + 32 ) ) < usGammonBest ) ) {
                  iGammonBest = j;
                  usGammonBest = us;
                  memcpy ( ausGammonBest, pusj + 32, 64 );
                }

	    }

	    g_assert( iBest >= 0 );
            g_assert( iGammonBest >= 0 );

	    if( anRoll[ 0 ] == anRoll[ 1 ] ) {
              for( i = 0; i < 31; i++ ) {
                aProb[ i + 1 ] += ausBest[ i ];
                if ( k == 15 && fGammon )
                  aProb[ 32 + i + 1 ] += ausGammonBest[ i ];
              }
            }
	    else {
              for( i = 0; i < 31; i++ ) {
                aProb[ i + 1 ] += 2 * ausBest[ i ];
                if ( k == 15 && fGammon )
                  aProb[ 32 + i + 1 ] += 2 * ausGammonBest[ i ];
              }
            }
	}
    
    for( i = 0, j = 0, iMode = 0; i < 32; i++ ) {
	j += ( aOutProb[ i ] = ( aProb[ i ] + 18 ) / 36 );
	if( aOutProb[ i ] > aOutProb[ iMode ] )
	    iMode = i;
    }

    aOutProb[ iMode ] -= ( j - 0xFFFF );
    
    /* gammon probs */

    if ( fGammon ) {
      for( i = 0, j = 0, iMode = 0; i < 32; i++ ) {
	j += ( aOutProb[ 32 + i ] = ( aProb[ 32 + i ] + 18 ) / 36 );
	if( aOutProb[ 32 + i ] > aOutProb[ 32 + iMode ] )
          iMode = i;
      }
      
      aOutProb[ 32 + iMode ] -= ( j - 0xFFFF );
    }

}


static void
WriteOS ( const unsigned short int aus[ 32 ], 
          const int fCompress, FILE *output ) {

  unsigned int iIdx, nNonZero;
  unsigned int j;

  if ( fCompress )
    CalcIndex ( aus, &iIdx, &nNonZero );
  else {
    iIdx = 0;
    nNonZero = 32;
  }

  for( j = iIdx; j < iIdx + nNonZero; j++ ) {
    putc ( aus[ j ] & 0xFF, output );
    putc ( aus[ j ] >> 8, output );
  }

}

static void
WriteIndex ( unsigned int *pnpos,
             const unsigned short int aus[ 64 ],
             const int fGammon, FILE *output ) {

  unsigned int iIdx, nNonZero;

  /* write offset */

  putc ( *pnpos & 0xFF, output );
  putc ( ( *pnpos >> 8 ) & 0xFF, output );
  putc ( ( *pnpos >> 16 ) & 0xFF, output );
  putc ( ( *pnpos >> 24 ) & 0xFF, output );
  
  /* write index and number of non-zero elements */
        
  CalcIndex ( aus, &iIdx, &nNonZero );

  putc ( nNonZero & 0xFF, output );
  putc ( iIdx & 0xFF, output );

  *pnpos += nNonZero;

  /* gammon probs: write index and number of non-zero elements */

  if ( fGammon ) 
    CalcIndex ( aus + 32, &iIdx, &nNonZero );
  else {
    nNonZero = 0;
    iIdx = 0;
  }

  putc ( nNonZero & 0xFF, output );
  putc ( iIdx & 0xFF, output );

  *pnpos += nNonZero;

}

static void
WriteFloat ( const float r, FILE *output ) {

  int j;
  unsigned char *pc;

  pc = (unsigned char *) &r;

  for ( j = 0; j < 4; ++j )
    putc ( *(pc++), output );

}



/*
 * Generate one sided bearoff database
 *
 * ! fCompress:
 *   write database directly to stdout
 *
 * fCompress:
 *   write index directly to stdout
 *   and write actual db to tmp file
 *   the tmp file is concatenated to the index when
 *   the generation is done.
 *
 */


static int
generate_os ( const int nOS, const int fHeader,
              const int fCompress, const int fGammon,
              const int nHashSize, bearoffcontext *pbc,
			  FILE *output) {

  int i;
  int n;
  unsigned short int aus[ 64 ];
  xhash h;
  FILE *pfTmp = NULL;
  unsigned int npos;
  char *tmpfile;
#ifndef WIN32
  int fTTY = isatty(STDERR_FILENO);
#endif

#if WIN32
  HINSTANCE hInstance = (HINSTANCE) GetModuleHandle(NULL);
  HWND hwndPB;
  INITCOMMONCONTROLSEX InitCtrlEx;
  if( hdlg != NULL)
    ShowWindow(hdlg, SW_SHOW);

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_PROGRESS_CLASS;
  InitCommonControlsEx(&InitCtrlEx);

  hwndPB = CreateWindowEx(0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE,
		  12, 300, 470, 20, hdlg, NULL, hInstance, NULL);
#endif

  /* initialise xhash */

#if WIN32
  dlgprintf(127, "Creating cache memory." );
#endif
  if ( XhashCreate ( &h, nHashSize /  ( fGammon ? 128 : 64 ) ) ) {
    dsplerr (  _("Error creating xhash with %d elements\n"),
              nHashSize /  fGammon ? 128 : 64 );
    exit(2);
  }

  XhashStatus ( &h );

  /* write header */

  if ( fHeader ) {
    char sz[ 41 ];
#if WIN32
    dlgprintf(127, "Writing header information." );
#endif
    sprintf ( sz, "gnubg-OS-%02d-15-%1d-%1d-0xxxxxxxxxxxxxxxxxxx\n", 
              nOS, fGammon, fCompress );
    fputs ( sz, output );
  }

  if ( fCompress ) {
#if WIN32
    dlgprintf(127, "Opening temporary file." );
#endif
	pfTmp = GetTemporaryFile(NULL, &tmpfile);
	if (pfTmp == NULL)
      exit(2);
  }
    

  /* loop trough bearoff positions */

  n = Combination ( nOS + 15, nOS );
  npos = 0;
  
#if WIN32
  SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, n / 100));
  SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);
  dlgprintf(127, "Calculating bearoff data." );
#endif

  for ( i = 0; i < n; ++i ) {
    
    if ( i )
      BearOff ( i, nOS, aus, fGammon, &h, pbc, fCompress, output, pfTmp );
    else {
      memset ( aus, 0, 128 );
      aus[  0 ] = 0xFFFF;
      aus[ 32 ] = 0xFFFF;
    }
#if WIN32
    if (!((i+1) % 100))
      SendMessage(hwndPB, PBM_STEPIT, 0, 0);
    if (CancelPressed)
      break;
#else
    if (!(i % 100) && fTTY)
      fprintf (stderr, "1:%d/%d        \r", i, n);
#endif

    WriteOS ( aus, fCompress, fCompress ? pfTmp : output );
    if ( fGammon )
      WriteOS ( aus + 32, fCompress, fCompress ? pfTmp : output );

    XhashAdd ( &h, i, aus, fGammon ? 128 : 64 );

    if ( fCompress ) 
      WriteIndex ( &npos, aus, fGammon, output );

  }

  if ( fCompress ) {

    char ac[ 256 ];
    int n;
#if WIN32
    dlgprintf(127, "Rewriting to compressed database." );
#endif

    /* write contents of pfTmp to output */

    rewind ( pfTmp );

    while ( ! feof ( pfTmp ) && ( n = fread ( ac, 1, sizeof ( ac ), pfTmp ) ) )
      fwrite ( ac, 1, n, output );

    fclose ( pfTmp );

    g_unlink ( tmpfile );

  }
#if !WIN32
  putc ( '\n', stderr );
#else
  dlgprintf(127, "Clearing cache memory." );
#endif

  XhashStatus ( &h );

  XhashDestroy ( &h );

  return 0;

}


static void
NDBearoff ( const int iPos, const unsigned int nPoints, float ar[ 4 ], xhash *ph,
            bearoffcontext *pbc) {

  int d0, d1;
  movelist ml;
  TanBoard anBoard, anBoardTemp;
  int ii, j, k;
  unsigned int i;
  int iBest;
  float rBest;
  float rMean;
  float rVarSum, rGammonVarSum;
  float *prj;
  float arj[ 4 ];
  float arBest[ 4 ];

  int iGammonBest;
  float arGammonBest[ 4 ];
  float rGammonBest;

  for ( i = 0; i < 4; ++i )
    ar[ i ] = 0.0f;

  if ( ! iPos ) 
    return;

  PositionFromBearoff( anBoard[ 1 ], iPos, nPoints, 15 );

  for( i = nPoints; i < 25; i++ )
    anBoard[ 1 ][ i ] = 0;

  /* 
   * look for position in existing bearoff file 
   */

  if ( pbc ) {
    for ( ii = 24; ii >= 0 && ! anBoard[ 1 ][ ii ]; --ii )
      ;

    if ( ii < (int)pbc->nPoints ) {
      unsigned int nPosID = PositionBearoff ( anBoard[ 1 ], 
                                              pbc->nPoints, pbc->nChequers );
      BearoffDist ( pbc, nPosID, NULL, NULL, ar, NULL, NULL );
      return;
    }

  }

  memset ( anBoard[ 0 ], 0, 25 * sizeof ( int ) );

  for ( i = 0, k = 0; i < nPoints; ++i )
    k += anBoard[ 1 ][ i ];

  /* loop over rolls */

  rVarSum = rGammonVarSum = 0.0f;

  for ( d0 = 1; d0 <= 6; ++d0 ) 
    for ( d1 = 1; d1 <= d0; ++d1 ) {

      GenerateMoves ( &ml, (ConstTanBoard)anBoard, d0, d1, FALSE );

      rBest = 1e10;
      rGammonBest = 1e10;
      iBest = -1;
      iGammonBest = -1;

      for ( i = 0; i < ml.cMoves; ++i ) {

        PositionFromKey ( anBoardTemp, ml.amMoves[ i ].auch );

        j = PositionBearoff ( anBoardTemp[ 1 ], nPoints, 15 );

        if ( ! (prj = XhashLookup ( ph, j ))) {
	  prj = arj;
          NDBearoff ( j, nPoints, prj, ph, pbc );
          XhashAdd ( ph, j, prj, 16 );
        }

        /* find best move to win */

        if ( prj[ 0 ] < rBest ) {
          iBest = j;
          rBest = prj[ 0 ];
          memcpy ( arBest, prj, 4 * sizeof ( float ) );
        }

        /* find best move to save gammon */

        if ( prj[ 2 ] < rGammonBest ) {
          iGammonBest = j;
          rGammonBest = prj[ 2 ];
          memcpy ( arGammonBest, prj, 4 * sizeof ( float ) );
        }

      }

      g_assert ( iBest >= 0 );
      g_assert ( iGammonBest >= 0 );
      
      rMean = 1.0f + arBest[ 0 ];

      ar[ 0 ] += ( d0 == d1 ) ? rMean : 2.0f * rMean;

      rMean = arBest[ 1 ] * arBest[ 1 ] + rMean * rMean;

      rVarSum += ( d0 == d1 ) ? rMean : 2.0f * rMean;
      
      if ( k == 15 ) {

        rMean = 1.0f + arGammonBest[ 2 ];

        ar[ 2 ] += ( d0 == d1 ) ? rMean : 2.0f * rMean;

        rMean = 
          arGammonBest[ 3 ] * arGammonBest[ 3 ] + rMean * rMean;

        rGammonVarSum += ( d0 == d1 ) ? rMean : 2.0f * rMean;

      }

    }

  
  ar[ 0 ] /= 36.0f;
  ar[ 1 ]  = sqrt ( rVarSum / 36.0f - ar[ 0 ] * ar[ 0 ] );

  ar[ 2 ] /= 36.0f;
  ar[ 3 ]  = 
    sqrt ( rGammonVarSum / 36.0f - ar[ 2 ] * ar[ 2 ] );

}



static void
generate_nd ( const int nPoints,const int nHashSize, const int fHeader,
              bearoffcontext *pbc, FILE *output ) {

  int n = Combination ( nPoints + 15, nPoints );

  int i, j;
  char sz[ 41 ];
  float ar[ 4 ];
#ifndef WIN32
  int fTTY = isatty(STDERR_FILENO);
#endif

  xhash h;
#if WIN32
  HINSTANCE hInstance = (HINSTANCE) GetModuleHandle(NULL);
  HWND hwndPB;
  INITCOMMONCONTROLSEX InitCtrlEx;
  if( hdlg != NULL)
    ShowWindow(hdlg, SW_SHOW);

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_PROGRESS_CLASS;
  InitCommonControlsEx(&InitCtrlEx);

  hwndPB = CreateWindowEx(0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE,
		  12, 300, 470, 20, hdlg, NULL, hInstance, NULL);
#endif

  /* initialise xhash */
  
#if WIN32
    dlgprintf(127, "Creating cache memory." );
#endif
 
  if ( XhashCreate ( &h, nHashSize / ( 4 * sizeof ( float ) ) ) ) {
    dsplerr (  "Error creating cache\n" );
    return;
  }

  XhashStatus ( &h );

  if ( fHeader ) {
#if WIN32
    dlgprintf(127, "Writing header information." );
#endif
    sprintf ( sz, "gnubg-OS-%02d-15-1-0-1xxxxxxxxxxxxxxxxxxx\n", nPoints );
    fputs ( sz, output );
  }

#if WIN32
  SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, n / 100));
  SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);
  dlgprintf(127, "Calculating bearoff data." );
#endif

  for ( i = 0; i < n; ++i ) {

    if ( i )
      NDBearoff ( i, nPoints, ar, &h, pbc );
    else
      ar[ 0 ] = ar[ 1 ] = ar[ 2 ] = ar[ 3 ] = 0.0f;

    for ( j = 0; j < 4; ++j )
      WriteFloat ( ar[ j ], output );

    XhashAdd ( &h, i, ar, 16 );
#if WIN32
    if (!((i+1) % 100))
      SendMessage(hwndPB, PBM_STEPIT, 0, 0);
#else
    if (!(i % 100) && fTTY)
      fprintf (stderr, "1:%d/%d        \r", i, n);
#endif

  }
#if !WIN32
  putc ( '\n', stderr );
#else
  dlgprintf(127, "Clearing cache memory." );
#endif
  XhashStatus ( &h );

  XhashDestroy ( &h );

}


static short int
CubeEquity ( const short int siND, const short int siDT,
             const short int siDP ) {

  if ( siDT >= (siND/2) && siDP >= siND ) {
    /* it's a double */

    if ( siDT >= (siDP/2) )
      /* double, pasi */
      return siDP;
    else
      /* double, take */
      return 2 * siDT;

  }
  else

    /* no double */

    return siND;

}

static int
CalcPosition ( const int i, const int j, const int n ) {

  int max;
  int k;

  max = ( i > j ) ? i : j;

  if ( i + j < n )
    k = ( i + j ) * ( i + j + 1 ) / 2 + j;
  else
    k = n * n - CalcPosition ( n - 1 - i, n - 1 - j, n - 1 ) - 1;

#if 0
  if ( n == 6 ) {
    fprintf ( stderr, "%2d ", k );
    if ( j == n - 1 )
      fprintf ( stderr, "\n" );
  }
#endif

  return k;

}



static void
TSLookup ( const int nUs, const int nThem,
           const int nTSP, const int nTSC,
           short int arEquity[ 4 ], 
           const int n, const int fCubeful,
           FILE *pfTmp ) {

  int iPos = CalcPosition ( nUs, nThem, n );
  unsigned char  ac[ 8 ];
  int i;
  unsigned short int us;

  /* seek to position */

  if ( fseek ( pfTmp, iPos * ( fCubeful ? 8 : 2 ), SEEK_SET ) < 0 ) {
    perror ( "temp file" );
    exit(-1);
  }

  if ( fread ( ac, 1, 8, pfTmp ) < 8 ) {
      if ( errno )
        perror ( "temp file" );
      else
        dsplerr (  "error reading temp file\n" );
      exit(-1);
  }

  /* re-position at EOF */
  
  if ( fseek ( pfTmp, 0L, SEEK_END ) < 0 ) {
    perror ( "temp file" );
    exit(-1);
  }
  
  for ( i = 0; i < ( fCubeful ? 4 : 1 ); ++i ) {
    us = ac[ 2 * i ] | ac[ 2 * i + 1 ] << 8;
    arEquity[ i ] = us - 0x8000;
  }

  ++cLookup;
    
}
  

/*
 * Calculate exact equity for position.
 *
 * We store the equity in two bytes:
 * 0x0000 meaning equity=-1 and 0xFFFF meaning equity=+1.
 *
 */


static void BearOff2( int nUs, int nThem,
                      const int nTSP, const int nTSC,
                      short int asiEquity[ 4 ],
                      const int n, const int fCubeful,
                      xhash *ph, bearoffcontext *pbc, FILE *pfTmp ) {

    int j, anRoll[ 2 ];
    unsigned int i;
	TanBoard anBoard, anBoardTemp;
    movelist ml;
    int aiBest[ 4 ];
    int asiBest[ 4 ];
    int aiTotal[ 4 ];
    short int k;
    short int *psij;
    short int asij[ 4 ];
    const short int EQUITY_P1 = 0x7FFF;
    const short int EQUITY_M1 = ~EQUITY_P1;

    if ( ! nUs ) {

      /* we have won */
      asiEquity[ 0 ] = asiEquity[ 1 ] = 
        asiEquity[ 2 ] = asiEquity[ 3 ] = EQUITY_P1;
      return;

    }

    if ( ! nThem ) {

      /* we have lost */
      asiEquity[ 0 ] = asiEquity[ 1 ] = 
        asiEquity[ 2 ] = asiEquity[ 3 ] = EQUITY_M1;
      return;

    }

    PositionFromBearoff( anBoard[ 0 ], nThem, nTSP, nTSC );
    PositionFromBearoff( anBoard[ 1 ], nUs, nTSP, nTSC );

    for( i = nTSP; i < 25; i++ )
	anBoard[ 1 ][ i ] = anBoard[ 0 ][ i ] = 0;

    /* look for position in bearoff file */

    if ( pbc && isBearoff ( pbc, (ConstTanBoard)anBoard ) ) {
      unsigned short int nUsL = 
        PositionBearoff ( anBoard[ 1 ], pbc->nPoints, pbc->nChequers );
      unsigned short int nThemL = 
        PositionBearoff ( anBoard[ 0 ], pbc->nPoints, pbc->nChequers );
      int nL = Combination ( pbc->nPoints + pbc->nChequers, pbc->nPoints );
      unsigned int iPos = nUsL * nL + nThemL;
      unsigned short int aus[ 4 ];
      
      BearoffCubeful ( pbc, iPos, NULL, aus );

      for ( i = 0; i < 4; ++i )
        asiEquity[ i ] = aus[ i ] - 0x8000;
      
      return;
    }

    aiTotal[ 0 ] = aiTotal[ 1 ] = aiTotal[ 2 ] = aiTotal[ 3 ] = 0;
    
    for( anRoll[ 0 ] = 1; anRoll[ 0 ] <= 6; anRoll[ 0 ]++ )
	for( anRoll[ 1 ] = 1; anRoll[ 1 ] <= anRoll[ 0 ]; anRoll[ 1 ]++ ) {
	    GenerateMoves( &ml, (ConstTanBoard)anBoard, anRoll[ 0 ], anRoll[ 1 ], FALSE );

            asiBest [ 0 ] = asiBest[ 1 ] = 
              asiBest[ 2 ] = asiBest [ 3 ] = -0xFFFF;
            aiBest [ 0 ] = aiBest[ 1 ] = aiBest[ 2 ] = aiBest [ 3 ] = -1;
	    
	    for( i = 0; i < ml.cMoves; i++ ) {
		PositionFromKey( anBoardTemp, ml.amMoves[ i ].auch );

		j = PositionBearoff( anBoardTemp[ 1 ], nTSP, nTSC );

		g_assert( j >= 0 );
		g_assert( j < nUs ); 

                if ( ! nThem ) {
                  asij[ 0 ] = asij[ 1 ] = asij[ 2 ] = asij[ 3 ] = EQUITY_P1;
                }
                else if ( ! j ) {
                  asij[ 0 ] = asij[ 1 ] = asij[ 2 ] = asij[ 3 ] = EQUITY_M1;
                }
                if ( ! (psij = XhashLookup ( ph, n * nThem + j)) ) {
                  /* lookup in file */
		  psij = asij;
                  TSLookup ( nThem, j, nTSP, nTSC, psij, n,
                             fCubeful, pfTmp );
                  XhashAdd ( ph, n * nThem + j, psij, fCubeful ? 8 : 2 );
                }

                /* cubeless */

                if ( psij[ 0 ] < -asiBest[ 0 ] ) { 
                  aiBest [ 0 ] = j;
                  asiBest [ 0 ] = ~psij[ 0 ];
                }

                if ( fCubeful ) {

                  /* I own cube:
                     from opponent's view he doesn't own cube */
                  
                  if ( psij[ 3 ] < -asiBest[ 1 ] ) {
                    aiBest [ 1 ] = j;
                    asiBest [ 1 ] = ~psij[ 3 ];
                  }

                  /* Centered cube (so centered for opponent too) */

                  k = CubeEquity ( psij[ 2 ], psij[ 3 ], EQUITY_P1 ); 
                  if ( ~k > asiBest[ 2 ] ) {
                    aiBest [ 2 ] = j;
                    asiBest [ 2 ] = ~k;
                  }

                  /* Opponent owns cube:
                     from opponent's view he owns cube */

                  k = CubeEquity ( psij[ 1 ], psij[ 3 ], EQUITY_P1 ); 
                  if ( ~k > asiBest[ 3 ] ) {
                    aiBest [ 3 ] = j;
                    asiBest [ 3 ] = ~k;
                  }

                }

	    }

	    g_assert( aiBest[ 0 ] >= 0 );
	    g_assert( ! fCubeful || aiBest[ 1 ] >= 0 );
	    g_assert( ! fCubeful || aiBest[ 2 ] >= 0 );
	    g_assert( ! fCubeful || aiBest[ 3 ] >= 0 );
	    
            if ( anRoll[ 0 ] == anRoll[ 1 ] )
              for ( k = 0; k < ( fCubeful ? 4 : 1 ); ++k )
                aiTotal [ k ] += asiBest[ k ];
            else
              for ( k = 0; k < ( fCubeful ? 4 : 1 ); ++k )
                aiTotal [ k ] += 2 * asiBest[ k ];

	}

    /* final equities */
    for ( k = 0; k < ( fCubeful ? 4 : 1 ); ++k )
      asiEquity[ k ] = aiTotal[ k ] / 36;

}



static void
WriteEquity ( FILE *pf, const short int si ) {
  
  unsigned short int us = si + 0x8000;

  putc( us & 0xFF, pf );
  putc( (us >> 8) & 0xFF, pf );

}

static void
generate_ts ( const int nTSP, const int nTSC, 
              const int fHeader, const int fCubeful,
              const int nHashSize, bearoffcontext *pbc, FILE *output ) {

    int i, j, k;
    int iPos;
    int n;
    short int asiEquity[ 4 ];
    xhash h;
    FILE *pfTmp;
    unsigned char ac[ 8 ];
    char *tmpfile;
#ifndef WIN32
  int fTTY = isatty(STDERR_FILENO);
#endif

#if WIN32
  HINSTANCE hInstance = (HINSTANCE) GetModuleHandle(NULL);
  HWND hwndPB;
  INITCOMMONCONTROLSEX InitCtrlEx;
  if( hdlg != NULL)
    ShowWindow(hdlg, SW_SHOW);

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_PROGRESS_CLASS;
  InitCommonControlsEx(&InitCtrlEx);

  hwndPB = CreateWindowEx(0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE,
		  12, 300, 470, 20, hdlg, NULL, hInstance, NULL);
#endif

	pfTmp = GetTemporaryFile(NULL, &tmpfile);
	if (pfTmp == NULL)
      exit(2);

    /* initialise xhash */
    
#if WIN32
    dlgprintf(127, "Initialising xhash." );
#endif
    
    if ( XhashCreate ( &h, nHashSize /  ( fCubeful ? 8 : 2 ) ) ) {
      dsplerr (  _("Error creating xhash with %d elements\n"),
                nHashSize /  fCubeful ? 8 : 2 );
      exit(2);
    }
    
    XhashStatus ( &h );

    /* write header information */

    if ( fHeader ) {
      char sz[ 41 ];
#if WIN32
      dlgprintf(127, "Writing header information." );
#endif
      sprintf ( sz, "gnubg-TS-%02d-%02d-%1dxxxxxxxxxxxxxxxxxxxxxxx\n", 
                nTSP, nTSC, fCubeful );
      fputs ( sz, output );
    }


    /* generate bearoff database */

    n = Combination ( nTSP + nTSC, nTSC );
    iPos = 0;
    
#if WIN32
    SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, n ));
    SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);
#endif

    /* positions above diagonal */
#if WIN32
    dlgprintf(127, "Calculating positions above diagonal." );
#endif

    for( i = 0; i < n; i++ ) {
      for( j = 0; j <= i; j++, ++iPos ) {

        BearOff2( i - j, j, nTSP, nTSC, asiEquity, n, fCubeful, 
                  &h, pbc, pfTmp );

        for ( k = 0; k < ( fCubeful ? 4 : 1 ); ++k )
          WriteEquity ( pfTmp, asiEquity[ k ] );

        XhashAdd ( &h, ( i - j ) * n + j, asiEquity, fCubeful ? 8 : 2 );

      }
#if WIN32
      SendMessage(hwndPB, PBM_STEPIT, 0, 0);
#else
      if (fTTY)
	      fprintf( stderr, "%d/%d     \r", iPos, n * n );
#endif
    }

    /* positions below diagonal */
#if WIN32
    dlgprintf(127, "Calculating positions below diagonal." );
    SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, n ));
    SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);
#endif

    for( i = 0; i < n; i++ ) {
      for( j = i + 1; j < n; j++, ++iPos ) {
        
        BearOff2( i + n  - j, j, nTSP, nTSC, asiEquity, n, fCubeful,
                  &h, pbc, pfTmp );
        
        for ( k = 0; k < ( fCubeful ? 4 : 1 ); ++k )
          WriteEquity ( pfTmp, asiEquity[ k ] );
        
        XhashAdd ( &h, ( i + n - j ) * n + j, asiEquity, fCubeful ? 8 : 2 );
        
      }
#if WIN32
      SendMessage(hwndPB, PBM_STEPIT, 0, 0);
#else
      if (fTTY)
	      fprintf( stderr, "%d/%d     \r", iPos, n * n );
#endif
    }

#if !WIN32
    putc ( '\n', stderr );
#else
    dlgprintf(127, "Clearing xhash." );
#endif
    XhashStatus ( &h );
    
    XhashDestroy ( &h );
    
    /* sort file from ordering:

       136       123
       258  to   456 
       479       789 

    */
#if WIN32
    dlgprintf(127, "Sorting file." );
    SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, n ));
    SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);
#endif

    for ( i = 0; i < n; ++i ){ 
      for ( j = 0; j < n; ++j ) {

        k = CalcPosition ( i, j, n );

        fseek ( pfTmp, ( fCubeful ? 8 : 2 ) * k, SEEK_SET );
        fread ( ac, 1, fCubeful ? 8 : 2, pfTmp );
        fwrite ( ac, 1, fCubeful ? 8 : 2, output );
      }
#if WIN32
      SendMessage(hwndPB, PBM_STEPIT, 0, 0);
#endif

    }

#if WIN32
    dlgprintf(127, "Closing and unlinking." );
#endif
    fclose ( pfTmp );

    g_unlink ( tmpfile ); 

}




static void
version ( void ) {
#ifndef WIN32
  printf ( "makebearoff $Revision: 1.66 $\n" );
#else
  MessageBox( NULL, "makebearoff $Revision: 1.66 $\n", "Makebearoff", MB_OK );
#endif
}


extern int main( int argc, char **argv )
{
  /* static storage for options to keep picky comipler happy */
  static int nOS = 0;
  static int fHeader = TRUE;
  static int fCompress = TRUE;
  static int fGammon = TRUE;
  static int nHashSize = 100000000;
  static int fCubeful = TRUE;
  static char *szOldBearoff = NULL;
  static int fND = FALSE;
  static char *szOutput = NULL;
  static char *szTwoSided = NULL;
  static int show_version=0;

  bearoffcontext *pbc = NULL;
  FILE *output = stdout;
  double r;
  int nTSP = 0, nTSC = 0;

#if WIN32
  int i;
  char *aszOS[] = {"Number of points:",
		 "Number of chequers:",
		 "Number of positions:",
		 "Approximate by normal distribution:",
		 "Include gammon distributions:",
		 "Use compression scheme:",
		 "Write header:",
		 "Size of cache:",
		 "Reuse old bearoff database:"};
		 
  char *aszTS[]= { "Number of points:", 
                "Number of chequers:",
                "Calculate equities:",
                "Write header:",
                "Number of one-sided positions:",
                "Total number of positions:",
                "Size of resulting file:",
                "Size of xhash:",
                "Reuse old bearoff database:",
                " ", " "};
#endif
           
  GOptionEntry ao[] = {
	  { "two-sided", 't',  0, G_OPTION_ARG_STRING, &szTwoSided,
		  "Number of points (P) and number of chequers (C) for two-sided database", "PxC"},
	  { "one-sided", 'o', 0, G_OPTION_ARG_INT, &nOS, 
		  "Number of points (P) for one-sided database", "P"},
	  { "xhash-size", 's', 0, G_OPTION_ARG_INT, &nHashSize, 
		  "Use cache of size N bytes", "N"},
	  { "old-bearoff", 'O', 0, G_OPTION_ARG_STRING, &szOldBearoff, 
		  "Reuse already generated bearoff database \"filename\"", "filename"},
	  { "no-header", 'H', G_OPTION_FLAG_REVERSE,  G_OPTION_ARG_NONE, &fHeader, 
		  "Do not write header", NULL},
	  { "no-cubeful", 'C', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &fCubeful, 
		  "Do not calculate cubeful equities for two-sided databases", NULL},
	  { "no-compress", 'c', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &fCompress, 
		  "Do not use compression scheme for one-sided databases", NULL},
	  { "no-gammon", 'g', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &fGammon,
		  "Include gammon distribution for one-sided databases", NULL},
	  { "normal-dist", 'n', 0, G_OPTION_ARG_NONE, &fND, 
		  "Approximate one-sided bearoff database with normal distributions", NULL},
	  { "version", 'v', 0, G_OPTION_ARG_NONE, &show_version, 
		  "Prints version and exits", NULL},
	  { "outfile", 'f', 0, G_OPTION_ARG_STRING, &szOutput, 
		  "Required output filename", "filename"}, 
	  {NULL, 0, 0, 0, NULL, NULL, NULL}
  };

  GError *error = NULL;
  GOptionContext *context;

  context = g_option_context_new(NULL);
  g_option_context_add_main_entries(context, ao, PACKAGE);
  g_option_context_parse(context, &argc, &argv, &error);
  g_option_context_free(context);
  if (error) {
  	g_printerr("%s\n", error->message);
  	exit(EXIT_FAILURE);
  }


  if (szTwoSided)
      sscanf ( szTwoSided, "%dx%d", &nTSP, &nTSC );

  if (show_version)
  {
	  version();
	  exit(0);
  }

  if ( ! szOutput ) {
	  g_printerr("Required argument -f missing\n");
    exit(EXIT_FAILURE);
  }

  if ( ! ( output = fopen ( szOutput, "w+b" ) ) ) {
    perror ( szOutput );
    return EXIT_FAILURE;
  }

  /* one sided database */

  if ( nOS ) {

    if ( nOS > 18 ) {
      dsplerr (  _("Size of one-sided bearoff database must be between "
                  "0 and 18\n") );
      exit ( 2 );
    }
#if WIN32 
    hdlg = CreateDialog(NULL, MAKEINTRESOURCE (DLG_MAKEBEAROFF), NULL, (DLGPROC)DlgProc);
    /* error if NULL */
    for (i = 0; i < 9; i++)
       SendDlgItemMessage(hdlg, 101 + i, WM_SETTEXT, 0, (LPARAM) aszOS[i]);
      
    dlgprintf( 116, "%d", nOS);
    dlgprintf( 117, "%d", 15); 
    dlgprintf( 118, "%d", Combination ( nOS + 15, nOS ));
    dlgprintf( 119, "%s", fND ? "yes" : "no");
    dlgprintf( 120, "%s", fGammon ? "yes" : "no"); 
    dlgprintf( 121, "%s", fCompress ? "yes" : "no"); 
    dlgprintf( 122, "%s", fHeader ? "yes" : "no");
    dlgprintf( 123, "%d", nHashSize);
    dlgprintf( 124, "%s", szOldBearoff ? "yes" : "no");
    dlgprintf(130, "Generating one-sided bearoff database. Please wait." );
    dlgprintf(131, "makebearoff $Revision: 1.66 $" );
#else
    fprintf ( stderr, 
              _("One-sided database:\n"
                "Number of points                  : %12d\n"
                "Number of chequers                : %12d\n"
                "Number of positions               : %12d\n"
                "Approximate by normal distribution: %s\n"
                "Include gammon distributions      : %s\n"
                "Use compression scheme            : %s\n"
                "Write header                      : %s\n"
                "Size of cache                     : %12d\n"
                "Reuse old bearoff database        : %s %s\n"),
              nOS, 
              15, 
              Combination ( nOS + 15, nOS ),
              fND ? "yes" : "no",
              fGammon ? "yes" : "no", 
              fCompress ? "yes" : "no", 
              fHeader ? "yes" : "no", 
              nHashSize,
              szOldBearoff ? "yes" : "no",
              szOldBearoff ? szOldBearoff : "" );
#endif

    if ( fND ) {
      r = Combination ( nOS + 15, nOS ) * 16.0;
#if WIN32
      dlgprintf(110, "Size of database:");
      dlgprintf(111, "");
      dlgprintf(125, "%.0f (%.1f MB)", r, r / 1048576.0);
      dlgprintf(126, "");
#else
      fprintf ( stderr, 
                _("Size of database                  : %.0f (%.1f MB)\n"), 
                r, r / 1048576.0 );
#endif
    }
    else {
      r = Combination ( nOS + 15, nOS ) * ( fGammon ? 128.0f : 64.0f );
#if WIN32
      dlgprintf(110, "Size of database (uncompressed):");
      dlgprintf(125, "%.0f (%.1f MB)", r, r / 1048576.0);
#else
      fprintf ( stderr, 
                _("Size of database (uncompressed)   : %.0f (%.1f MB)\n"), 
                r, r / 1048576.0 );
#endif
      if ( fCompress ) {
        r = Combination ( nOS + 15, nOS ) * ( fGammon ? 32.0f : 16.0f );
#if WIN32
        dlgprintf(111, "Estimated size of compressed db:");
        dlgprintf(126, "%.0f (%.1f MB)", r, r / 1048576.0);
#else
        fprintf ( stderr, 
                  _("Estimated size of compressed db   : %.0f (%.1f MB)\n"), 
                  r, r / 1048576.0 );
#endif
      }
    }

    if ( szOldBearoff &&
         ! ( pbc = BearoffInit ( szOldBearoff, BO_NONE, NULL ) ) ) {
      dsplerr ( _("Error initialising old bearoff database!\n" ) );
      exit( 2 );
    }

    /* bearoff database must be of the same kind as the request one-sided
       database */

    if ( pbc && 
         ( pbc->bt != BEAROFF_ONESIDED || pbc->fND != fND || 
           pbc->fGammon < fGammon ) ) {
      dsplerr ( _("The old database is not of the same kind as the"
                  " requested database\n") );
      exit( 2 );
    }
    
    if ( fND ) {
      generate_nd ( nOS, nHashSize, fHeader, pbc, output );
    }
    else {
      generate_os ( nOS, fHeader, fCompress, fGammon, nHashSize, pbc, output );
    }

    if ( pbc ) {
#if !WIN32
      fprintf ( stderr, "Number of reads in old database: %lu\n",
                pbc->nReads );
#endif
      BearoffClose ( pbc );
    }

#if !WIN32
    fprintf ( stderr, "Number of re-reads while generating: %ld\n", 
              cLookup );
#endif
  }
  
  /*
   * Two-sided database
   */

  if ( nTSC && nTSP ) {

    int n = Combination ( nTSP + nTSC, nTSC );

    r = n;
    r = r * r * ( fCubeful ? 8.0 : 2.0 );
#if WIN32 
    hdlg = CreateDialog(NULL, MAKEINTRESOURCE (DLG_MAKEBEAROFF), NULL, (DLGPROC)DlgProc);
    /* error if NULL */
    for (i = 0; i < 11; i++)
       SendDlgItemMessage(hdlg, 101 + i, WM_SETTEXT, 0, (LPARAM) aszTS[i]);
      
    dlgprintf(116, "%d", nTSP);
    dlgprintf(117, "%d", nTSC);
    dlgprintf(118, "%s", 
	fCubeful ? _("cubeless and cubeful") : _("cubeless only"));
    dlgprintf(119, "%s",  fHeader ? _("yes") : ("no"));
    dlgprintf(120, "%d",  n);
    dlgprintf(121, "%d",  n * n);
    dlgprintf(122, "%.0f bytes (%.1f MB)", r, r / 1048576.0);
    dlgprintf(123, "%d bytes",  nHashSize);
    dlgprintf(124, "%s",  szOldBearoff ? szOldBearoff : "No" );
    dlgprintf(125, "" );
    dlgprintf(126, "" );
    dlgprintf(130, "Generating two-sided bearoff database. Please wait." );
    dlgprintf(131, "makebearoff $Revision: 1.66 $" );
#else 
    fprintf ( stderr,
              _("Two-sided database:\n"
                "Number of points             : %12d\n"
                "Number of chequers           : %12d\n"
                "Calculate equities           : %s\n"
                "Write header                 : %s\n"
                "Number of one-sided positions: %12d\n"
                "Total number of positions    : %12d\n"
                "Size of resulting file       : %.0f bytes (%.1f MB)\n"
                "Size of xhash                : %12d bytes\n"
                "Reuse old bearoff database   : %s %s\n"),
              nTSP, nTSC,
              fCubeful ? _("cubeless and cubeful") : _("cubeless only"),
              fHeader ? _("yes") : ("no"),
              n,
              n * n,
              r, r / 1048576.0,
              nHashSize,
              szOldBearoff ? "yes" : "no",
              szOldBearoff ? szOldBearoff : "" );
#endif
    /* initialise old bearoff database */
#if WIN32
    dlgprintf(127, "Initialising old bearoff database." );
#endif
    if ( szOldBearoff &&
         ! ( pbc = BearoffInit ( szOldBearoff, BO_NONE, NULL ) ) ) {
      dsplerr ( _("Error initialising old bearoff database!\n" ) );
      exit( 2 );
    }
    
    /* bearoff database must be of the same kind as the request one-sided
       database */
    
    if ( pbc && ( pbc->bt != BEAROFF_TWOSIDED || pbc->fCubeful != fCubeful ) ) {
      dsplerr ( _("The old database is not of the same kind as the"
                  " requested database\n") );
      exit( 2 );
    }
    
    generate_ts ( nTSP, nTSC, fHeader, fCubeful, nHashSize, pbc, output );

    /* close old bearoff database */

    if ( pbc ) {
#if !WIN32
      fprintf ( stderr, "Number of reads in old database: %lu\n",
                pbc->nReads );
#endif
      BearoffClose ( pbc );
    }
#if !WIN32
    fprintf ( stderr, "Number of re-reads while generating: %ld\n", 
              cLookup );
#endif

  }

  fclose ( output );
#if WIN32
  EndDialog(hdlg, 0);
#endif
  return 0;

}

extern bearoffcontext *
BearoffInitBuiltin ( void ) {

  printf ( "Make makebearoff build (avoid resursive rules Makefile :-)\n" );
  return NULL;

}

#if WIN32
BOOL CALLBACK
DlgProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam){
  
   switch (Message)
   {
   case WM_INITDIALOG:
	   return TRUE;

   case WM_COMMAND:
	switch ( LOWORD(wParam) )
	{
	case IDCANCEL:
           CancelPressed = TRUE;		
	   EndDialog(hwnd, 0);
	   exit(2);
	   return TRUE;
	}
	break;
   }
   return FALSE;
}
#endif