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