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