]> git.sesse.net Git - stockfish/blob - src/search.cpp
Fix a couple of bugs (fallout from previous patches)
[stockfish] / src / search.cpp
1 /*
2   Glaurung, a UCI chess playing engine.
3   Copyright (C) 2004-2008 Tord Romstad
4
5   Glaurung is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9   
10   Glaurung is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14   
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25 #include <cstdio>
26 #include <fstream>
27 #include <iostream>
28 #include <sstream>
29
30 #include "book.h"
31 #include "evaluate.h"
32 #include "history.h"
33 #include "misc.h"
34 #include "movepick.h"
35 #include "san.h"
36 #include "search.h"
37 #include "thread.h"
38 #include "tt.h"
39 #include "ucioption.h"
40
41
42 ////
43 //// Local definitions
44 ////
45
46 namespace {
47
48   /// Types
49
50   // The RootMove class is used for moves at the root at the tree.  For each
51   // root move, we store a score, a node count, and a PV (really a refutation
52   // in the case of moves which fail low).
53
54   class RootMove {
55
56   public:
57     RootMove();
58     Move move;
59     Value score;
60     int64_t nodes, cumulativeNodes;
61     Move pv[PLY_MAX_PLUS_2];
62   };
63
64
65   // The RootMoveList class is essentially an array of RootMove objects, with
66   // a handful of methods for accessing the data in the individual moves.
67
68   class RootMoveList {
69
70   public:
71     RootMoveList(Position &pos, Move searchMoves[]);
72     Move get_move(int moveNum) const;
73     Value get_move_score(int moveNum) const;
74     void set_move_score(int moveNum, Value score);
75     void set_move_nodes(int moveNum, int64_t nodes);
76     void set_move_pv(int moveNum, const Move pv[]);
77     Move get_move_pv(int moveNum, int i) const;
78     int64_t get_move_cumulative_nodes(int moveNum);
79     int move_count() const;
80     Move scan_for_easy_move() const;
81     void sort();
82     void sort_multipv(int n);
83
84   private:
85     static int compare_root_moves(const RootMove &rm1, const RootMove &rm2);
86     static const int MaxRootMoves = 500;
87     RootMove moves[MaxRootMoves];
88     int count;
89   };
90
91
92   /// Constants and variables
93
94   // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
95   // nodes:
96   int LMRPVMoves = 15;
97   int LMRNonPVMoves = 4;
98
99   // Depth limit for use of dynamic threat detection:
100   Depth ThreatDepth = 5*OnePly;
101
102   // Depth limit for selective search:
103   Depth SelectiveDepth = 7*OnePly;
104
105   // Use internal iterative deepening?
106   const bool UseIIDAtPVNodes = true;
107   const bool UseIIDAtNonPVNodes = false;
108
109   // Internal iterative deepening margin.  At Non-PV moves, when
110   // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
111   // when the static evaluation is at most IIDMargin below beta.
112   const Value IIDMargin = Value(0x100);
113
114   // Use easy moves?
115   const bool UseEasyMove = true;
116
117   // Easy move margin.  An easy move candidate must be at least this much
118   // better than the second best move.
119   const Value EasyMoveMargin = Value(0x200);
120
121   // Problem margin.  If the score of the first move at iteration N+1 has
122   // dropped by more than this since iteration N, the boolean variable
123   // "Problem" is set to true, which will make the program spend some extra
124   // time looking for a better move.
125   const Value ProblemMargin = Value(0x28);
126
127   // No problem margin.  If the boolean "Problem" is true, and a new move
128   // is found at the root which is less than NoProblemMargin worse than the
129   // best move from the previous iteration, Problem is set back to false.
130   const Value NoProblemMargin = Value(0x14);
131
132   // Null move margin.  A null move search will not be done if the approximate
133   // evaluation of the position is more than NullMoveMargin below beta.
134   const Value NullMoveMargin = Value(0x300);
135
136   // Pruning criterions.  See the code and comments in ok_to_prune() to
137   // understand their precise meaning.
138   const bool PruneEscapeMoves = false;
139   const bool PruneDefendingMoves = false;
140   const bool PruneBlockingMoves = false;
141
142   // Use futility pruning?
143   bool UseQSearchFutilityPruning = true;
144   bool UseFutilityPruning = true;
145
146   // Margins for futility pruning in the quiescence search, at frontier
147   // nodes, and at pre-frontier nodes:
148   Value FutilityMargin0 = Value(0x80);
149   Value FutilityMargin1 = Value(0x100);
150   Value FutilityMargin2 = Value(0x300);
151
152   // Razoring
153   Depth RazorDepth = 4*OnePly;
154   Value RazorMargin = Value(0x300);
155
156   // Extensions.  Array index 0 is used at non-PV nodes, index 1 at PV nodes.
157   Depth CheckExtension[2] = {OnePly, OnePly};
158   Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
159   Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
160   Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
161   Depth PawnEndgameExtension[2] = {OnePly, OnePly};
162   Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
163
164   // Search depth at iteration 1:
165   const Depth InitialDepth = OnePly /*+ OnePly/2*/;
166
167   // Node counters
168   int NodesSincePoll;
169   int NodesBetweenPolls = 30000;
170
171   // Iteration counter:
172   int Iteration;
173
174   // Scores and number of times the best move changed for each iteration:
175   Value ValueByIteration[PLY_MAX_PLUS_2];
176   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
177
178   // MultiPV mode:
179   int MultiPV = 1;
180
181   // Time managment variables
182   int SearchStartTime;
183   int MaxNodes, MaxDepth;
184   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
185   Move BestRootMove, PonderMove, EasyMove;
186   int RootMoveNumber;
187   bool InfiniteSearch;
188   bool PonderSearch;
189   bool StopOnPonderhit;
190   bool AbortSearch;
191   bool Quit;
192   bool FailHigh;
193   bool Problem;
194   bool PonderingEnabled;
195   int ExactMaxTime;
196
197   // Show current line?
198   bool ShowCurrentLine = false;
199
200   // Log file
201   bool UseLogFile = false;
202   std::ofstream LogFile;
203
204   // MP related variables
205   Depth MinimumSplitDepth = 4*OnePly;
206   int MaxThreadsPerSplitPoint = 4;
207   Thread Threads[THREAD_MAX];
208   Lock MPLock;
209   bool AllThreadsShouldExit = false;
210   const int MaxActiveSplitPoints = 8;
211   SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
212   bool Idle = true;
213
214 #if !defined(_MSC_VER)
215   pthread_cond_t WaitCond;
216   pthread_mutex_t WaitLock;
217 #else
218   HANDLE SitIdleEvent[THREAD_MAX];
219 #endif
220
221
222   /// Functions
223
224   void id_loop(const Position &pos, Move searchMoves[]);
225   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
226   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
227                   Depth depth, int ply, int threadID);
228   Value search(Position &pos, SearchStack ss[], Value beta,
229                Depth depth, int ply, bool allowNullmove, int threadID);
230   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
231                 Depth depth, int ply, int threadID);
232   void sp_search(SplitPoint *sp, int threadID);
233   void sp_search_pv(SplitPoint *sp, int threadID);
234   void init_search_stack(SearchStack ss[]);
235   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
236   void update_pv(SearchStack ss[], int ply);
237   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
238   bool connected_moves(const Position &pos, Move m1, Move m2);
239   Depth extension(const Position &pos, Move m, bool pvNode, bool check,
240                   bool singleReply, bool mateThreat);
241   bool ok_to_do_nullmove(const Position &pos);
242   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
243
244   bool fail_high_ply_1();
245   int current_search_time();
246   int nps();
247   void poll();
248   void ponderhit();
249   void print_current_line(SearchStack ss[], int ply, int threadID);
250   void wait_for_stop_or_ponderhit();
251
252   void idle_loop(int threadID, SplitPoint *waitSp);
253   void init_split_point_stack();
254   void destroy_split_point_stack();
255   bool thread_should_stop(int threadID);
256   bool thread_is_available(int slave, int master);
257   bool idle_thread_exists(int master);
258   bool split(const Position &pos, SearchStack *ss, int ply,
259              Value *alpha, Value *beta, Value *bestValue, Depth depth,
260              int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
261              bool pvNode);
262   void wake_sleeping_threads();
263
264 #if !defined(_MSC_VER)
265   void *init_thread(void *threadID);
266 #else
267   DWORD WINAPI init_thread(LPVOID threadID);
268 #endif
269   
270 }
271
272
273 ////
274 //// Global variables
275 ////
276
277 // The main transposition table
278 TranspositionTable TT = TranspositionTable(TTDefaultSize);
279
280
281 // Number of active threads:
282 int ActiveThreads = 1;
283
284 // Locks.  In principle, there is no need for IOLock to be a global variable,
285 // but it could turn out to be useful for debugging.
286 Lock IOLock;
287
288 History H;  // Should be made local?
289
290
291 ////
292 //// Functions
293 ////
294
295 /// think() is the external interface to Glaurung's search, and is called when
296 /// the program receives the UCI 'go' command.  It initializes various
297 /// search-related global variables, and calls root_search()
298
299 void think(const Position &pos, bool infinite, bool ponder, int time,
300            int increment, int movesToGo, int maxDepth, int maxNodes,
301            int maxTime, Move searchMoves[]) {
302
303   // Look for a book move:
304   if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
305     Move bookMove;
306     if(get_option_value_string("Book File") != OpeningBook.file_name()) {
307       OpeningBook.close();
308       OpeningBook.open("book.bin");
309     }
310     bookMove = OpeningBook.get_move(pos);
311     if(bookMove != MOVE_NONE) {
312       std::cout << "bestmove " << bookMove << std::endl;
313       return;
314     }
315   }
316
317   // Initialize global search variables:
318   Idle = false;
319   SearchStartTime = get_system_time();
320   BestRootMove = MOVE_NONE;
321   PonderMove = MOVE_NONE;
322   EasyMove = MOVE_NONE;
323   for(int i = 0; i < THREAD_MAX; i++) {
324     Threads[i].nodes = 0ULL;
325     Threads[i].failHighPly1 = false;
326   }
327   NodesSincePoll = 0;
328   InfiniteSearch = infinite;
329   PonderSearch = ponder;
330   StopOnPonderhit = false;
331   AbortSearch = false;
332   Quit = false;
333   FailHigh = false;
334   Problem = false;
335   ExactMaxTime = maxTime;
336
337   // Read UCI option values:
338   TT.set_size(get_option_value_int("Hash"));
339   if(button_was_pressed("Clear Hash"))
340     TT.clear();
341   PonderingEnabled = get_option_value_int("Ponder");
342   MultiPV = get_option_value_int("MultiPV");
343
344   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
345   CheckExtension[0] =
346     Depth(get_option_value_int("Check Extension (non-PV nodes)"));
347   SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
348   SingleReplyExtension[0] =
349     Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
350   PawnPushTo7thExtension[1] =
351     Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
352   PawnPushTo7thExtension[0] =
353     Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
354   PassedPawnExtension[1] =
355     Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
356   PassedPawnExtension[0] = 
357     Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
358   PawnEndgameExtension[1] =
359     Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
360   PawnEndgameExtension[0] =
361     Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
362   MateThreatExtension[1] =
363     Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
364   MateThreatExtension[0] =
365     Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
366
367   LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
368   LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
369   ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
370   SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
371
372   Chess960 = get_option_value_bool("UCI_Chess960");
373   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
374   UseLogFile = get_option_value_bool("Use Search Log");
375   if(UseLogFile)
376     LogFile.open(get_option_value_string("Search Log Filename").c_str(),
377                  std::ios::out | std::ios::app);
378
379   UseQSearchFutilityPruning =
380     get_option_value_bool("Futility Pruning (Quiescence Search)");
381   UseFutilityPruning =
382     get_option_value_bool("Futility Pruning (Main Search)");
383
384   FutilityMargin0 =
385     value_from_centipawns(get_option_value_int("Futility Margin 0"));
386   FutilityMargin1 =
387     value_from_centipawns(get_option_value_int("Futility Margin 1"));
388   FutilityMargin2 =
389     value_from_centipawns(get_option_value_int("Futility Margin 2"));
390
391   RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
392   RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
393
394   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
395   MaxThreadsPerSplitPoint =
396     get_option_value_int("Maximum Number of Threads per Split Point");
397
398   read_weights(pos.side_to_move());
399   
400   int newActiveThreads = get_option_value_int("Threads");
401   if(newActiveThreads != ActiveThreads) {
402     ActiveThreads = newActiveThreads;
403     init_eval(ActiveThreads);
404   }
405
406   // Write information to search log file:
407   if(UseLogFile) {
408     LogFile << "Searching: " << pos.to_fen() << '\n';
409     LogFile << "infinite: " << infinite << " ponder: " << ponder
410             << " time: " << time << " increment: " << increment
411             << " moves to go: " << movesToGo << '\n';
412   }
413
414   // Wake up sleeping threads:
415   wake_sleeping_threads();
416
417   for(int i = 1; i < ActiveThreads; i++)
418     assert(thread_is_available(i, 0));
419
420   // Set thinking time:
421   if(!movesToGo) { // Sudden death time control
422     if(increment) {
423       MaxSearchTime = time / 30 + increment;
424       AbsoluteMaxSearchTime = Max(time / 4, increment - 100);
425     }
426     else { // Blitz game without increment
427       MaxSearchTime = time / 40;
428       AbsoluteMaxSearchTime = time / 8;
429     }
430   }
431   else { // (x moves) / (y minutes)
432     if(movesToGo == 1) {
433       MaxSearchTime = time / 2;
434       AbsoluteMaxSearchTime = Min(time / 2, time - 500);
435     }
436     else {
437       MaxSearchTime = time / Min(movesToGo, 20);
438       AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3);
439     }
440   }
441   if(PonderingEnabled) {
442     MaxSearchTime += MaxSearchTime / 4;
443     MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
444   }
445
446   // Fixed depth or fixed number of nodes?
447   MaxDepth = maxDepth;
448   if(MaxDepth)
449     InfiniteSearch = true; // HACK
450
451   MaxNodes = maxNodes;
452   if(MaxNodes) {
453     NodesBetweenPolls = Min(MaxNodes, 30000);
454     InfiniteSearch = true; // HACK
455   }
456   else
457     NodesBetweenPolls = 30000;
458
459   // We're ready to start thinking.  Call the iterative deepening loop
460   // function:
461   id_loop(pos, searchMoves);
462
463   if(UseLogFile)
464     LogFile.close();
465   
466   if(Quit) {
467     OpeningBook.close();
468     stop_threads();
469     quit_eval();
470     exit(0);
471   }
472
473   Idle = true;
474 }
475
476
477 /// init_threads() is called during startup.  It launches all helper threads,
478 /// and initializes the split point stack and the global locks and condition
479 /// objects.
480
481 void init_threads() {
482   volatile int i;
483 #if !defined(_MSC_VER)
484   pthread_t pthread[1];
485 #endif
486
487   for(i = 0; i < THREAD_MAX; i++)
488     Threads[i].activeSplitPoints = 0;
489
490   // Initialize global locks:
491   lock_init(&MPLock, NULL);
492   lock_init(&IOLock, NULL);
493
494   init_split_point_stack();
495   
496 #if !defined(_MSC_VER)
497   pthread_mutex_init(&WaitLock, NULL);
498   pthread_cond_init(&WaitCond, NULL);
499 #else
500   for(i = 0; i < THREAD_MAX; i++)
501     SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
502 #endif
503
504   // All threads except the main thread should be initialized to idle state:
505   for(i = 1; i < THREAD_MAX; i++) {
506     Threads[i].stop = false;
507     Threads[i].workIsWaiting = false;
508     Threads[i].idle = true;
509     Threads[i].running = false;
510   }
511
512   // Launch the helper threads:
513   for(i = 1; i < THREAD_MAX; i++) {
514 #if !defined(_MSC_VER)
515     pthread_create(pthread, NULL, init_thread, (void*)(&i));
516 #else
517     {
518       DWORD iID[1];
519       CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
520     }
521 #endif
522
523     // Wait until the thread has finished launching:
524     while(!Threads[i].running);
525   }
526 }
527
528
529 /// stop_threads() is called when the program exits.  It makes all the
530 /// helper threads exit cleanly.
531
532 void stop_threads() {
533   ActiveThreads = THREAD_MAX;  // HACK
534   Idle = false;  // HACK
535   wake_sleeping_threads();
536   AllThreadsShouldExit = true;
537   for(int i = 1; i < THREAD_MAX; i++) {
538     Threads[i].stop = true;
539     while(Threads[i].running);
540   }
541   destroy_split_point_stack();
542 }
543
544
545 /// nodes_searched() returns the total number of nodes searched so far in
546 /// the current search.
547
548 int64_t nodes_searched() {
549   int64_t result = 0ULL;
550   for(int i = 0; i < ActiveThreads; i++)
551     result += Threads[i].nodes;
552   return result;
553 }
554
555
556 namespace {
557
558   // id_loop() is the main iterative deepening loop.  It calls root_search
559   // repeatedly with increasing depth until the allocated thinking time has
560   // been consumed, the user stops the search, or the maximum search depth is
561   // reached.
562
563   void id_loop(const Position &pos, Move searchMoves[]) {
564     Position p(pos);
565     RootMoveList rml(p, searchMoves);
566     SearchStack ss[PLY_MAX_PLUS_2];
567
568     // Initialize
569     TT.new_search();
570     H.clear();
571     init_search_stack(ss);
572
573     ValueByIteration[0] = Value(0);
574     ValueByIteration[1] = rml.get_move_score(0);
575     Iteration = 1;
576
577     EasyMove = rml.scan_for_easy_move();
578
579     // Iterative deepening loop
580     while(!AbortSearch && Iteration < PLY_MAX) {
581
582       // Initialize iteration
583       rml.sort();
584       Iteration++;
585       BestMoveChangesByIteration[Iteration] = 0;
586       if(Iteration <= 5)
587         ExtraSearchTime = 0;
588
589       std::cout << "info depth " << Iteration << std::endl;
590
591       // Search to the current depth
592       ValueByIteration[Iteration] = root_search(p, ss, rml);
593
594       // Erase the easy move if it differs from the new best move
595       if(ss[0].pv[0] != EasyMove)
596         EasyMove = MOVE_NONE;
597
598       Problem = false;
599
600       if(!InfiniteSearch) {
601         // Time to stop?
602         bool stopSearch = false;
603
604         // Stop search early if there is only a single legal move:
605         if(Iteration >= 6 && rml.move_count() == 1)
606           stopSearch = true;
607
608         // Stop search early when the last two iterations returned a mate
609         // score:
610         if(Iteration >= 6
611            && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
612            && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
613           stopSearch = true;
614
615         // Stop search early if one move seems to be much better than the
616         // rest:
617         int64_t nodes = nodes_searched();
618         if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
619            ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
620              current_search_time() > MaxSearchTime / 16) ||
621             (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
622              current_search_time() > MaxSearchTime / 32)))
623           stopSearch = true;
624
625         // Add some extra time if the best move has changed during the last
626         // two iterations:
627         if(Iteration > 5 && Iteration <= 50)
628           ExtraSearchTime =
629             BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
630             BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
631
632         // Stop search if most of MaxSearchTime is consumed at the end of the
633         // iteration.  We probably don't have enough time to search the first
634         // move at the next iteration anyway.
635         if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
636           stopSearch = true;
637
638         if(stopSearch) {
639           if(!PonderSearch)
640             break;
641           else
642             StopOnPonderhit = true;
643         }
644       }
645
646       // Write PV to transposition table, in case the relevant entries have 
647       // been overwritten during the search:
648       TT.insert_pv(p, ss[0].pv);
649
650       if(MaxDepth && Iteration >= MaxDepth)
651         break;
652     }
653
654     rml.sort();
655
656     // If we are pondering, we shouldn't print the best move before we
657     // are told to do so
658     if(PonderSearch)
659       wait_for_stop_or_ponderhit();
660     else
661       // Print final search statistics
662       std::cout << "info nodes " << nodes_searched() << " nps " << nps()
663                 << " time " << current_search_time()
664                 << " hashfull " << TT.full() << std::endl;
665
666     // Print the best move and the ponder move to the standard output:
667     std::cout << "bestmove " << ss[0].pv[0];
668     if(ss[0].pv[1] != MOVE_NONE)
669       std::cout << " ponder " << ss[0].pv[1];
670     std::cout << std::endl;
671
672     if(UseLogFile) {
673       UndoInfo u;
674       LogFile << "Nodes: " << nodes_searched() << '\n';
675       LogFile << "Nodes/second: " << nps() << '\n';
676       LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
677       p.do_move(ss[0].pv[0], u);
678       LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
679       LogFile << std::endl;
680     }
681   }
682
683
684   // root_search() is the function which searches the root node.  It is
685   // similar to search_pv except that it uses a different move ordering
686   // scheme (perhaps we should try to use this at internal PV nodes, too?)
687   // and prints some information to the standard output.
688
689   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
690     Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
691     Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
692
693     // Loop through all the moves in the root move list:
694     for(int i = 0; i <  rml.move_count() && !AbortSearch; i++) {
695       int64_t nodes;
696       Move move;
697       UndoInfo u;
698       Depth ext, newDepth;
699
700       RootMoveNumber = i + 1;
701       FailHigh = false;
702
703       // Remember the node count before the move is searched.  The node counts
704       // are used to sort the root moves at the next iteration.
705       nodes = nodes_searched();
706
707       // Pick the next root move, and print the move and the move number to
708       // the standard output:
709       move = ss[0].currentMove = rml.get_move(i);
710       if(current_search_time() >= 1000)
711         std::cout << "info currmove " << move
712                   << " currmovenumber " << i + 1 << std::endl;
713       
714       // Decide search depth for this move:
715       ext = extension(pos, move, true, pos.move_is_check(move), false, false);
716       newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
717
718       // Make the move, and search it.
719       pos.do_move(move, u, dcCandidates);
720
721       if(i < MultiPV) {
722         value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
723         // If the value has dropped a lot compared to the last iteration,
724         // set the boolean variable Problem to true.  This variable is used
725         // for time managment:  When Problem is true, we try to complete the
726         // current iteration before playing a move.
727         Problem = (Iteration >= 2 &&
728                    value <= ValueByIteration[Iteration-1] - ProblemMargin);
729         if(Problem && StopOnPonderhit)
730           StopOnPonderhit = false;
731       }
732       else {
733         value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
734         if(value > alpha) {
735           // Fail high!  Set the boolean variable FailHigh to true, and 
736           // re-search the move with a big window.  The variable FailHigh is
737           // used for time managment:  We try to avoid aborting the search
738           // prematurely during a fail high research.
739           FailHigh = true;
740           value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
741         }
742       }
743
744       pos.undo_move(move, u);
745
746       // Finished searching the move.  If AbortSearch is true, the search
747       // was aborted because the user interrupted the search or because we
748       // ran out of time.  In this case, the return value of the search cannot
749       // be trusted, and we break out of the loop without updating the best
750       // move and/or PV:
751       if(AbortSearch)
752         break;
753
754       // Remember the node count for this move.  The node counts are used to 
755       // sort the root moves at the next iteration.
756       rml.set_move_nodes(i, nodes_searched() - nodes);
757
758       assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
759
760       if(value <= alpha && i >= MultiPV)
761         rml.set_move_score(i, -VALUE_INFINITE);
762       else {
763         // New best move!
764
765         // Update PV:
766         rml.set_move_score(i, value);
767         update_pv(ss, 0);
768         rml.set_move_pv(i, ss[0].pv);
769
770         if(MultiPV == 1) {
771           // We record how often the best move has been changed in each 
772           // iteration.  This information is used for time managment:  When
773           // the best move changes frequently, we allocate some more time.
774           if(i > 0)
775             BestMoveChangesByIteration[Iteration]++;
776
777           // Print search information to the standard output:
778           std::cout << "info depth " << Iteration
779                     << " score " << value_to_string(value)
780                     << " time " << current_search_time()
781                     << " nodes " << nodes_searched()
782                     << " nps " << nps()
783                     << " pv ";
784           for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
785             std::cout << ss[0].pv[j] << " ";
786           std::cout << std::endl;
787
788           if(UseLogFile)
789             LogFile << pretty_pv(pos, current_search_time(), Iteration,
790                                  nodes_searched(), value, ss[0].pv)
791                     << std::endl;
792
793           alpha = value;
794
795           // Reset the global variable Problem to false if the value isn't too
796           // far below the final value from the last iteration.
797           if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
798             Problem = false;
799         }
800         else { // MultiPV > 1
801           rml.sort_multipv(i);
802           for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
803             int k;
804             std::cout << "info multipv " << j + 1
805                       << " score " << value_to_string(rml.get_move_score(j))
806                       << " depth " << ((j <= i)? Iteration : Iteration - 1)
807                       << " time " << current_search_time()
808                       << " nodes " << nodes_searched()
809                       << " nps " << nps()
810                       << " pv ";
811             for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
812               std::cout << rml.get_move_pv(j, k) << " ";
813             std::cout << std::endl;
814           }
815           alpha = rml.get_move_score(Min(i, MultiPV-1));
816         }
817       }
818     }
819     return alpha;
820   }
821
822
823   // search_pv() is the main search function for PV nodes.
824
825   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
826                   Depth depth, int ply, int threadID) {
827     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
828     assert(beta > alpha && beta <= VALUE_INFINITE);
829     assert(ply >= 0 && ply < PLY_MAX);
830     assert(threadID >= 0 && threadID < ActiveThreads);
831
832     EvalInfo ei;
833
834     // Initialize, and make an early exit in case of an aborted search,
835     // an instant draw, maximum ply reached, etc.
836     Value oldAlpha = alpha;
837
838     if(AbortSearch || thread_should_stop(threadID))
839       return Value(0);
840
841     if(depth < OnePly)
842       return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
843
844     init_node(pos, ss, ply, threadID);
845
846     if(pos.is_draw())
847       return VALUE_DRAW;
848
849     if(ply >= PLY_MAX - 1)
850       return evaluate(pos, ei, threadID);
851
852     // Mate distance pruning
853     alpha = Max(value_mated_in(ply), alpha);
854     beta = Min(value_mate_in(ply+1), beta);
855     if(alpha >= beta)
856       return alpha;
857
858     // Transposition table lookup.  At PV nodes, we don't use the TT for
859     // pruning, but only for move ordering.  
860     Value ttValue;
861     Depth ttDepth;
862     Move ttMove = MOVE_NONE;
863     ValueType ttValueType;
864
865     TT.retrieve(pos, &ttValue, &ttDepth, &ttMove, &ttValueType);
866
867     // Internal iterative deepening.
868     if(UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly) {
869       search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
870       ttMove = ss[ply].pv[ply];
871     }
872
873     // Initialize a MovePicker object for the current position, and prepare
874     // to search all moves:
875     MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
876                                ss[ply].killer1, ss[ply].killer2, depth);
877     Move move, movesSearched[256];
878     int moveCount = 0;
879     Value value, bestValue = -VALUE_INFINITE;
880     Bitboard dcCandidates = mp.discovered_check_candidates();
881     bool mateThreat =
882       MateThreatExtension[1] > Depth(0)
883       && pos.has_mate_threat(opposite_color(pos.side_to_move()));
884
885     // Loop through all legal moves until no moves remain or a beta cutoff
886     // occurs.
887     while(alpha < beta && !thread_should_stop(threadID)
888           && (move = mp.get_next_move()) != MOVE_NONE) {
889       UndoInfo u;
890       Depth ext, newDepth;
891       bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
892       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
893       bool moveIsCapture = pos.move_is_capture(move);
894       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
895       
896       assert(move_is_ok(move));
897       movesSearched[moveCount++] = ss[ply].currentMove = move;
898
899       ss[ply].currentMoveCaptureValue = move_is_ep(move)?
900         PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
901
902       // Decide the new search depth.
903       ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
904       newDepth = depth - OnePly + ext;
905
906       // Make and search the move.
907       pos.do_move(move, u, dcCandidates);
908       
909       if(moveCount == 1) 
910         value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
911       else {
912         if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRPVMoves
913            && !moveIsCapture && !move_promotion(move)
914            && !moveIsPassedPawnPush && !move_is_castle(move)
915            && move != ss[ply].killer1 && move != ss[ply].killer2) {
916           ss[ply].reduction = OnePly;
917           value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, 
918                           threadID);
919         }
920         else value = alpha + 1;
921         if(value > alpha) {
922           ss[ply].reduction = Depth(0);
923           value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
924           if(value > alpha && value < beta) {
925             if(ply == 1 && RootMoveNumber == 1)
926               // When the search fails high at ply 1 while searching the first
927               // move at the root, set the flag failHighPly1.  This is used for
928               // time managment:  We don't want to stop the search early in
929               // such cases, because resolving the fail high at ply 1 could
930               // result in a big drop in score at the root.
931               Threads[threadID].failHighPly1 = true;
932             value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, 
933                                threadID);
934             Threads[threadID].failHighPly1 = false;
935           }
936         }
937       }
938       pos.undo_move(move, u);
939
940       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
941       
942       // New best move?
943       if(value > bestValue) {
944         bestValue = value;
945         if(value > alpha) {
946           alpha = value;
947           update_pv(ss, ply);
948           if(value == value_mate_in(ply + 1))
949             ss[ply].mateKiller = move;
950         }
951         // If we are at ply 1, and we are searching the first root move at
952         // ply 0, set the 'Problem' variable if the score has dropped a lot
953         // (from the computer's point of view) since the previous iteration:
954         if(Iteration >= 2 &&
955            -value <= ValueByIteration[Iteration-1] - ProblemMargin)
956           Problem = true;
957       }
958
959       // Split?
960       if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth
961          && Iteration <= 99 && idle_thread_exists(threadID)
962          && !AbortSearch && !thread_should_stop(threadID)
963          && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
964                   &moveCount, &mp, dcCandidates, threadID, true))
965         break;
966     }
967
968     // All legal moves have been searched.  A special case: If there were
969     // no legal moves, it must be mate or stalemate:
970     if(moveCount == 0) {
971       if(pos.is_check())
972         return value_mated_in(ply);
973       else
974         return VALUE_DRAW;
975     }
976
977     // If the search is not aborted, update the transposition table, 
978     // history counters, and killer moves.  This code is somewhat messy,
979     // and definitely needs to be cleaned up.  FIXME
980     if(!AbortSearch && !thread_should_stop(threadID)) {
981       if(bestValue <= oldAlpha)
982         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE,
983                  VALUE_TYPE_UPPER);
984       else if(bestValue >= beta) {
985         Move m = ss[ply].pv[ply];
986         if(pos.square_is_empty(move_to(m)) && !move_promotion(m) &&
987            !move_is_ep(m)) {
988           for(int i = 0; i < moveCount - 1; i++)
989             if(pos.square_is_empty(move_to(movesSearched[i]))
990                && !move_promotion(movesSearched[i])
991                && !move_is_ep(movesSearched[i]))
992               H.failure(pos.piece_on(move_from(movesSearched[i])),
993                         movesSearched[i]);
994
995           H.success(pos.piece_on(move_from(m)), m, depth);
996           
997           if(m != ss[ply].killer1) {
998             ss[ply].killer2 = ss[ply].killer1;
999             ss[ply].killer1 = m;
1000           }
1001         }
1002         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1003       }
1004       else
1005         TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply],
1006                  VALUE_TYPE_EXACT);
1007     }
1008
1009     return bestValue;
1010   }
1011   
1012
1013   // search() is the search function for zero-width nodes.
1014
1015   Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1016                int ply, bool allowNullmove, int threadID) {
1017     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1018     assert(ply >= 0 && ply < PLY_MAX);
1019     assert(threadID >= 0 && threadID < ActiveThreads);
1020
1021     EvalInfo ei;
1022
1023     // Initialize, and make an early exit in case of an aborted search,
1024     // an instant draw, maximum ply reached, etc.
1025     if(AbortSearch || thread_should_stop(threadID))
1026       return Value(0);
1027
1028     if(depth < OnePly)
1029       return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1030
1031     init_node(pos, ss, ply, threadID);
1032
1033     if(pos.is_draw())
1034       return VALUE_DRAW;
1035
1036     if(ply >= PLY_MAX - 1)
1037       return evaluate(pos, ei, threadID);
1038
1039     // Mate distance pruning
1040     if(value_mated_in(ply) >= beta)
1041       return beta;
1042     if(value_mate_in(ply+1) < beta)
1043       return beta-1;
1044
1045     // Transposition table lookup
1046     bool ttFound;
1047     Value ttValue;
1048     Depth ttDepth;
1049     Move ttMove = MOVE_NONE;
1050     ValueType ttValueType;
1051
1052     ttFound = TT.retrieve(pos, &ttValue, &ttDepth, &ttMove, &ttValueType);
1053     if(ttFound) {
1054       ttValue = value_from_tt(ttValue, ply);
1055       if(ttDepth >= depth
1056          || ttValue >= Max(value_mate_in(100), beta)
1057          || ttValue < Min(value_mated_in(100), beta)) {
1058         if((is_lower_bound(ttValueType) && ttValue >= beta) ||
1059            (is_upper_bound(ttValueType) && ttValue < beta)) {
1060           ss[ply].currentMove = ttMove;
1061           return ttValue;
1062         }
1063       }
1064     }
1065
1066     Value approximateEval = quick_evaluate(pos);
1067     bool mateThreat = false;
1068
1069     // Null move search
1070     if(!pos.is_check() && allowNullmove && ok_to_do_nullmove(pos)
1071        && approximateEval >= beta - NullMoveMargin) {
1072       UndoInfo u;
1073       Value nullValue;
1074
1075       ss[ply].currentMove = MOVE_NULL;
1076       pos.do_null_move(u);
1077       nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false,
1078                           threadID);
1079       pos.undo_null_move(u);
1080
1081       if(nullValue >= beta) {
1082         if(depth >= 6 * OnePly) { // Do zugzwang verification search
1083           Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1084           if(v >= beta)
1085             return beta;
1086         }
1087         else
1088           return beta;
1089       }
1090       else {
1091         // The null move failed low, which means that we may be faced with
1092         // some kind of threat.  If the previous move was reduced, check if
1093         // the move that refuted the null move was somehow connected to the
1094         // move which was reduced.  If a connection is found, return a fail
1095         // low score (which will cause the reduced move to fail high in the
1096         // parent node, which will trigger a re-search with full depth).
1097         if(nullValue == value_mated_in(ply+2))
1098           mateThreat = true;
1099         ss[ply].threatMove = ss[ply+1].currentMove;
1100         if(depth < ThreatDepth && ss[ply-1].reduction &&
1101            connected_moves(pos, ss[ply-1].currentMove, ss[ply].threatMove))
1102           return beta - 1;
1103       }
1104     }
1105     // Razoring:
1106     else if(depth < RazorDepth && approximateEval < beta - RazorMargin &&
1107             evaluate(pos, ei, threadID) < beta - RazorMargin) {
1108       Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1109       if(v < beta)
1110         return v;
1111     }
1112
1113     // Internal iterative deepening
1114     if(UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1115        evaluate(pos, ei, threadID) >= beta - IIDMargin) {
1116       search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1117       ttMove = ss[ply].pv[ply];
1118     }
1119
1120     // Initialize a MovePicker object for the current position, and prepare
1121     // to search all moves:
1122     MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1123                                ss[ply].killer1, ss[ply].killer2, depth);
1124     Move move, movesSearched[256];
1125     int moveCount = 0;
1126     Value value, bestValue = -VALUE_INFINITE, futilityValue = VALUE_NONE;
1127     Bitboard dcCandidates = mp.discovered_check_candidates();
1128     bool isCheck = pos.is_check();
1129     bool useFutilityPruning =
1130       UseFutilityPruning && depth < SelectiveDepth && !isCheck;
1131
1132     // Loop through all legal moves until no moves remain or a beta cutoff
1133     // occurs.
1134     while(bestValue < beta && !thread_should_stop(threadID)
1135           && (move = mp.get_next_move()) != MOVE_NONE) {
1136       UndoInfo u;
1137       Depth ext, newDepth;
1138       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1139       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1140       bool moveIsCapture = pos.move_is_capture(move);
1141       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1142
1143       assert(move_is_ok(move));
1144       movesSearched[moveCount++] = ss[ply].currentMove = move;
1145
1146       // Decide the new search depth.
1147       ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1148       newDepth = depth - OnePly + ext;
1149
1150       // Futility pruning
1151       if(useFutilityPruning && ext == Depth(0) && !moveIsCapture &&
1152          !moveIsPassedPawnPush && !move_promotion(move)) {
1153         
1154         if(moveCount >= 2 + int(depth)
1155            && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1156           continue;
1157
1158         if(depth < 3 * OnePly && approximateEval < beta) {
1159           if(futilityValue == VALUE_NONE)
1160             futilityValue = evaluate(pos, ei, threadID)
1161               + ((depth < 2 * OnePly)? FutilityMargin1 : FutilityMargin2);
1162           if(futilityValue < beta) {
1163             if(futilityValue > bestValue)
1164               bestValue = futilityValue;
1165             continue;
1166           }
1167         }
1168       }
1169
1170       // Make and search the move.
1171       pos.do_move(move, u, dcCandidates);
1172       
1173       if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRNonPVMoves
1174          && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1175          && !move_is_castle(move)
1176          && move != ss[ply].killer1 && move != ss[ply].killer2) {
1177         ss[ply].reduction = OnePly;
1178         value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true,
1179                         threadID);
1180       }
1181       else
1182         value = beta;
1183       if(value >= beta) {
1184         ss[ply].reduction = Depth(0);
1185         value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1186       }
1187       pos.undo_move(move, u);
1188
1189       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1190       
1191       // New best move?
1192       if(value > bestValue) {
1193         bestValue = value;
1194         if(value >= beta)
1195           update_pv(ss, ply);
1196         if(value == value_mate_in(ply + 1))
1197           ss[ply].mateKiller = move;
1198       }
1199
1200       // Split?
1201       if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth
1202          && Iteration <= 99 && idle_thread_exists(threadID)
1203          && !AbortSearch && !thread_should_stop(threadID)
1204          && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1205                   &mp, dcCandidates, threadID, false))
1206         break;
1207     }
1208
1209     // All legal moves have been searched.  A special case: If there were
1210     // no legal moves, it must be mate or stalemate:
1211     if(moveCount == 0) {
1212       if(pos.is_check())
1213         return value_mated_in(ply);
1214       else
1215         return VALUE_DRAW;
1216     }
1217
1218     // If the search is not aborted, update the transposition table,
1219     // history counters, and killer moves.  This code is somewhat messy,
1220     // and definitely needs to be cleaned up.  FIXME
1221     if(!AbortSearch && !thread_should_stop(threadID)) {
1222       if(bestValue < beta)
1223         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE,
1224                  VALUE_TYPE_UPPER);
1225       else {
1226         Move m = ss[ply].pv[ply];
1227                                                        
1228         if(pos.square_is_empty(move_to(m)) && !move_promotion(m) &&
1229            !move_is_ep(m)) {
1230           for(int i = 0; i < moveCount - 1; i++)
1231             if(pos.square_is_empty(move_to(movesSearched[i]))
1232                && !move_promotion(movesSearched[i])
1233                && !move_is_ep(movesSearched[i]))
1234               H.failure(pos.piece_on(move_from(movesSearched[i])),
1235                         movesSearched[i]);
1236           H.success(pos.piece_on(move_from(m)), m, depth);
1237           
1238           if(m != ss[ply].killer1) {
1239             ss[ply].killer2 = ss[ply].killer1;
1240             ss[ply].killer1 = m;
1241           }
1242         }
1243         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1244       }
1245     }
1246
1247     return bestValue;
1248   }
1249   
1250
1251   // qsearch() is the quiescence search function, which is called by the main
1252   // search function when the remaining depth is zero (or, to be more precise,
1253   // less than OnePly).
1254
1255   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1256                 Depth depth, int ply, int threadID) {
1257     Value staticValue, bestValue, value;
1258     EvalInfo ei;
1259
1260     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1261     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1262     assert(depth <= 0);
1263     assert(ply >= 0 && ply < PLY_MAX);
1264     assert(threadID >= 0 && threadID < ActiveThreads);
1265
1266     // Initialize, and make an early exit in case of an aborted search, 
1267     // an instant draw, maximum ply reached, etc.
1268     if(AbortSearch || thread_should_stop(threadID))
1269       return Value(0);
1270
1271     init_node(pos, ss, ply, threadID);
1272
1273     if(pos.is_draw())
1274       return VALUE_DRAW;
1275
1276     // Evaluate the position statically:
1277     staticValue = evaluate(pos, ei, threadID);
1278
1279     if(ply == PLY_MAX - 1) return staticValue;
1280
1281     // Initialize "stand pat score", and return it immediately if it is
1282     // at least beta.
1283     if(pos.is_check())
1284       bestValue = -VALUE_INFINITE;
1285     else {
1286       bestValue = staticValue;
1287       if(bestValue >= beta)
1288         return bestValue;
1289       if(bestValue > alpha)
1290         alpha = bestValue;
1291     }
1292
1293     // Initialize a MovePicker object for the current position, and prepare
1294     // to search the moves.  Because the depth is <= 0 here, only captures,
1295     // queen promotions and checks (only if depth == 0) will be generated.
1296     MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1297                                MOVE_NONE, depth);
1298     Move move;
1299     int moveCount = 0;
1300     Bitboard dcCandidates = mp.discovered_check_candidates();
1301     bool isCheck = pos.is_check();
1302
1303     // Loop through the moves until no moves remain or a beta cutoff 
1304     // occurs.
1305     while(alpha < beta && ((move = mp.get_next_move()) != MOVE_NONE)) {
1306       UndoInfo u;
1307       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1308       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1309
1310       assert(move_is_ok(move));
1311
1312       moveCount++;
1313       ss[ply].currentMove = move;
1314
1315       // Futility pruning
1316       if(UseQSearchFutilityPruning && !isCheck && !moveIsCheck && 
1317          !move_promotion(move) && !moveIsPassedPawnPush && 
1318          beta - alpha == 1 &&
1319          pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame) {
1320         Value futilityValue =
1321           staticValue 
1322           + Max(pos.midgame_value_of_piece_on(move_to(move)),
1323                 pos.endgame_value_of_piece_on(move_to(move)))
1324           + FutilityMargin0
1325           + ei.futilityMargin;
1326         if(futilityValue < alpha) {
1327           if(futilityValue > bestValue) 
1328             bestValue = futilityValue;
1329           continue;
1330         }
1331       }
1332
1333       // Don't search captures and checks with negative SEE values.
1334       if(!isCheck && !move_promotion(move) &&
1335          pos.midgame_value_of_piece_on(move_from(move)) >
1336          pos.midgame_value_of_piece_on(move_to(move)) &&
1337          pos.see(move) < 0)
1338         continue;
1339
1340       // Make and search the move.
1341       pos.do_move(move, u, dcCandidates);
1342       value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1343       pos.undo_move(move, u);
1344
1345       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1346
1347       // New best move?
1348       if(value > bestValue) {
1349         bestValue = value;
1350         if(value > alpha) {
1351           alpha = value;
1352           update_pv(ss, ply);
1353         }
1354       }
1355     }
1356
1357     // All legal moves have been searched.  A special case: If we're in check
1358     // and no legal moves were found, it is checkmate: 
1359     if(pos.is_check() && moveCount == 0) // Mate!
1360       return value_mated_in(ply);
1361
1362     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1363
1364     return bestValue;
1365   }
1366
1367
1368   // sp_search() is used to search from a split point.  This function is called
1369   // by each thread working at the split point.  It is similar to the normal
1370   // search() function, but simpler.  Because we have already probed the hash
1371   // table, done a null move search, and searched the first move before
1372   // splitting, we don't have to repeat all this work in sp_search().  We
1373   // also don't need to store anything to the hash table here:  This is taken
1374   // care of after we return from the split point.
1375   
1376   void sp_search(SplitPoint *sp, int threadID) {
1377     assert(threadID >= 0 && threadID < ActiveThreads);
1378     assert(ActiveThreads > 1);
1379     
1380     Position pos = Position(sp->pos);
1381     SearchStack *ss = sp->sstack[threadID];
1382     Value value;
1383     Move move;
1384     int moveCount = sp->moves;
1385     bool isCheck = pos.is_check();
1386     bool useFutilityPruning =
1387       UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck;
1388
1389     while(sp->bestValue < sp->beta && !thread_should_stop(threadID)
1390           && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1391       UndoInfo u;
1392       Depth ext, newDepth;
1393       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1394       bool moveIsCapture = pos.move_is_capture(move);
1395       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1396
1397       assert(move_is_ok(move));
1398
1399       lock_grab(&(sp->lock));
1400       sp->moves++;
1401       moveCount = sp->moves;
1402       lock_release(&(sp->lock));
1403
1404       ss[sp->ply].currentMove = move;
1405
1406       // Decide the new search depth.
1407       ext = extension(pos, move, false, moveIsCheck, false, false);
1408       newDepth = sp->depth - OnePly + ext;
1409
1410       // Prune?
1411       if(useFutilityPruning && ext == Depth(0) && !moveIsCapture
1412          && !moveIsPassedPawnPush && !move_promotion(move)
1413          && moveCount >= 2 + int(sp->depth)
1414          && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1415         continue;
1416
1417       // Make and search the move.
1418       pos.do_move(move, u, sp->dcCandidates);
1419       if(ext == Depth(0) && moveCount >= LMRNonPVMoves
1420          && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1421          && !move_is_castle(move)
1422          && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1423         ss[sp->ply].reduction = OnePly;
1424         value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1,
1425                         true, threadID);
1426       }
1427       else
1428         value = sp->beta;
1429       if(value >= sp->beta) {
1430         ss[sp->ply].reduction = Depth(0);
1431         value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true,
1432                         threadID);
1433       }
1434       pos.undo_move(move, u);
1435
1436       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1437
1438       if(thread_should_stop(threadID))
1439         break;
1440       
1441       // New best move?
1442       lock_grab(&(sp->lock));
1443       if(value > sp->bestValue && !thread_should_stop(threadID)) {
1444         sp->bestValue = value;
1445         if(sp->bestValue >= sp->beta) {
1446           sp_update_pv(sp->parentSstack, ss, sp->ply);
1447           for(int i = 0; i < ActiveThreads; i++)
1448             if(i != threadID && (i == sp->master || sp->slaves[i]))
1449               Threads[i].stop = true;
1450           sp->finished = true;
1451         }
1452       }
1453       lock_release(&(sp->lock));
1454     }
1455
1456     lock_grab(&(sp->lock));
1457
1458     // If this is the master thread and we have been asked to stop because of
1459     // a beta cutoff higher up in the tree, stop all slave threads:
1460     if(sp->master == threadID && thread_should_stop(threadID))
1461       for(int i = 0; i < ActiveThreads; i++)
1462         if(sp->slaves[i])
1463           Threads[i].stop = true;
1464
1465     sp->cpus--;
1466     sp->slaves[threadID] = 0;
1467
1468     lock_release(&(sp->lock));
1469   }
1470
1471
1472   // sp_search_pv() is used to search from a PV split point.  This function
1473   // is called by each thread working at the split point.  It is similar to
1474   // the normal search_pv() function, but simpler.  Because we have already
1475   // probed the hash table and searched the first move before splitting, we
1476   // don't have to repeat all this work in sp_search_pv().  We also don't
1477   // need to store anything to the hash table here:  This is taken care of
1478   // after we return from the split point.
1479   
1480   void sp_search_pv(SplitPoint *sp, int threadID) {
1481     assert(threadID >= 0 && threadID < ActiveThreads);
1482     assert(ActiveThreads > 1);
1483     
1484     Position pos = Position(sp->pos);
1485     SearchStack *ss = sp->sstack[threadID];
1486     Value value;
1487     Move move;
1488     int moveCount = sp->moves;
1489
1490     while(sp->alpha < sp->beta && !thread_should_stop(threadID)
1491           && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1492       UndoInfo u;
1493       Depth ext, newDepth;
1494       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1495       bool moveIsCapture = pos.move_is_capture(move);
1496       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1497
1498       assert(move_is_ok(move));
1499
1500       ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1501         PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1502
1503       lock_grab(&(sp->lock));
1504       sp->moves++;
1505       moveCount = sp->moves;
1506       lock_release(&(sp->lock));
1507
1508       ss[sp->ply].currentMove = move;
1509       
1510       // Decide the new search depth.
1511       ext = extension(pos, move, true, moveIsCheck, false, false);
1512       newDepth = sp->depth - OnePly + ext;
1513
1514       // Make and search the move.
1515       pos.do_move(move, u, sp->dcCandidates);
1516       if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
1517          && !move_promotion(move) && !moveIsPassedPawnPush
1518          && !move_is_castle(move)
1519          && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1520         ss[sp->ply].reduction = OnePly;
1521         value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
1522                         true, threadID);
1523       }
1524       else
1525         value = sp->alpha + 1;
1526       if(value > sp->alpha) {
1527         ss[sp->ply].reduction = Depth(0);
1528         value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
1529                         threadID);
1530         if(value > sp->alpha && value < sp->beta) {
1531           if(sp->ply == 1 && RootMoveNumber == 1)
1532             // When the search fails high at ply 1 while searching the first
1533             // move at the root, set the flag failHighPly1.  This is used for
1534             // time managment:  We don't want to stop the search early in
1535             // such cases, because resolving the fail high at ply 1 could
1536             // result in a big drop in score at the root.
1537             Threads[threadID].failHighPly1 = true;
1538           value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
1539                              sp->ply+1, threadID);
1540           Threads[threadID].failHighPly1 = false;
1541         }
1542       }
1543       pos.undo_move(move, u);
1544
1545       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1546
1547       if(thread_should_stop(threadID))
1548         break;
1549       
1550       // New best move?
1551       lock_grab(&(sp->lock));
1552       if(value > sp->bestValue && !thread_should_stop(threadID)) {
1553         sp->bestValue = value;
1554         if(value > sp->alpha) {
1555           sp->alpha = value;
1556           sp_update_pv(sp->parentSstack, ss, sp->ply);
1557           if(value == value_mate_in(sp->ply + 1))
1558             ss[sp->ply].mateKiller = move;
1559           if(value >= sp->beta) {
1560             for(int i = 0; i < ActiveThreads; i++)
1561               if(i != threadID && (i == sp->master || sp->slaves[i]))
1562                 Threads[i].stop = true;
1563             sp->finished = true;
1564           }
1565         }
1566         // If we are at ply 1, and we are searching the first root move at
1567         // ply 0, set the 'Problem' variable if the score has dropped a lot
1568         // (from the computer's point of view) since the previous iteration:
1569         if(Iteration >= 2 &&
1570            -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1571           Problem = true;
1572       }
1573       lock_release(&(sp->lock));
1574     }
1575
1576     lock_grab(&(sp->lock));
1577
1578     // If this is the master thread and we have been asked to stop because of
1579     // a beta cutoff higher up in the tree, stop all slave threads:
1580     if(sp->master == threadID && thread_should_stop(threadID))
1581       for(int i = 0; i < ActiveThreads; i++)
1582         if(sp->slaves[i])
1583           Threads[i].stop = true;
1584
1585     sp->cpus--;
1586     sp->slaves[threadID] = 0;
1587
1588     lock_release(&(sp->lock));
1589   }  
1590
1591
1592   /// The RootMove class
1593
1594   // Constructor
1595
1596   RootMove::RootMove() {
1597     nodes = cumulativeNodes = 0ULL;
1598   }
1599   
1600
1601   /// The RootMoveList class
1602
1603   // Constructor
1604
1605   RootMoveList::RootMoveList(Position &pos, Move searchMoves[]) {
1606     MoveStack mlist[MaxRootMoves];
1607     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1608     int i, j = 0, k;
1609
1610     // Generate all legal moves
1611     count = generate_legal_moves(pos, mlist);
1612
1613     // Add each move to the moves[] array
1614     for(i = 0; i < count; i++) {
1615       UndoInfo u;
1616       SearchStack ss[PLY_MAX_PLUS_2];
1617       bool includeMove;
1618
1619       if(includeAllMoves)
1620         includeMove = true;
1621       else {
1622         includeMove = false;
1623         for(k = 0; searchMoves[k] != MOVE_NONE; k++)
1624           if(searchMoves[k] == mlist[i].move) {
1625             includeMove = true;
1626             break;
1627           }
1628       }
1629
1630       if(includeMove) {
1631         moves[j].move = mlist[i].move;
1632         moves[j].nodes = 0ULL;
1633         pos.do_move(moves[j].move, u);
1634         moves[j].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1635                                   Depth(0), 1, 0);
1636         pos.undo_move(moves[j].move, u);
1637         moves[j].pv[0] = moves[i].move;
1638         moves[j].pv[1] = MOVE_NONE; // FIXME
1639         j++;
1640       }
1641     }
1642     count = j;
1643     this->sort();
1644   }
1645
1646
1647   // Simple accessor methods for the RootMoveList class
1648
1649   Move RootMoveList::get_move(int moveNum) const {
1650     return moves[moveNum].move;
1651   }
1652
1653   Value RootMoveList::get_move_score(int moveNum) const {
1654     return moves[moveNum].score;
1655   }
1656
1657   void RootMoveList::set_move_score(int moveNum, Value score) {
1658     moves[moveNum].score = score;
1659   }
1660   
1661   void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1662     moves[moveNum].nodes = nodes;
1663     moves[moveNum].cumulativeNodes += nodes;
1664   }
1665
1666   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1667     int j;
1668     for(j = 0; pv[j] != MOVE_NONE; j++)
1669       moves[moveNum].pv[j] = pv[j];
1670     moves[moveNum].pv[j] = MOVE_NONE;
1671   }
1672
1673   Move RootMoveList::get_move_pv(int moveNum, int i) const {
1674     return moves[moveNum].pv[i];
1675   }
1676
1677   int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) {
1678     return moves[moveNum].cumulativeNodes;
1679   }
1680   
1681   int RootMoveList::move_count() const {
1682     return count;
1683   }
1684
1685
1686   // RootMoveList::scan_for_easy_move() is called at the end of the first
1687   // iteration, and is used to detect an "easy move", i.e. a move which appears
1688   // to be much bester than all the rest.  If an easy move is found, the move
1689   // is returned, otherwise the function returns MOVE_NONE.  It is very
1690   // important that this function is called at the right moment:  The code
1691   // assumes that the first iteration has been completed and the moves have
1692   // been sorted.
1693
1694   Move RootMoveList::scan_for_easy_move() const {
1695     Value bestMoveValue = this->get_move_score(0);
1696     for(int i = 1; i < this->move_count(); i++)
1697       if(this->get_move_score(i) >= bestMoveValue - EasyMoveMargin)
1698         return MOVE_NONE;
1699     return this->get_move(0);
1700   }
1701
1702
1703   // RootMoveList::sort() sorts the root move list at the beginning of a new
1704   // iteration.
1705
1706   void RootMoveList::sort() {
1707     for(int i = 1; i < count; i++) {
1708       RootMove rm = moves[i];
1709       int j;
1710       for(j = i; j > 0 && compare_root_moves(moves[j-1], rm); j--)
1711         moves[j] = moves[j-1];
1712       moves[j] = rm;
1713     }
1714   }
1715
1716
1717   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1718   // list by their scores and depths.  It is used to order the different PVs
1719   // correctly in MultiPV mode.
1720
1721   void RootMoveList::sort_multipv(int n) {
1722     for(int i = 1; i <= n; i++) {
1723       RootMove rm = moves[i];
1724       int j;
1725       for(j = i; j > 0 && moves[j-1].score < rm.score; j--)
1726         moves[j] = moves[j-1];
1727       moves[j] = rm;
1728     }
1729   }
1730
1731
1732   // RootMoveList::compare_root_moves() is the comparison function used by
1733   // RootMoveList::sort when sorting the moves.  A move m1 is considered to
1734   // be better than a move m2 if it has a higher score, or if the moves have
1735   // equal score but m1 has the higher node count.
1736   
1737   int RootMoveList::compare_root_moves(const RootMove &rm1,
1738                                        const RootMove &rm2) {
1739     if(rm1.score < rm2.score) return 1;
1740     else if(rm1.score > rm2.score) return 0;
1741     else if(rm1.nodes < rm2.nodes) return 1;
1742     else if(rm1.nodes > rm2.nodes) return 0;
1743     else return 1;
1744   }
1745
1746
1747   // init_search_stack() initializes a search stack at the beginning of a
1748   // new search from the root.
1749
1750   void init_search_stack(SearchStack ss[]) {
1751     for(int i = 0; i < 3; i++) {
1752       ss[i].pv[i] = MOVE_NONE;
1753       ss[i].pv[i+1] = MOVE_NONE;
1754       ss[i].currentMove = MOVE_NONE;
1755       ss[i].mateKiller = MOVE_NONE;
1756       ss[i].killer1 = MOVE_NONE;
1757       ss[i].killer2 = MOVE_NONE;
1758       ss[i].threatMove = MOVE_NONE;
1759       ss[i].reduction = Depth(0);
1760     }
1761   }
1762
1763
1764   // init_node() is called at the beginning of all the search functions
1765   // (search(), search_pv(), qsearch(), and so on) and initializes the search
1766   // stack object corresponding to the current node.  Once every
1767   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1768   // for user input and checks whether it is time to stop the search.
1769
1770   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1771     assert(ply >= 0 && ply < PLY_MAX);
1772     assert(threadID >= 0 && threadID < ActiveThreads);
1773
1774     Threads[threadID].nodes++;
1775
1776     if(threadID == 0) {
1777       NodesSincePoll++;
1778       if(NodesSincePoll >= NodesBetweenPolls) {
1779         poll();
1780         NodesSincePoll = 0;
1781       }
1782     }
1783
1784     ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1785     ss[ply+2].mateKiller = MOVE_NONE;
1786     ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1787     ss[ply].threatMove = MOVE_NONE;
1788     ss[ply].reduction = Depth(0);
1789     ss[ply].currentMoveCaptureValue = Value(0);
1790
1791     if(Threads[threadID].printCurrentLine)
1792       print_current_line(ss, ply, threadID);
1793   }
1794
1795
1796   // update_pv() is called whenever a search returns a value > alpha.  It
1797   // updates the PV in the SearchStack object corresponding to the current
1798   // node.
1799     
1800   void update_pv(SearchStack ss[], int ply) {
1801     assert(ply >= 0 && ply < PLY_MAX);
1802
1803     ss[ply].pv[ply] = ss[ply].currentMove;
1804     int p;
1805     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1806       ss[ply].pv[p] = ss[ply+1].pv[p];
1807     ss[ply].pv[p] = MOVE_NONE;
1808   }
1809
1810
1811   // sp_update_pv() is a variant of update_pv for use at split points.  The
1812   // difference between the two functions is that sp_update_pv also updates
1813   // the PV at the parent node.
1814
1815   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1816     assert(ply >= 0 && ply < PLY_MAX);
1817
1818     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1819     int p;
1820     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1821       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1822     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1823   }
1824
1825
1826   // connected_moves() tests whether two moves are 'connected' in the sense
1827   // that the first move somehow made the second move possible (for instance
1828   // if the moving piece is the same in both moves).  The first move is
1829   // assumed to be the move that was made to reach the current position, while
1830   // the second move is assumed to be a move from the current position.
1831
1832   bool connected_moves(const Position &pos, Move m1, Move m2) {
1833     Square f1, t1, f2, t2;
1834
1835     assert(move_is_ok(m1));
1836     assert(move_is_ok(m2));
1837
1838     if(m2 == MOVE_NONE)
1839       return false;
1840
1841     // Case 1: The moving piece is the same in both moves.
1842     f2 = move_from(m2);
1843     t1 = move_to(m1);
1844     if(f2 == t1)
1845       return true;
1846
1847     // Case 2: The destination square for m2 was vacated by m1.
1848     t2 = move_to(m2);
1849     f1 = move_from(m1);
1850     if(t2 == f1)
1851       return true;
1852
1853     // Case 3: Moving through the vacated square:
1854     if(piece_is_slider(pos.piece_on(f2)) &&
1855        bit_is_set(squares_between(f2, t2), f1))
1856       return true;
1857
1858     // Case 4: The destination square for m2 is attacked by the moving piece
1859     // in m1:
1860     if(pos.piece_attacks_square(t1, t2))
1861       return true;
1862
1863     // Case 5: Discovered check, checking piece is the piece moved in m1:
1864     if(piece_is_slider(pos.piece_on(t1)) &&
1865        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1866                   f2) &&
1867        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1868                    t2)) {
1869       Bitboard occ = pos.occupied_squares();
1870       Color us = pos.side_to_move();
1871       Square ksq = pos.king_square(us);
1872       clear_bit(&occ, f2);
1873       if(pos.type_of_piece_on(t1) == BISHOP) {
1874         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1875           return true;
1876       }
1877       else if(pos.type_of_piece_on(t1) == ROOK) {
1878         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1879           return true;
1880       }
1881       else {
1882         assert(pos.type_of_piece_on(t1) == QUEEN);
1883         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1884           return true;
1885       }
1886     }
1887
1888     return false;
1889   }
1890     
1891   
1892   // extension() decides whether a move should be searched with normal depth,
1893   // or with extended depth.  Certain classes of moves (checking moves, in
1894   // particular) are searched with bigger depth than ordinary moves.
1895
1896   Depth extension(const Position &pos, Move m, bool pvNode,
1897                   bool check, bool singleReply, bool mateThreat) {
1898     Depth result = Depth(0);
1899
1900     if(check)
1901       result += CheckExtension[pvNode];
1902     if(singleReply)
1903       result += SingleReplyExtension[pvNode];
1904     if(pos.move_is_pawn_push_to_7th(m))
1905       result += PawnPushTo7thExtension[pvNode];
1906     if(pos.move_is_passed_pawn_push(m))
1907       result += PassedPawnExtension[pvNode];
1908     if(mateThreat)
1909       result += MateThreatExtension[pvNode];
1910     if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1911        && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1912            - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1913        && !move_promotion(m))
1914       result += PawnEndgameExtension[pvNode];
1915     if(pvNode && pos.move_is_capture(m)
1916        && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1917       result += OnePly/2;
1918
1919     return Min(result, OnePly);
1920   }
1921
1922
1923   // ok_to_do_nullmove() looks at the current position and decides whether
1924   // doing a 'null move' should be allowed.  In order to avoid zugzwang
1925   // problems, null moves are not allowed when the side to move has very
1926   // little material left.  Currently, the test is a bit too simple:  Null
1927   // moves are avoided only when the side to move has only pawns left.  It's
1928   // probably a good idea to avoid null moves in at least some more
1929   // complicated endgames, e.g. KQ vs KR.  FIXME
1930
1931   bool ok_to_do_nullmove(const Position &pos) {
1932     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
1933       return false;
1934     return true;
1935   }
1936
1937
1938   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
1939   // non-tactical moves late in the move list close to the leaves are
1940   // candidates for pruning.
1941
1942   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
1943     Square mfrom, mto, tfrom, tto;
1944
1945     assert(move_is_ok(m));
1946     assert(threat == MOVE_NONE || move_is_ok(threat));
1947     assert(!move_promotion(m));
1948     assert(!pos.move_is_check(m));
1949     assert(!pos.move_is_capture(m));
1950     assert(!pos.move_is_passed_pawn_push(m));
1951     assert(d >= OnePly);
1952
1953     mfrom = move_from(m);
1954     mto = move_to(m);
1955     tfrom = move_from(threat);
1956     tto = move_to(threat);
1957
1958     // Case 1: Castling moves are never pruned.
1959     if(move_is_castle(m))
1960       return false;
1961
1962     // Case 2: Don't prune moves which move the threatened piece
1963     if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
1964       return false;
1965
1966     // Case 3: If the threatened piece has value less than or equal to the
1967     // value of the threatening piece, don't prune move which defend it.
1968     if(!PruneDefendingMoves && threat != MOVE_NONE
1969        && (piece_value_midgame(pos.piece_on(tfrom))
1970            >= piece_value_midgame(pos.piece_on(tto)))
1971        && pos.move_attacks_square(m, tto))
1972       return false;
1973
1974     // Case 4: Don't prune moves with good history.
1975     if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
1976       return false;
1977     
1978     // Case 5: If the moving piece in the threatened move is a slider, don't
1979     // prune safe moves which block its ray.
1980     if(!PruneBlockingMoves && threat != MOVE_NONE
1981        && piece_is_slider(pos.piece_on(tfrom))
1982        && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
1983       return false;
1984
1985     return true;
1986   }
1987   
1988
1989   // fail_high_ply_1() checks if some thread is currently resolving a fail
1990   // high at ply 1 at the node below the first root node.  This information
1991   // is used for time managment.
1992   
1993   bool fail_high_ply_1() {
1994     for(int i = 0; i < ActiveThreads; i++)
1995       if(Threads[i].failHighPly1)
1996         return true;
1997     return false;
1998   }
1999
2000
2001   // current_search_time() returns the number of milliseconds which have passed
2002   // since the beginning of the current search.
2003
2004   int current_search_time() {
2005     return get_system_time() - SearchStartTime;
2006   }
2007
2008
2009   // nps() computes the current nodes/second count.
2010
2011   int nps() {
2012     int t = current_search_time();
2013     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2014   }
2015
2016
2017   // poll() performs two different functions:  It polls for user input, and it
2018   // looks at the time consumed so far and decides if it's time to abort the
2019   // search.
2020
2021   void poll() {
2022     int t, data;
2023     static int lastInfoTime;
2024
2025     t = current_search_time();
2026
2027     //  Poll for input
2028     data = Bioskey();
2029     if(data) {
2030       char input[256];
2031       if(fgets(input, 255, stdin) == NULL)
2032         strcpy(input, "quit\n");
2033       if(strncmp(input, "quit", 4) == 0) {
2034         AbortSearch = true;
2035         PonderSearch = false;
2036         Quit = true;
2037       }
2038       else if(strncmp(input, "stop", 4) == 0) {
2039         AbortSearch = true;
2040         PonderSearch = false;
2041       }
2042       else if(strncmp(input, "ponderhit", 9) == 0)
2043         ponderhit();
2044     }
2045     
2046     // Print search information
2047     if(t < 1000)
2048       lastInfoTime = 0;
2049     else if(lastInfoTime > t)
2050       // HACK: Must be a new search where we searched less than
2051       // NodesBetweenPolls nodes during the first second of search.
2052       lastInfoTime = 0;
2053     else if(t - lastInfoTime >= 1000) {
2054       lastInfoTime = t;
2055       lock_grab(&IOLock);
2056       std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2057                 << " time " << t << " hashfull " << TT.full() << std::endl;
2058       lock_release(&IOLock);
2059       if(ShowCurrentLine) 
2060         Threads[0].printCurrentLine = true;
2061     }
2062
2063     // Should we stop the search?
2064     if(!PonderSearch && Iteration >= 2 &&
2065        (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
2066                             (RootMoveNumber == 1 &&
2067                              t > MaxSearchTime + ExtraSearchTime) ||
2068                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2069                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2070       AbortSearch = true;
2071
2072     if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
2073       AbortSearch = true;
2074
2075     if(!PonderSearch && Iteration >= 3 && MaxNodes
2076        && nodes_searched() >= MaxNodes)
2077       AbortSearch = true;
2078   }
2079
2080
2081   // ponderhit() is called when the program is pondering (i.e. thinking while
2082   // it's the opponent's turn to move) in order to let the engine know that
2083   // it correctly predicted the opponent's move.
2084
2085   void ponderhit() {
2086     int t = current_search_time();
2087     PonderSearch = false;
2088     if(Iteration >= 2 &&
2089        (!InfiniteSearch && (StopOnPonderhit ||
2090                             t > AbsoluteMaxSearchTime ||
2091                             (RootMoveNumber == 1 &&
2092                              t > MaxSearchTime + ExtraSearchTime) ||
2093                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2094                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2095       AbortSearch = true;
2096   }
2097
2098
2099   // print_current_line() prints the current line of search for a given
2100   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2101   
2102   void print_current_line(SearchStack ss[], int ply, int threadID) {
2103     assert(ply >= 0 && ply < PLY_MAX);
2104     assert(threadID >= 0 && threadID < ActiveThreads);
2105
2106     if(!Threads[threadID].idle) {
2107       lock_grab(&IOLock);
2108       std::cout << "info currline " << (threadID + 1);
2109       for(int p = 0; p < ply; p++)
2110         std::cout << " " << ss[p].currentMove;
2111       std::cout << std::endl;
2112       lock_release(&IOLock);
2113     }
2114     Threads[threadID].printCurrentLine = false;
2115     if(threadID + 1 < ActiveThreads)
2116       Threads[threadID + 1].printCurrentLine = true;
2117   }
2118
2119
2120   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2121   // while the program is pondering.  The point is to work around a wrinkle in
2122   // the UCI protocol:  When pondering, the engine is not allowed to give a
2123   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2124   // We simply wait here until one of these commands is sent, and return,
2125   // after which the bestmove and pondermove will be printed (in id_loop()).
2126   
2127   void wait_for_stop_or_ponderhit() {
2128     std::string command;
2129
2130     while(true) {
2131       if(!std::getline(std::cin, command))
2132         command = "quit";
2133       
2134       if(command == "quit") {
2135         OpeningBook.close();
2136         stop_threads();
2137         quit_eval();
2138         exit(0);
2139       }
2140       else if(command == "ponderhit" || command == "stop")
2141         break;
2142     }
2143   }
2144
2145   
2146   // idle_loop() is where the threads are parked when they have no work to do.
2147   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2148   // object for which the current thread is the master.
2149
2150   void idle_loop(int threadID, SplitPoint *waitSp) {
2151     assert(threadID >= 0 && threadID < THREAD_MAX);
2152
2153     Threads[threadID].running = true; 
2154
2155     while(true) {
2156       if(AllThreadsShouldExit && threadID != 0)
2157         break;
2158
2159       // If we are not thinking, wait for a condition to be signaled instead
2160       // of wasting CPU time polling for work:
2161       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2162 #if !defined(_MSC_VER)
2163         pthread_mutex_lock(&WaitLock);
2164         if(Idle || threadID >= ActiveThreads)
2165           pthread_cond_wait(&WaitCond, &WaitLock);
2166         pthread_mutex_unlock(&WaitLock);
2167 #else
2168         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2169 #endif
2170       }
2171
2172       // If this thread has been assigned work, launch a search:
2173       if(Threads[threadID].workIsWaiting) {
2174         Threads[threadID].workIsWaiting = false;
2175         if(Threads[threadID].splitPoint->pvNode)
2176           sp_search_pv(Threads[threadID].splitPoint, threadID);
2177         else
2178           sp_search(Threads[threadID].splitPoint, threadID);
2179         Threads[threadID].idle = true;
2180       }
2181
2182       // If this thread is the master of a split point and all threads have
2183       // finished their work at this split point, return from the idle loop:
2184       if(waitSp != NULL && waitSp->cpus == 0)
2185         return;
2186     }
2187
2188     Threads[threadID].running = false;
2189   }
2190
2191
2192   // init_split_point_stack() is called during program initialization, and
2193   // initializes all split point objects.
2194
2195   void init_split_point_stack() {
2196     for(int i = 0; i < THREAD_MAX; i++)
2197       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2198         SplitPointStack[i][j].parent = NULL;
2199         lock_init(&(SplitPointStack[i][j].lock), NULL);
2200       }
2201   }
2202
2203
2204   // destroy_split_point_stack() is called when the program exits, and
2205   // destroys all locks in the precomputed split point objects.
2206
2207   void destroy_split_point_stack() {
2208     for(int i = 0; i < THREAD_MAX; i++)
2209       for(int j = 0; j < MaxActiveSplitPoints; j++)
2210         lock_destroy(&(SplitPointStack[i][j].lock));
2211   }  
2212
2213
2214   // thread_should_stop() checks whether the thread with a given threadID has
2215   // been asked to stop, directly or indirectly.  This can happen if a beta
2216   // cutoff has occured in thre thread's currently active split point, or in
2217   // some ancestor of the current split point.
2218
2219   bool thread_should_stop(int threadID) {
2220     assert(threadID >= 0 && threadID < ActiveThreads);
2221   
2222     SplitPoint *sp;
2223
2224     if(Threads[threadID].stop)
2225       return true;
2226     if(ActiveThreads <= 2)
2227       return false;
2228     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2229       if(sp->finished) {
2230         Threads[threadID].stop = true;
2231         return true;
2232       }
2233     return false;
2234   }  
2235
2236
2237   // thread_is_available() checks whether the thread with threadID "slave" is
2238   // available to help the thread with threadID "master" at a split point.  An
2239   // obvious requirement is that "slave" must be idle.  With more than two
2240   // threads, this is not by itself sufficient:  If "slave" is the master of
2241   // some active split point, it is only available as a slave to the other
2242   // threads which are busy searching the split point at the top of "slave"'s
2243   // split point stack (the "helpful master concept" in YBWC terminology).
2244
2245   bool thread_is_available(int slave, int master) {
2246     assert(slave >= 0 && slave < ActiveThreads);
2247     assert(master >= 0 && master < ActiveThreads);
2248     assert(ActiveThreads > 1);
2249   
2250     if(!Threads[slave].idle || slave == master)
2251       return false;
2252
2253     if(Threads[slave].activeSplitPoints == 0)
2254       // No active split points means that the thread is available as a slave
2255       // for any other thread.
2256       return true;
2257
2258     if(ActiveThreads == 2)
2259       return true;
2260
2261     // Apply the "helpful master" concept if possible.
2262     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2263       return true;
2264
2265     return false;
2266   }
2267
2268   
2269   // idle_thread_exists() tries to find an idle thread which is available as
2270   // a slave for the thread with threadID "master".
2271
2272   bool idle_thread_exists(int master) {
2273     assert(master >= 0 && master < ActiveThreads);
2274     assert(ActiveThreads > 1);
2275   
2276     for(int i = 0; i < ActiveThreads; i++)
2277       if(thread_is_available(i, master))
2278         return true;
2279     return false;
2280   }
2281
2282
2283   // split() does the actual work of distributing the work at a node between
2284   // several threads at PV nodes.  If it does not succeed in splitting the
2285   // node (because no idle threads are available, or because we have no unused
2286   // split point objects), the function immediately returns false.  If
2287   // splitting is possible, a SplitPoint object is initialized with all the
2288   // data that must be copied to the helper threads (the current position and
2289   // search stack, alpha, beta, the search depth, etc.), and we tell our
2290   // helper threads that they have been assigned work.  This will cause them
2291   // to instantly leave their idle loops and call sp_search_pv().  When all
2292   // threads have returned from sp_search_pv (or, equivalently, when
2293   // splitPoint->cpus becomes 0), split() returns true.
2294
2295   bool split(const Position &p, SearchStack *sstck, int ply,
2296              Value *alpha, Value *beta, Value *bestValue,
2297              Depth depth, int *moves,
2298              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2299     assert(p.is_ok());
2300     assert(sstck != NULL);
2301     assert(ply >= 0 && ply < PLY_MAX);
2302     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2303     assert(!pvNode || *alpha < *beta);
2304     assert(*beta <= VALUE_INFINITE);
2305     assert(depth > Depth(0));
2306     assert(master >= 0 && master < ActiveThreads);
2307     assert(ActiveThreads > 1);
2308
2309     SplitPoint *splitPoint;
2310     int i;
2311
2312     lock_grab(&MPLock);
2313
2314     // If no other thread is available to help us, or if we have too many
2315     // active split points, don't split:
2316     if(!idle_thread_exists(master) ||
2317        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2318       lock_release(&MPLock);
2319       return false;
2320     }
2321
2322     // Pick the next available split point object from the split point stack:
2323     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2324     Threads[master].activeSplitPoints++;
2325
2326     // Initialize the split point object:
2327     splitPoint->parent = Threads[master].splitPoint;
2328     splitPoint->finished = false;
2329     splitPoint->ply = ply;
2330     splitPoint->depth = depth;
2331     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2332     splitPoint->beta = *beta;
2333     splitPoint->pvNode = pvNode;
2334     splitPoint->dcCandidates = dcCandidates;
2335     splitPoint->bestValue = *bestValue;
2336     splitPoint->master = master;
2337     splitPoint->mp = mp;
2338     splitPoint->moves = *moves;
2339     splitPoint->cpus = 1;
2340     splitPoint->pos.copy(p);
2341     splitPoint->parentSstack = sstck;
2342     for(i = 0; i < ActiveThreads; i++)
2343       splitPoint->slaves[i] = 0;
2344
2345     // Copy the current position and the search stack to the master thread:
2346     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2347     Threads[master].splitPoint = splitPoint;
2348
2349     // Make copies of the current position and search stack for each thread:
2350     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2351         i++)
2352       if(thread_is_available(i, master)) {
2353         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2354         Threads[i].splitPoint = splitPoint;
2355         splitPoint->slaves[i] = 1;
2356         splitPoint->cpus++;
2357       }
2358
2359     // Tell the threads that they have work to do.  This will make them leave
2360     // their idle loop.
2361     for(i = 0; i < ActiveThreads; i++)
2362       if(i == master || splitPoint->slaves[i]) {
2363         Threads[i].workIsWaiting = true;
2364         Threads[i].idle = false;
2365         Threads[i].stop = false;
2366       }
2367
2368     lock_release(&MPLock);
2369
2370     // Everything is set up.  The master thread enters the idle loop, from
2371     // which it will instantly launch a search, because its workIsWaiting
2372     // slot is 'true'.  We send the split point as a second parameter to the
2373     // idle loop, which means that the main thread will return from the idle
2374     // loop when all threads have finished their work at this split point
2375     // (i.e. when // splitPoint->cpus == 0).
2376     idle_loop(master, splitPoint);
2377
2378     // We have returned from the idle loop, which means that all threads are
2379     // finished.  Update alpha, beta and bestvalue, and return:
2380     lock_grab(&MPLock);
2381     if(pvNode) *alpha = splitPoint->alpha;
2382     *beta = splitPoint->beta;
2383     *bestValue = splitPoint->bestValue;
2384     Threads[master].stop = false;
2385     Threads[master].idle = false;
2386     Threads[master].activeSplitPoints--;
2387     Threads[master].splitPoint = splitPoint->parent;
2388     lock_release(&MPLock);
2389
2390     return true;
2391   }
2392
2393
2394   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2395   // to start a new search from the root.
2396
2397   void wake_sleeping_threads() {
2398     if(ActiveThreads > 1) {
2399       for(int i = 1; i < ActiveThreads; i++) {
2400         Threads[i].idle = true;
2401         Threads[i].workIsWaiting = false;
2402       }
2403 #if !defined(_MSC_VER)
2404       pthread_mutex_lock(&WaitLock);
2405       pthread_cond_broadcast(&WaitCond);
2406       pthread_mutex_unlock(&WaitLock);
2407 #else
2408       for(int i = 1; i < THREAD_MAX; i++)
2409         SetEvent(SitIdleEvent[i]);
2410 #endif
2411     }
2412   }
2413     
2414
2415   // init_thread() is the function which is called when a new thread is
2416   // launched.  It simply calls the idle_loop() function with the supplied
2417   // threadID.  There are two versions of this function; one for POSIX threads
2418   // and one for Windows threads.
2419   
2420 #if !defined(_MSC_VER)
2421
2422   void *init_thread(void *threadID) {
2423     idle_loop(*(int *)threadID, NULL);
2424     return NULL;
2425   }
2426   
2427 #else
2428
2429   DWORD WINAPI init_thread(LPVOID threadID) {
2430     idle_loop(*(int *)threadID, NULL);
2431     return NULL;
2432   }
2433
2434 #endif
2435
2436 }