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