summaryrefslogtreecommitdiff
path: root/src/changes/root.c
blob: d38f8c0a89f9b7fe37b02c16956f395ad44b7987 (plain)
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
/**

Copyright (c) Scott Gasch

Module Name:

    root.c

Abstract:

    Routines dealing with the root of the search tree.  Specifically
    move ordering at the root node, searching, search support, pondering,
    pondering support, and the main iterative deepening loop.

Author:

    Scott Gasch ([email protected]) 21 May 2004

Revision History:

    $Id: root.c 351 2008-06-28 04:21:53Z scott $

**/

#include "chess.h"

volatile MOVE_TIMER g_MoveTimer;
ULONG g_uIterateDepth;
ULONG g_uSoftExtendLimit;
ULONG g_uHardExtendLimit;
ULONG g_uExtensionReduction[MAX_PLY_PER_SEARCH];
FLAG g_fCanSplit[MAX_PLY_PER_SEARCH];
extern FILE *g_pfLogfile;
SCORE g_iRootScore[2] = {0, 0};
SCORE g_iScore;


static void
_SetMoveTimerForPonder(void)
/**

Routine description:

    Set the move timer before a ponder operation.  A time limit of -1
    means search forever... so the only way out of the ponder is for
    new user input to interrupt it.

Parameters:

    void

Return value:

    static void

**/
{
    g_MoveTimer.dStartTime = SystemTimeStamp();
    g_MoveTimer.dSoftTimeLimit = -1;
    g_MoveTimer.dHardTimeLimit = -1;
    g_MoveTimer.uNodeCheckMask = 0x200 - 1;
    g_MoveTimer.bvFlags = 0;
}


void
SetMoveTimerToThinkForever(void)
/**

Routine description:

Parameters:

    void

Return value:

    void

**/
{
    g_MoveTimer.dStartTime = SystemTimeStamp();
    g_MoveTimer.dSoftTimeLimit = -1;
    g_MoveTimer.dHardTimeLimit = -1;
    g_MoveTimer.uNodeCheckMask = 0x1000000 - 1;
    g_MoveTimer.bvFlags = 0;
}


void
SetMoveTimerForSearch(FLAG fSwitchOver, ULONG uColor)
/**

Routine description:

    Set the move timer for a search operation.

Parameters:

    FLAG fSwitchOver : if TRUE then this search is a converted ponder
    (i.e. they made the ponder move and now we are searching).

Return value:

    void

**/
{
    ULONG uMovesDone = GetMoveNumber(uColor);
    double dClock = (double)g_Options.uMyClock;
    double dSec = 0;
    ULONG uMargin = 0;
    ULONG uMovesToDo;

    //
    // If switching over from a ponder search leave the start time and
    // move flags alone (i.e. N seconds in the past already).
    //
    if (FALSE == fSwitchOver)
    {
        g_MoveTimer.dStartTime = SystemTimeStamp();
        g_MoveTimer.bvFlags = 0;
    }

    //
    // Check the clock more often in search if there is little time
    // left on the clock -- we can't afford an oversearch when the
    // bullet game is down to the wire.
    //
#ifdef DEBUG
    g_MoveTimer.uNodeCheckMask = 0x800 - 1;
#else
    if (WeAreRunningASuite())
    {
        g_MoveTimer.uNodeCheckMask = 0x20000 - 1;
    }
    else if (g_Options.u64MaxNodeCount) 
    {
        g_MoveTimer.uNodeCheckMask = 0x1000 - 1;
    }
    else
    {
        if (dClock < 10.0)
        {
            g_MoveTimer.uNodeCheckMask = 0x400 - 1;
        }
        else
        {
            g_MoveTimer.uNodeCheckMask = 0x8000 - 1;
        }
    }
#endif

    switch (g_Options.eClock)
    {
        //
        // Fixed time per move.  Think for g_uMyIncrement seconds exactly and
        // no hard time limit.
        //
        case CLOCK_FIXED:
            dSec = (double)g_Options.uMyIncrement;
            uMargin = 0;
            break;

        //
        // N moves per time control or entire game in time control.
        //
        case CLOCK_NORMAL:
            if (g_Options.uMovesPerTimePeriod != 0)
            {
                //
                // N moves per time control.
                //
                ASSERT(g_Options.uMovesPerTimePeriod < 256);
                uMovesToDo =
                    (g_Options.uMovesPerTimePeriod -
                     ((uMovesDone - 1) % g_Options.uMovesPerTimePeriod));
#ifdef DEBUG
                Trace("SetMoveTimer: %u moves left to do this in %s sec.\n",
                      uMovesToDo, TimeToString(dClock));
#endif
                ASSERT(uMovesToDo <= g_Options.uMovesPerTimePeriod);
                dSec = (dClock / (double)uMovesToDo);
                dSec *= 0.95;
                uMargin = (ULONG)(dSec * 2.2);
                if (uMovesToDo <= 5)
                {
                    dSec *= 0.75;
                    uMargin /= 2;
                }
                break;
            }
            else
            {
                //
                // Fixed time finish entire game.
                //
#ifdef DEBUG
                Trace("SetMoveTimer: finish the game in %s sec.\n",
                      TimeToString(dClock));
#endif
                dSec = dClock / 60;
                uMargin = (ULONG)(dSec * 2.2);
            }
            break;

        //
        // We get back a certain number of seconds with each move made.
        //
        case CLOCK_INCREMENT:
            dSec = g_Options.uMyIncrement;
            dSec += (dClock / 50);
            uMargin = (int)(dSec * 2.2);

#ifdef DEBUG
            Trace("SetMoveTimer: finish the game in %s sec (+%u per move).\n",
                  TimeToString(dClock), g_Options.uMyIncrement);
#endif

            //
            // If we are running out of time, think for less than the
            // increment.
            //
            if (dClock < 20.0)
            {
                dSec -= g_Options.uMyIncrement;
                uMargin = 0;
            }
            ASSERT(dSec > 0);
            break;

        case CLOCK_NONE:
#ifdef DEBUG
            Trace("SetMoveTimer: no time limit, think until interrupted.\n");
#endif
            g_MoveTimer.dHardTimeLimit = -1;
            g_MoveTimer.dSoftTimeLimit = -1;
            goto post;

        default:
            ASSERT(FALSE);
            break;
    }
    if ((dSec + uMargin) >= (dClock * 7 / 8)) uMargin = 0;
    g_MoveTimer.dSoftTimeLimit = g_MoveTimer.dStartTime + dSec;
    g_MoveTimer.dHardTimeLimit = g_MoveTimer.dStartTime + dSec + uMargin;

 post:
    if (TRUE == g_Options.fShouldPost)
    {
        if (g_MoveTimer.dSoftTimeLimit > 0)
        {
            Trace("SetMoveTimer: Soft time limit %s seconds.\n",
                  TimeToString(g_MoveTimer.dSoftTimeLimit -
                               g_MoveTimer.dStartTime));
            ASSERT(g_MoveTimer.dHardTimeLimit > 0);
            Trace("SetMoveTimer: Hard time limit %s seconds.\n",
                  TimeToString(g_MoveTimer.dHardTimeLimit -
                               g_MoveTimer.dStartTime));
            if (TRUE == fSwitchOver)
            {
                Trace("SetMoveTimer: Already searched %s seconds.\n",
                      TimeToString(SystemTimeStamp() -
                                   g_MoveTimer.dStartTime));
            }
        }
#ifdef DEBUG
        Trace("SetMoveTimer: Checking input and timer every %u nodes.\n",
              g_MoveTimer.uNodeCheckMask);
#endif
    }
}


void
ReInitializeSearcherContext(POSITION *pos,
                            SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    Reinitializes a SEARCHER_THREAD_CONTEXT structure.

Parameters:

    POSITION *pos,
    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    void

**/
{
    if (NULL != pos)
    {
        memmove(&(ctx->sPosition), pos, sizeof(POSITION));
    }
    ctx->uPly = 0;
    ctx->uPositional = 133;
    memset(&(ctx->sCounters), 0, sizeof(COUNTERS));
}


void
InitializeSearcherContext(POSITION *pos,
                          SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    Initialize a SEARCHER_THREAD_CONTEXT structure.

Parameters:

    POSITION *pos,
    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    void

**/
{
    ULONG u;

    memset(ctx, 0, sizeof(SEARCHER_THREAD_CONTEXT));
    ReInitializeSearcherContext(pos, ctx);
    ctx->sMoveStack.uUnblockedKeyValue[0] = 1;
    for (u = 1;
         u < MAX_PLY_PER_SEARCH;
         u++)
    {
        ctx->sMoveStack.uUnblockedKeyValue[u] =
            ctx->sMoveStack.uUnblockedKeyValue[u-1] + 0x28F5C28;
    }
}


void
InitializeLightweightSearcherContext(POSITION *pos,
                                     LIGHTWEIGHT_SEARCHER_CONTEXT *ctx)
/**

Routine description:

    Initialize a LIGHTWEIGHT_SEARCHER_CONTEXT structure.

Parameters:

    POSITION *pos,
    LIGHTWEIGHT_SEARCHER_CONTEXT *ctx

Return value:

    void

**/
{
    ULONG u;

    memset(ctx, 0, sizeof(LIGHTWEIGHT_SEARCHER_CONTEXT));
    if (NULL != pos)
    {
        memmove(&(ctx->sPosition), pos, sizeof(POSITION));
    }
    ctx->uPly = 0;
    ctx->uPositional = 133;
    ctx->sMoveStack.uUnblockedKeyValue[0] = 1;
    for (u = 1;
         u < MAX_PLY_PER_SEARCH;
         u++)
    {
        ctx->sMoveStack.uUnblockedKeyValue[u] =
            ctx->sMoveStack.uUnblockedKeyValue[u-1] + 0x28F5C28;
    }
}


void
PostMoveSearchReport(SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    Dump a report to stdout after every move.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx,

Return value:

    void

**/
{
    double d;
    char buf[256];
#ifdef PERF_COUNTERS
    double n;
#endif
    d = (double)g_MoveTimer.dEndTime - (double)g_MoveTimer.dStartTime + 0.01;
    ASSERT(d);
    Trace("---------------------------------------------\n"
          "Searched for %5.1f seconds, saw %"
          COMPILER_LONGLONG_UNSIGNED_FORMAT
          " nodes (%"
          COMPILER_LONGLONG_UNSIGNED_FORMAT
          " qnodes) (%6.0f nps).\n",
          d, ctx->sCounters.tree.u64TotalNodeCount,
          ctx->sCounters.tree.u64QNodeCount,
          ((double)ctx->sCounters.tree.u64TotalNodeCount / d));
    if (g_Options.fThinking)
    {
        snprintf(buf, ARRAY_LENGTH(buf), "d%u, %s, %3.1fs, %6.0fknps, PV=%s",
                 ctx->uRootDepth / ONE_PLY,
                 ScoreToString(ctx->iRootScore),
                 d,
                 ((double)ctx->sCounters.tree.u64TotalNodeCount / d / 1000),
                 ctx->szLastPV);
        Trace("tellothers %s\n", buf);
    }
#ifdef MP
#ifdef PERF_COUNTERS
    if (ctx->sCounters.parallel.uNumSplits > 0)
    {
        n = (double)ctx->sCounters.parallel.uNumSplits;
        Trace("Split %u times total ",
              ctx->sCounters.parallel.uNumSplits);
        Trace("(~%7.2fx/sec).\n", (n / d));
        d = n + 1;
        ASSERT(d);
        n = (double)ctx->sCounters.parallel.uNumSplitsTerminated;
        Trace("  ...%u (%5.2f percent) terminated early.\n",
              ctx->sCounters.parallel.uNumSplitsTerminated, ((n/d) * 100.0));
        DumpHelperIdlenessReport();
    }
#endif
#endif

#ifdef TEST
    AnalyzeFullHashTable();
#endif
#ifdef PERF_COUNTERS
    d = (double)(ctx->sCounters.hash.u64Probes) + 1;
    ASSERT(d);
    Trace("Hashing percentages: (%5.3f total, %5.3f useful)\n",
          ((double)(ctx->sCounters.hash.u64OverallHits) / d) * 100.0,
          ((double)(ctx->sCounters.hash.u64UsefulHits) / d) * 100.0);
    d = (double)(ctx->sCounters.pawnhash.u64Probes) + 1;
    ASSERT(d);
    n = (double)(ctx->sCounters.pawnhash.u64Hits);
    Trace("Pawn hash hitrate: %5.3f percent.\n", (n/d) * 100.0);
    n = (double)(ctx->sCounters.tree.u64NullMoveSuccess);
    d = (double)(ctx->sCounters.tree.u64NullMoves) + 1;
    ASSERT(d);
    Trace("Null move cutoff rate: %5.3f percent.\n",
          ((n / d) * 100.0));
#ifdef TEST_ENDGAME
    n = (double)(ctx->sCounters.tree.u64EndgamePruningSuccess);
    d = n + (double)(ctx->sCounters.tree.u64EndgamePruningFailures);
    if (d != 0.0)
    {
        Trace("Endgame pruning heuristic success rate was %5.3f percent.\n"
              "Endgame pruning heuristic was "
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT " / "
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT ".\n",
              ((n / d) * 100.0),
              ctx->sCounters.tree.u64EndgamePruningSuccess,
              (ctx->sCounters.tree.u64EndgamePruningSuccess +
               ctx->sCounters.tree.u64EndgamePruningFailures));
    }
    else
    {
        Trace("Never used endgame pruning heuristic.\n");
    }
#endif
#ifdef TEST_NULL
    n = (double)(ctx->sCounters.tree.u64AvoidNullSuccess);
    d = n + (double)(ctx->sCounters.tree.u64AvoidNullFailures);
    if (d != 0.0)
    {
        Trace("Avoid null move heuristic rate was %5.3f percent.\n"
              "Avoid null move heuristic was "
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT " / "
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT ".\n",
              ((n / d) * 100.0),
              ctx->sCounters.tree.u64AvoidNullSuccess,
              (ctx->sCounters.tree.u64AvoidNullSuccess +
               ctx->sCounters.tree.u64AvoidNullFailures));
    }
    else
    {
        Trace("Never used the avoid null move heuristic.\n");
    }
    n = (double)(ctx->sCounters.tree.u64QuickNullSuccess);
    n += (double)(ctx->sCounters.tree.u64QuickNullDeferredSuccess);
    d = n + (double)(ctx->sCounters.tree.u64QuickNullFailures);
    if (d != 0.0)
    {
        Trace("Quick null move heuristic rate was %5.3f percent.\n"
              "Quick null move heuristic rate was "
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT " ("
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT ") / "
              "%"COMPILER_LONGLONG_UNSIGNED_FORMAT ".\n",
              ((n / d) * 100.0),
              ctx->sCounters.tree.u64QuickNullSuccess,
              ctx->sCounters.tree.u64QuickNullDeferredSuccess,
              (ctx->sCounters.tree.u64QuickNullSuccess +
               ctx->sCounters.tree.u64QuickNullDeferredSuccess +
               ctx->sCounters.tree.u64QuickNullFailures));
    }
    else
    {
        Trace("Never used the quick null move heuristic.\n");
    }
#endif
    n = (double)ctx->sCounters.tree.u64BetaCutoffsOnFirstMove;
    d = (double)ctx->sCounters.tree.u64BetaCutoffs + 1;
    Trace("First move beta cutoff rate was %5.3f percent.\n",
          ((n / d) * 100.0));
#ifdef LAZY_EVAL
    d = (double)ctx->sCounters.tree.u64LazyEvals;
    d += (double)ctx->sCounters.tree.u64FullEvals;
    d += (double)ctx->sCounters.tree.u64EvalHashHits;
    d += 1;
    ASSERT(d);
    Trace("Eval percentages: (%5.2f hash, %5.2f lazy, %5.2f full)\n",
          ((double)ctx->sCounters.tree.u64EvalHashHits / d) * 100.0,
          ((double)ctx->sCounters.tree.u64LazyEvals / d) * 100.0,
          ((double)ctx->sCounters.tree.u64FullEvals / d) * 100.0);
#endif
    Trace("Extensions: (%u +, %u q+, %u 1mv, %u !kmvs, %u mult+, %u pawn\n"
          "             %u threat, %u zug, %u sing, %u endg, %u bm, %u recap)\n",
          ctx->sCounters.extension.uCheck,
          ctx->sCounters.extension.uQExtend,
          ctx->sCounters.extension.uOneLegalMove,
          ctx->sCounters.extension.uNoLegalKingMoves,
          ctx->sCounters.extension.uMultiCheck,
          ctx->sCounters.extension.uPawnPush,
          ctx->sCounters.extension.uMateThreat,
          ctx->sCounters.extension.uZugzwang,
          ctx->sCounters.extension.uSingularReplyToCheck,
          ctx->sCounters.extension.uEndgame,
          ctx->sCounters.extension.uBotvinnikMarkoff,
          ctx->sCounters.extension.uRecapture);
#ifdef EVAL_TIME
    n = (double)ctx->sCounters.tree.u64CyclesInEval;
    Trace("Avg. cpu cycles in eval: %8.1f.\n", (n / d));
#endif
#endif
    fflush(g_pfLogfile);
}


SCORE
RootSearch(SEARCHER_THREAD_CONTEXT *ctx,
           SCORE iAlpha,
           SCORE iBeta,
           ULONG uDepth)
/**

Routine description:

    Search at the root of the whole tree.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx,
    SCORE iAlpha,
    SCORE iBeta,
    ULONG uDepth,

Return value:

    SCORE

**/
{
    PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
    SCORE iBestScore = -INFINITY;
    SCORE iInitialAlpha = iAlpha;
    MOVE mv;
    ULONG x, y;
    SCORE iScore;
    ULONG uNextDepth;
    UINT64 u64StartingNodeCount;
    ULONG uNumLegalMoves;

#ifdef DEBUG
	POSITION *pos = &ctx->sPosition;
    ASSERT(IS_VALID_SCORE(iAlpha));
    ASSERT(IS_VALID_SCORE(iBeta));
    ASSERT(iAlpha < iBeta);
    ASSERT((ctx->uPly == 0) || (ctx->uPly == 1)); // 1 is for under a ponder
    memcpy(&pi->sPosition, pos, sizeof(POSITION));
#endif

    ctx->sCounters.tree.u64TotalNodeCount++;
    pi->PV[ctx->uPly] = NULLMOVE;
    pi->mvBest = NULLMOVE;
    g_MoveTimer.bvFlags |= TIMER_SEARCHING_FIRST_MOVE;
#ifdef DEBUG
    Trace("---- depth=%u, a=%d, b=%d ----\n", uDepth / ONE_PLY, iAlpha, iBeta);
#endif

    uNumLegalMoves = 0;
    for (x = ctx->sMoveStack.uBegin[ctx->uPly];
         x < ctx->sMoveStack.uEnd[ctx->uPly];
         x++)
    {
        SelectMoveAtRoot(ctx, x);
        if (ctx->sMoveStack.mvf[x].bvFlags & MVF_MOVE_SEARCHED) break;
        ctx->sMoveStack.mvf[x].bvFlags |= MVF_MOVE_SEARCHED;
        mv = ctx->sMoveStack.mvf[x].mv;
        mv.bvFlags |= WouldGiveCheck(ctx, mv);

        if (MakeMove(ctx, mv))
        {
            uNumLegalMoves++;
            u64StartingNodeCount = ctx->sCounters.tree.u64TotalNodeCount;

            //
            // TODO: Fancy recap shit here?
            //

            uNextDepth = uDepth - ONE_PLY;
            if (IS_CHECKING_MOVE(mv))
            {
                uNextDepth += HALF_PLY;
                ctx->sPlyInfo[ctx->uPly].iExtensionAmount = HALF_PLY;
            }

            ctx->sSearchFlags.fVerifyNullmove = TRUE;
            ctx->sSearchFlags.uQsearchDepth = 0;
            if (uNumLegalMoves == 1)
            {
                //
                // Move 1, full a..b window
                //
                iScore = -Search(ctx, -iBeta, -iAlpha, uNextDepth);
            }
            else
            {
                //
                // Moves 2..N, minimal window search
                //
                ASSERT(x > 0);
                ASSERT(uNumLegalMoves > 1);
                iScore = -Search(ctx, -iAlpha - 1, -iAlpha, uNextDepth);
                if ((iAlpha < iScore) && (iScore < iBeta))
                {
                    iScore = -Search(ctx, -iBeta, -iAlpha, uNextDepth);
                }
            }
            ctx->sSearchFlags.fVerifyNullmove = FALSE;
            UnmakeMove(ctx, mv);
            if (WE_SHOULD_STOP_SEARCHING)
            {
                iBestScore = INVALID_SCORE;
                goto end;
            }
#ifdef DEBUG
            Trace("%2u. %-8s => node=%" COMPILER_LONGLONG_UNSIGNED_FORMAT
                  ", predict=%d, actual=%d, ",
                  x + 1,
                  MoveToSan(mv, &ctx->sPosition),
                  u64StartingNodeCount,
                  ctx->sMoveStack.mvf[x].iValue,
                  iScore);
            ASSERT(PositionsAreEquivalent(&pi->sPosition, &ctx->sPosition));
#endif
            //
            // Keep track of how many moves are under each one we
            // search and use this as the basis for root move ordering
            // next iteration.
            //
            u64StartingNodeCount = (ctx->sCounters.tree.u64TotalNodeCount -
                                    u64StartingNodeCount);
            u64StartingNodeCount >>= 9;
            u64StartingNodeCount &= (MAX_INT / 4);
            ctx->sMoveStack.mvf[x].iValue =
                (SCORE)(u64StartingNodeCount + iScore);
#ifdef DEBUG
            Trace("next_predict: %d\n", ctx->sMoveStack.mvf[x].iValue);
            ASSERT(iBestScore <= iAlpha);
            ASSERT(iAlpha < iBeta);
#endif
            if (iScore > iBestScore)
            {
                iBestScore = iScore;
                pi->mvBest = mv;
                if (iScore > iAlpha)
                {
                    //
                    // We have a best move so far.  As of now it is
                    // the one we'll be playing.  Also make sure to
                    // search it first at the next depth.
                    //
#ifdef DEBUG
                    Trace("Best so far... root score=%d.\n", iScore);
#endif
                    ctx->mvRootMove = mv;
                    ctx->iRootScore = iScore;
                    ctx->uRootDepth = uDepth;
                    ctx->sMoveStack.mvf[x].iValue = MAX_INT;

                    //
                    // If there was a previous PV move then knock its
                    // score down so that it will be considered second
                    // on the next depth.
                    //
                    for (y = ctx->sMoveStack.uBegin[ctx->uPly];
                         y < x;
                         y++)
                    {
                        if (ctx->sMoveStack.mvf[y].iValue == MAX_INT)
                        {
                            ctx->sMoveStack.mvf[y].iValue /= 2;
                        }
                    }

                    UpdatePV(ctx, mv);
                    if (iScore >= iBeta)
                    {
                        //
                        // Root fail high...
                        //
                        UpdateDynamicMoveOrdering(ctx,
                                                  uDepth,
                                                  mv,
                                                  iScore,
                                                  x + 1);
                        UtilPrintPV(ctx, iAlpha, iBeta, iScore, mv);
                        KEEP_TRACK_OF_FIRST_MOVE_FHs(iBestScore == -INFINITY);
                        ctx->sMoveStack.mvf[x].bvFlags &= ~MVF_MOVE_SEARCHED;
                        goto end;
                    }
                    else
                    {
                        //
                        // Root PV change...
                        //
                        UtilPrintPV(ctx, iAlpha, iBeta, iScore, mv);
                        iAlpha = iScore;
                    }
				}
            }
            g_MoveTimer.bvFlags &= ~TIMER_SEARCHING_FIRST_MOVE;
        }
    }

    if (iAlpha == iInitialAlpha)
    {
        //
        // Root fail low...
        //
        ASSERT(iBestScore <= iAlpha);
        ASSERT(PositionsAreEquivalent(pos, &pi->sPosition));
        UtilPrintPV(ctx, iAlpha, iBeta, iBestScore, mv);
    }

 end:
    return(iBestScore);
}



static GAME_RESULT
_DetectPreMoveTerminalStates(SEARCHER_THREAD_CONTEXT *ctx,
                             FLAG fInCheck,
                             MOVE *pmv) {
    ULONG u;
    MOVE mv;
    MOVE mvLegal;
    ULONG uNumLegal = 0;
    GAME_RESULT ret;

    ret.eResult = RESULT_IN_PROGRESS;
    ret.szDescription[0] = '\0';
    pmv->uMove = 0;

    for (u = ctx->sMoveStack.uBegin[ctx->uPly];
         u < ctx->sMoveStack.uEnd[ctx->uPly];
         u++) {
        mv = ctx->sMoveStack.mvf[u].mv;
        if (MakeMove(ctx, mv)) {
            mvLegal = mv;
            uNumLegal += 1;
            UnmakeMove(ctx, mv);
            if (uNumLegal > 1) {
                return ret;
            }
        }
    }

    if (uNumLegal == 1) {
        *pmv = mvLegal;
    }
    if (uNumLegal == 0) {
        if (TRUE == fInCheck) {
            if (ctx->sPosition.uToMove == WHITE) {
                ret.eResult = RESULT_BLACK_WON;
                strcpy(ret.szDescription, "black checkmated white");
                return ret;
            }
            ret.eResult = RESULT_WHITE_WON;
            strcpy(ret.szDescription, "white checkmated black");
            return ret;
        }
        ret.eResult = RESULT_DRAW;
        strcpy(ret.szDescription, "stalemate");
    }
    return ret;
}



static GAME_RESULT
_DetectPostMoveTerminalStates(SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    This function is called by Iterate and MakeTheMove to declare
    wins/losses/draws.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    FLAG

**/
{
    GAME_RESULT ret;
    FLAG fInCheck = InCheck(&ctx->sPosition, ctx->sPosition.uToMove);

    // Did we just make the 50th+ move without progress?
    if (ctx->sPosition.uFifty >= 100) {
        ret.eResult = RESULT_DRAW;
        strcpy(ret.szDescription, "fifty moves without progress");
        return ret;
    }
    
    // Did we just repeat a position for the 3rd time?
    if (IsLegalDrawByRepetition()) {
        ret.eResult = RESULT_DRAW;
        strcpy(ret.szDescription, "third repetition of position");
        return ret;
    }

    // Did we just checkmate or stalemate our opponent?  The conditions
    // here are the same as PreMove... so call that code.
    GenerateMoves(ctx, NULLMOVE, (fInCheck ? GENERATE_ESCAPES :
                                             GENERATE_ALL_MOVES));
    MOVE mvUnused;
    return _DetectPreMoveTerminalStates(ctx, 
                                        fInCheck, 
                                        &mvUnused);
}


static void
_IterateSetSearchGlobals(ULONG uDepth)
{
    ULONG u, v;
    ULONG uDontSplitLessThan;

    //
    // Set some globals that will be used throughout this search.
    //
    g_uIterateDepth = uDepth;
    ASSERT(g_uIterateDepth > 0);
    ASSERT(g_uIterateDepth < MAX_PLY_PER_SEARCH);

    //
    // For use in scaling back extensions that are very far from
    // the root.
    //
    //          Iterate   g_Soft              g_Hard
    //   |    |    |    |    |    |    |    |    |
    //   0         1         2   2.5   3   3.5   4       (x Iterate)
    //   |-------------------|----|----|---------|----...
    //   |full full full full|-1/4|-1/2|-3/4 -3/4|none...
    //
    g_uSoftExtendLimit = g_uIterateDepth * 2;
    g_uHardExtendLimit = g_uIterateDepth * 4;
    for (u = 0; u < MAX_PLY_PER_SEARCH; u++)
    {
        if (u < g_uSoftExtendLimit)
        {
            g_uExtensionReduction[u] = 0;
        }
        else if (u < (g_uSoftExtendLimit + g_uIterateDepth / 2))
        {
            g_uExtensionReduction[u] = QUARTER_PLY;
        }
        else if (u < (g_uSoftExtendLimit + g_uIterateDepth))
        {
            g_uExtensionReduction[u] = HALF_PLY;
        }
        else if (u < g_uHardExtendLimit)
        {
            g_uExtensionReduction[u] = THREE_QUARTERS_PLY;
        }
        else
        {
            g_uExtensionReduction[u] = 5 * ONE_PLY;
        }
    }

    //
    // Determine how much depth we need below a point in the tree in
    // order to split the search (which is based on iteration depth).
    //
    uDontSplitLessThan = (ULONG)((double)(uDepth) * 0.30);
    for (v = 0; v < MAX_PLY_PER_SEARCH; v++)
    {
        g_fCanSplit[v] = ((v + 1) >= uDontSplitLessThan);
    }
	g_fCanSplit[0] = FALSE;
}


#define SKIP_GRADUAL_OPENING 600
#define INITIAL_HALF_WINDOW  75
#define FIRST_FAIL_STEP      150
#define SECOND_FAIL_STEP     375

void
_IterateWidenWindow(ULONG uColor,
                    SCORE iScore,
                    SCORE *piBound,
                    ULONG *puState,
                    int iDir)
{
    SCORE iRoughScore = g_iRootScore[uColor];
    static SCORE _Steps[] =
    {
        FIRST_FAIL_STEP,
        SECOND_FAIL_STEP,
        INFINITY
    };

//    Trace("State = %u.\n", *puState);
//    Trace("Bound from %d to ", *piBound);
    if ((abs(iRoughScore - iScore) > SKIP_GRADUAL_OPENING) ||
        (*puState == 2))
    {
        *piBound = iDir * INFINITY;
        *puState = 2;
    }
    else
    {
        ASSERT(*puState < 2);
        *piBound = iScore;
        *piBound += iDir * _Steps[*puState];
        *puState += 1;
    }
//    Trace("%d.\n", *piBound);
//    Trace("State = %u\n", *puState);
}


GAME_RESULT Iterate(SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    Main iterative deepening loop for both thinking and pondering.
    Call RootSearch with progressively deeper depths while there is
    remaining time, we haven't found a forced mate, and there's no
    user interruption.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    FLAG : is the game over?

**/
{
    ULONG uNumRootFailLows = 0;
    ULONG uDepth;
    ULONG uFailState = 0;
    ULONG uColor;
    ULONG u;
    SCORE iAlpha = -INFINITY;
    SCORE iBeta = +INFINITY;
    SCORE iScore;
    FLAG fInCheck = InCheck(&(ctx->sPosition), ctx->sPosition.uToMove);
    MOVE mv;
    GAME_RESULT ret;
#ifdef DEBUG
    POSITION board;
    memcpy(&board, &(ctx->sPosition), sizeof(POSITION));
    VerifyPositionConsistency(&board, FALSE);
#endif

    uColor = ctx->sPosition.uToMove;
    g_iRootScore[uColor] = GetRoughEvalScore(ctx, iAlpha, iBeta, TRUE);
    g_iRootScore[FLIP(uColor)] = -g_iRootScore[uColor];

    //
    // Generate moves here so that RootSearch doesn't have to.
    //
    ASSERT((ctx->uPly == 0) || (ctx->uPly == 1)); // 1 is under a ponder
    ctx->sPlyInfo[ctx->uPly].fInCheck = fInCheck;
    GenerateMoves(ctx, NULLMOVE, (fInCheck ? GENERATE_ESCAPES : 
                                             GENERATE_ALL_MOVES));
    ASSERT(ctx->sMoveStack.uBegin[0] == 0);

    //
    // See if we are sitting at a checkmate or stalemate position; no
    // sense searching if so.
    //
    ret = _DetectPreMoveTerminalStates(ctx, 
                                       fInCheck, 
                                       &mv);
    if (ret.eResult != RESULT_IN_PROGRESS) {
        goto end;
    }
    
    // One legal move available?
    if (mv.uMove != 0) {
        ctx->mvRootMove = mv;
        ctx->iRootScore = 0;
        ctx->uRootDepth = 0;
        ctx->sPlyInfo[0].PV[0] = mv;
        ctx->sPlyInfo[0].PV[1] = NULLMOVE;
        strcpy(ctx->szLastPV, "only");
        if (!g_Options.fPondering) {
            Trace("ONLY MOVE --> stop searching now\n");
            g_MoveTimer.bvFlags |= TIMER_STOPPING;
            g_MoveTimer.bvFlags |= TIMER_CURRENT_OBVIOUS;
        } else {
            Trace("ONLY PONDER --> move immediately if prediction correct.\n");
            g_MoveTimer.bvFlags |= TIMER_MOVE_IMMEDIATELY;
            g_MoveTimer.bvFlags |= TIMER_CURRENT_OBVIOUS;
        }
        goto end;
    }

    for (uDepth = 1;
         uDepth <= g_Options.uMaxDepth;
         uDepth++)
    {
        //
        // Re-rank the moves based on nodecounts and mark all moves as
        // not yet searched at this depth.
        //
        for (u = ctx->sMoveStack.uBegin[ctx->uPly];
             u < ctx->sMoveStack.uEnd[ctx->uPly];
             u++)
        {
            ctx->sMoveStack.mvf[u].bvFlags &= ~MVF_MOVE_SEARCHED;
        }

        //
        // Make sure a..b window makes sense and set some other per-depth
        // globals used by the search.
        //
        _IterateSetSearchGlobals(uDepth);

        //
        // Try to get a PV for this depth before we're out of time...
        //
        do
        {
            if (iBeta > INFINITY) iBeta = +INFINITY;
            if (iAlpha < -INFINITY) iAlpha = -INFINITY;
            if (iAlpha >= iBeta) iAlpha = iBeta - 1;
            iScore = RootSearch(ctx,
                                iAlpha,
                                iBeta,
                                uDepth * ONE_PLY + HALF_PLY);
            if (g_MoveTimer.bvFlags & TIMER_STOPPING) break;
            mv = ctx->mvRootMove;

            //
            // Got a PV, we're done with this depth.
            //
            if ((iAlpha < iScore) && (iScore < iBeta))
            {
                ASSERT(iScore == ctx->iRootScore);
                ASSERT(mv.uMove);
                ASSERT(SanityCheckMove(&ctx->sPosition, mv));
                iAlpha = iScore - INITIAL_HALF_WINDOW;
                iBeta = iScore + INITIAL_HALF_WINDOW;
                g_iRootScore[uColor] = iScore;
                g_iRootScore[FLIP(uColor)] = -iScore;
                g_MoveTimer.bvFlags &= ~TIMER_RESOLVING_ROOT_FH;
                g_MoveTimer.bvFlags &= ~TIMER_RESOLVING_ROOT_FL;
                uFailState = 0;
                (void)CheckTestSuiteMove(mv, iScore, uDepth);
                break;
            }

            //
            // Root fail low?  We'll have to research with a wider
            // window.
            //
            else if (iScore <= iAlpha)
            {
                ASSERT(ctx->mvRootMove.uMove);
                g_MoveTimer.bvFlags |= TIMER_RESOLVING_ROOT_FL;
                uNumRootFailLows++;
                if (uNumRootFailLows > 3)
                {
                    g_MoveTimer.bvFlags |= TIMER_MANY_ROOT_FLS;
                }
                _IterateWidenWindow(uColor, iScore, &iAlpha, &uFailState, -1);

                //
                // Consider all moves again with wider window...
                //
                for (u = ctx->sMoveStack.uBegin[ctx->uPly];
                     u < ctx->sMoveStack.uEnd[ctx->uPly];
                     u++)
                {
                    ctx->sMoveStack.mvf[u].bvFlags &= ~MVF_MOVE_SEARCHED;
                }
            }

            //
            // Must be a root fail high.
            //
            else
            {
                ASSERT(iScore >= iBeta);
                ASSERT(mv.uMove);
                ASSERT(SanityCheckMove(&ctx->sPosition, mv));
                g_MoveTimer.bvFlags |= TIMER_RESOLVING_ROOT_FH;
                _IterateWidenWindow(uColor, iScore, &iBeta, &uFailState, +1);
            }
        }
        while(1); // repeat until we run out of time or fall inside a..b

        //
        // We are here because either:
        //
        //    1. we completed a search depth,
        // or 2. we ran out of time,
        // or 3. there is one legal move and we want to make it immediately,
        // or 4. there was user input and we unrolled the search.
        //

        //
        // TODO: Scale back history between iterative depths?
        //

        //
        // Mate-in-n when we have searched n?  Stop searching.
        //
        if (IS_VALID_SCORE(iScore) &&
            (ULONG)abs(iScore) >= (INFINITY - uDepth))
        {
            Trace("FORCED MATE --> stop searching now\n");
            g_MoveTimer.bvFlags |= TIMER_STOPPING;
        }

        //
        // Have we reached user's maxdepth option?  Stop searching.
        //
        if (uDepth >= g_Options.uMaxDepth)
        {
            Trace("DEPTH LIMIT --> stop searching now\n");
            g_MoveTimer.bvFlags |= TIMER_STOPPING;
        }

        //
        // Did the move timer expire?  Stop searching.
        //
        if (g_MoveTimer.bvFlags & TIMER_STOPPING) break;
    }
    g_Options.u64NodesSearched = ctx->sCounters.tree.u64TotalNodeCount;
    g_MoveTimer.dEndTime = SystemTimeStamp();

    //
    // Here we are at the end of a search.  If we were:
    //
    // ...Searching then:               ...Pondering then:
    //
    // 1. we ran out of time            1. they made a different move than
    //                                     the predicted move and we aborted
    // 2. we ran out of depth
    //                                  2. we ran out of depth
    // 3. we found a mate-in-n
    //                                  3. we found a mate-in-n
    // TODO: node count limit?
    //                                 (4. if they made the predicted move
    //                                     then we converted to a search)
    //
    ASSERT(ctx->mvRootMove.uMove);
    ASSERT(SanityCheckMove(&board, ctx->mvRootMove));
    if (g_MoveTimer.bvFlags & TIMER_RESOLVING_ROOT_FL)
    {
        ctx->sPlyInfo[ctx->uPly].PV[ctx->uPly] = ctx->mvRootMove;
        ctx->sPlyInfo[ctx->uPly].PV[ctx->uPly+1] = NULLMOVE;
    }
    ret.eResult = RESULT_IN_PROGRESS;
    ret.szDescription[0] = '\0';
 end:
    return ret;
}

void
MakeTheMove(SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    Make the move that search selected in the official game list.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    FLAG

**/
{
    MOVE mv = ctx->mvRootMove;
    ASSERT(mv.uMove);

    if (TRUE == g_Options.fThinking)
    {
        //
        // TODO: keep track of how many moves in a row we are at or
        // below a draw score and use this to respond to draw offers.
        //

        //
        // Was this a search that converted from a ponder?
        //
        if (TRUE == g_Options.fSuccessfulPonder)
        {
            if (FALSE == OfficiallyMakeMove(g_Options.mvPonder, 0, FALSE))
            {
                UtilPanic(CANNOT_OFFICIALLY_MAKE_MOVE,
                          GetRootPosition(),
                          (void *)g_Options.mvPonder.uMove,
                          NULL,
                          NULL,
                          __FILE__,
                          __LINE__);
            }
            g_Options.fSuccessfulPonder = FALSE;
        }

        //
        // Tell the server about our move and actually play it on the
        // root board.
        //
        Trace("move %s\n", MoveToSan(mv, &ctx->sPosition));
        if (FALSE == OfficiallyMakeMove(mv, g_iScore, FALSE))
        {
            UtilPanic(CANNOT_OFFICIALLY_MAKE_MOVE,
                      GetRootPosition(),
                      (void *)mv.uMove,
                      NULL,
                      NULL,
                      __FILE__,
                      __LINE__);
        }
        if (g_Options.fVerbosePosting)
        {
            PostMoveSearchReport(ctx);
            PostMoveTestSuiteReport(ctx);
        }
    }
    g_Options.fPondering = g_Options.fThinking = FALSE;
}


GAME_RESULT
Ponder(POSITION *pos)
/**

Routine description:

    Prepare to ponder.

Parameters:

    POSITION *pos

Return value:

    FLAG

**/
{
    static SEARCHER_THREAD_CONTEXT ctx;
    GAME_RESULT ret;

    InitializeSearcherContext(pos, &ctx);
    g_Options.fPondering = TRUE;
    g_Options.fThinking = FALSE;
    g_Options.fSuccessfulPonder = FALSE;
    ret.eResult = RESULT_IN_PROGRESS;
    ret.szDescription[0] = '\0';

    //
    // When do we not want to ponder
    //
    if ((g_Options.ePlayMode == FORCE_MODE) || (g_Options.uMyClock < 10))
    {
        g_Options.fPondering = FALSE;
        return ret;
    }

    //
    // What should we ponder?
    //
    g_Options.mvPonder = GetPonderMove(pos);
    if (g_Options.mvPonder.uMove == 0)
    {
        g_Options.fPondering = FALSE;
        return ret;
    }
    ASSERT(SanityCheckMove(pos, g_Options.mvPonder));

    //
    // Prepare to ponder by doing some maintenance on the dynamic move
    // ordering scheme counters, changing the dirty tag in the hash
    // code, and clearing the root nodes-per-move hash.
    //
    MaintainDynamicMoveOrdering();
    DirtyHashTable();

    //
    // Make the move ponder move.
    //
    if (FALSE == MakeMove(&ctx, g_Options.mvPonder))
    {
        ASSERT(FALSE);
        g_Options.fPondering = FALSE;
        return ret;
    }

    //
    // TODO: probe the book
    //

    _SetMoveTimerForPonder();

    //
    // TODO: Any preEval?
    //

    //
    // TODO: Set draw value
    //

    MakeStatusLine();
#if (PERF_COUNTERS && MP)
    ClearHelperThreadIdleness();
#endif
    ASSERT(ctx.uPly == 1);
    ret = Iterate(&ctx);
    ASSERT(ctx.uPly == 1);
    if (ret.eResult == RESULT_IN_PROGRESS) {
        MakeTheMove(&ctx);
        return _DetectPostMoveTerminalStates(&ctx);
    } else {
        return ret;
    }
}


GAME_RESULT Think(POSITION *pos)
/**

Routine description:

    Prepare to think.

Parameters:

    POSITION *pos

Return value:

    FLAG

**/
{
    static SEARCHER_THREAD_CONTEXT ctx;
    MOVE mvBook;
	  CHAR *p;

    InitializeSearcherContext(pos, &ctx);
    g_MoveTimer.bvFlags = 0;
    g_Options.fPondering = FALSE;
    g_Options.fThinking = TRUE;
    g_Options.fSuccessfulPonder = FALSE;

    //
    // Prepare to think by doing some maintenance on the dynamic move
    // ordering scheme counters, changing the dirty tag in the hash
    // code, and clearing the root nodes-per-move hash.
    //
    if (NULL != (p = PositionToFen(&(ctx.sPosition))))
    {
        Trace("The root position is: %s\n", p);
        SystemFreeMemory(p);
    }
    MaintainDynamicMoveOrdering();
    DirtyHashTable();

    //
    // Check the opening book, maybe it has a move for us.
    //
    if ((g_uBookProbeFailures < 3) && (!WeAreRunningASuite()))
    {
        mvBook = BookMove(pos, BOOKMOVE_SELECT_MOVE);
        if (mvBook.uMove == 0)
        {
            g_uBookProbeFailures++;
        }
        else
        {
            g_uBookProbeFailures = 0;
            ASSERT(SanityCheckMove(pos, mvBook));
            ctx.mvRootMove = mvBook;
            MakeTheMove(&ctx);
            return _DetectPostMoveTerminalStates(&ctx);
        }
    }

    //
    // TODO: Any preEval?
    //

    //
    // Set time limit for move
    //
    SetMoveTimerForSearch(FALSE, pos->uToMove);

    //
    // TODO: Set draw value
    //
#if (PERF_COUNTERS && MP)
    ClearHelperThreadIdleness();
#endif
    GAME_RESULT ret = Iterate(&ctx);
    if (ret.eResult == RESULT_IN_PROGRESS) {
        MakeTheMove(&ctx);
        return _DetectPostMoveTerminalStates(&ctx);
    } else {
        return ret;
    }
}