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