]> git.sesse.net Git - stockfish/blobdiff - src/search.cpp
Revert "Last minute surprise" for now
[stockfish] / src / search.cpp
index 55533ddd9af8caba5ae9f009e407cd13d77f71fe..80eeb717f52d548897a5fdf4b7d9119d908aaefd 100644 (file)
@@ -1,13 +1,14 @@
 /*
-  Glaurung, a UCI chess playing engine.
-  Copyright (C) 2004-2008 Tord Romstad
+  Stockfish, a UCI chess playing engine derived from Glaurung 2.1
+  Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
+  Copyright (C) 2008 Marco Costalba
 
-  Glaurung is free software: you can redistribute it and/or modify
+  Stockfish is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
 
-  Glaurung is distributed in the hope that it will be useful,
+  Stockfish is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
@@ -22,7 +23,6 @@
 ////
 
 #include <cassert>
-#include <cstdio>
 #include <fstream>
 #include <iostream>
 #include <sstream>
@@ -70,16 +70,16 @@ namespace {
 
   public:
     RootMoveList(Position &pos, Move searchMoves[]);
-    Move get_move(int moveNum) const;
-    Value get_move_score(int moveNum) const;
-    void set_move_score(int moveNum, Value score);
-    void set_move_nodes(int moveNum, int64_t nodes);
+    inline Move get_move(int moveNum) const;
+    inline Value get_move_score(int moveNum) const;
+    inline void set_move_score(int moveNum, Value score);
+    inline void set_move_nodes(int moveNum, int64_t nodes);
     void set_move_pv(int moveNum, const Move pv[]);
-    Move get_move_pv(int moveNum, int i) const;
-    int64_t get_move_cumulative_nodes(int moveNum) const;
-    int move_count() const;
+    inline Move get_move_pv(int moveNum, int i) const;
+    inline int64_t get_move_cumulative_nodes(int moveNum) const;
+    inline int move_count() const;
     Move scan_for_easy_move() const;
-    void sort();
+    inline void sort();
     void sort_multipv(int n);
 
   private:
@@ -153,6 +153,12 @@ namespace {
   Depth RazorDepth = 4*OnePly;
   Value RazorMargin = Value(0x300);
 
+  // Last seconds noise filtering (LSN)
+  bool UseLSNFiltering = false;
+  bool looseOnTime = false;
+  int LSNTime = 4 * 1000; // In milliseconds
+  Value LSNValue = Value(0x200);
+
   // Extensions.  Array index 0 is used at non-PV nodes, index 1 at PV nodes.
   Depth CheckExtension[2] = {OnePly, OnePly};
   Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
@@ -181,7 +187,7 @@ namespace {
   // Time managment variables
   int SearchStartTime;
   int MaxNodes, MaxDepth;
-  int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
+  int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
   Move BestRootMove, PonderMove, EasyMove;
   int RootMoveNumber;
   bool InfiniteSearch;
@@ -221,7 +227,7 @@ namespace {
 
   /// Functions
 
-  void id_loop(const Position &pos, Move searchMoves[]);
+  Value id_loop(const Position &pos, Move searchMoves[]);
   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
                   Depth depth, int ply, int threadID);
@@ -241,6 +247,9 @@ namespace {
   bool ok_to_do_nullmove(const Position &pos);
   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
+  bool ok_to_history(const Position &pos, Move m);
+  void update_history(const Position& pos, Move m, Depth depth,
+                      Move movesSearched[], int moveCount);
 
   bool fail_high_ply_1();
   int current_search_time();
@@ -293,13 +302,13 @@ History H;  // Should be made local?
 //// Functions
 ////
 
-/// think() is the external interface to Glaurung's search, and is called when
+/// think() is the external interface to Stockfish's search, and is called when
 /// the program receives the UCI 'go' command.  It initializes various
 /// search-related global variables, and calls root_search()
 
-void think(const Position &pos, bool infinite, bool ponder, int time,
-           int increment, int movesToGo, int maxDepth, int maxNodes,
-           int maxTime, Move searchMoves[]) {
+void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
+           int time[], int increment[], int movesToGo, int maxDepth,
+           int maxNodes, int maxTime, Move searchMoves[]) {
 
   // Look for a book move:
   if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
@@ -339,7 +348,7 @@ void think(const Position &pos, bool infinite, bool ponder, int time,
   TT.set_size(get_option_value_int("Hash"));
   if(button_was_pressed("Clear Hash"))
     TT.clear();
-  PonderingEnabled = get_option_value_int("Ponder");
+  PonderingEnabled = get_option_value_bool("Ponder");
   MultiPV = get_option_value_int("MultiPV");
 
   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
@@ -392,6 +401,10 @@ void think(const Position &pos, bool infinite, bool ponder, int time,
   RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
   RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
 
+  UseLSNFiltering = get_option_value_bool("LSN filtering");
+  LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
+  LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
+
   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
   MaxThreadsPerSplitPoint =
     get_option_value_int("Maximum Number of Threads per Split Point");
@@ -404,14 +417,6 @@ void think(const Position &pos, bool infinite, bool ponder, int time,
     init_eval(ActiveThreads);
   }
 
-  // Write information to search log file:
-  if(UseLogFile) {
-    LogFile << "Searching: " << pos.to_fen() << '\n';
-    LogFile << "infinite: " << infinite << " ponder: " << ponder
-            << " time: " << time << " increment: " << increment
-            << " moves to go: " << movesToGo << '\n';
-  }
-
   // Wake up sleeping threads:
   wake_sleeping_threads();
 
@@ -419,24 +424,30 @@ void think(const Position &pos, bool infinite, bool ponder, int time,
     assert(thread_is_available(i, 0));
 
   // Set thinking time:
+  int myTime = time[side_to_move];
+  int myIncrement = increment[side_to_move];
+  int oppTime = time[1 - side_to_move];
+
+  TimeAdvantage = myTime - oppTime;
+
   if(!movesToGo) { // Sudden death time control
     if(increment) {
-      MaxSearchTime = time / 30 + increment;
-      AbsoluteMaxSearchTime = Max(time / 4, increment - 100);
+      MaxSearchTime = myTime / 30 + myIncrement;
+      AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
     }
     else { // Blitz game without increment
-      MaxSearchTime = time / 40;
-      AbsoluteMaxSearchTime = time / 8;
+      MaxSearchTime = myTime / 40;
+      AbsoluteMaxSearchTime = myTime / 8;
     }
   }
   else { // (x moves) / (y minutes)
     if(movesToGo == 1) {
-      MaxSearchTime = time / 2;
-      AbsoluteMaxSearchTime = Min(time / 2, time - 500);
+      MaxSearchTime = myTime / 2;
+      AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
     }
     else {
-      MaxSearchTime = time / Min(movesToGo, 20);
-      AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3);
+      MaxSearchTime = myTime / Min(movesToGo, 20);
+      AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
     }
   }
   if(PonderingEnabled) {
@@ -457,9 +468,32 @@ void think(const Position &pos, bool infinite, bool ponder, int time,
   else
     NodesBetweenPolls = 30000;
 
+
+  // Write information to search log file:
+  if(UseLogFile) {
+    LogFile << "Searching: " << pos.to_fen() << '\n';
+    LogFile << "infinite: " << infinite << " ponder: " << ponder
+            << " time: " << myTime << " increment: " << myIncrement
+            << " moves to go: " << movesToGo << '\n';
+  }
+
   // We're ready to start thinking.  Call the iterative deepening loop
   // function:
-  id_loop(pos, searchMoves);
+  if (!looseOnTime)
+  {
+      Value v = id_loop(pos, searchMoves);
+      looseOnTime = (   UseLSNFiltering
+                     && myTime < LSNTime
+                     && myIncrement == 0
+                     && v < -LSNValue);
+  }
+  else
+  {
+      looseOnTime = false; // reset for next match
+      while (SearchStartTime + myTime + 1000 > get_system_time())
+          ; // wait here
+      id_loop(pos, searchMoves); // to fail gracefully
+  }
 
   if(UseLogFile)
     LogFile.close();
@@ -561,7 +595,7 @@ namespace {
   // been consumed, the user stops the search, or the maximum search depth is
   // reached.
 
-  void id_loop(const Position &pos, Move searchMoves[]) {
+  Value id_loop(const Position &pos, Move searchMoves[]) {
     Position p(pos);
     SearchStack ss[PLY_MAX_PLUS_2];
 
@@ -632,6 +666,10 @@ namespace {
             BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
             BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
 
+        // If we need some more and we are in time advantage take it.
+        if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
+            ExtraSearchTime += MaxSearchTime / 2;
+
         // Stop search if most of MaxSearchTime is consumed at the end of the
         // iteration.  We probably don't have enough time to search the first
         // move at the next iteration anyway.
@@ -681,6 +719,7 @@ namespace {
       LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
       LogFile << std::endl;
     }
+    return rml.get_move_score(0);
   }
 
 
@@ -932,7 +971,7 @@ namespace {
         else
             value = alpha + 1; // Just to trigger next condition
 
-        if (value > alpha) // Go with full depth non-pv search
+        if (value > alpha) // Go with full depth pv search
         {
             ss[ply].reduction = Depth(0);
             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
@@ -993,8 +1032,7 @@ namespace {
         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
 
     // If the search is not aborted, update the transposition table,
-    // history counters, and killer moves.  This code is somewhat messy,
-    // and definitely needs to be cleaned up.  FIXME
+    // history counters, and killer moves.
     if (AbortSearch || thread_should_stop(threadID))
         return bestValue;
 
@@ -1004,21 +1042,14 @@ namespace {
     else if (bestValue >= beta)
     {
         Move m = ss[ply].pv[ply];
-        if (pos.square_is_empty(move_to(m)) && !move_promotion(m) && !move_is_ep(m))
+        if (ok_to_history(pos, m)) // Only non capture moves are considered
         {
-            for (int i = 0; i < moveCount - 1; i++)
-                if (    pos.square_is_empty(move_to(movesSearched[i]))
-                    && !move_promotion(movesSearched[i])
-                    && !move_is_ep(movesSearched[i]))
-                    H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
-
-            H.success(pos.piece_on(move_from(m)), m, depth);
-
-          if (m != ss[ply].killer1)
-          {
-            ss[ply].killer2 = ss[ply].killer1;
-            ss[ply].killer1 = m;
-          }
+            update_history(pos, m, depth, movesSearched, moveCount);
+            if (m != ss[ply].killer1)
+            {
+                ss[ply].killer2 = ss[ply].killer1;
+                ss[ply].killer1 = m;
+            }
         }
         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
     }
@@ -1117,9 +1148,8 @@ namespace {
         }
     }
     // Null move search not allowed, try razoring
-    else if (   depth < RazorDepth
-             && approximateEval < beta - RazorMargin
-             && evaluate(pos, ei, threadID) < beta - RazorMargin)
+    else if (  (approximateEval < beta - RazorMargin && depth < RazorDepth)
+             ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
     {
         Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
         if (v < beta)
@@ -1255,8 +1285,7 @@ namespace {
         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
 
     // If the search is not aborted, update the transposition table,
-    // history counters, and killer moves.  This code is somewhat messy,
-    // and definitely needs to be cleaned up.  FIXME
+    // history counters, and killer moves.
     if (AbortSearch || thread_should_stop(threadID))
         return bestValue;
 
@@ -1265,16 +1294,9 @@ namespace {
     else
     {
         Move m = ss[ply].pv[ply];
-        if (pos.square_is_empty(move_to(m)) && !move_promotion(m) && !move_is_ep(m))
+        if (ok_to_history(pos, m)) // Only non capture moves are considered
         {
-            for (int i = 0; i < moveCount - 1; i++)
-                if (    pos.square_is_empty(move_to(movesSearched[i]))
-                    && !move_promotion(movesSearched[i])
-                    && !move_is_ep(movesSearched[i]))
-                    H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
-
-            H.success(pos.piece_on(move_from(m)), m, depth);
-
+            update_history(pos, m, depth, movesSearched, moveCount);
             if (m != ss[ply].killer1)
             {
                 ss[ply].killer2 = ss[ply].killer1;
@@ -1312,6 +1334,11 @@ namespace {
     if (pos.is_draw())
         return VALUE_DRAW;
 
+    // Transposition table lookup
+    const TTEntry* tte = TT.retrieve(pos);
+    if (tte && ok_to_use_TT(tte, depth, beta, ply))
+        return value_from_tt(tte->value(), ply);
+
     // Evaluate the position statically:
     Value staticValue = evaluate(pos, ei, threadID);
 
@@ -1409,6 +1436,9 @@ namespace {
 
     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
 
+    // Update transposition table
+    TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
+
     return bestValue;
   }
 
@@ -1422,6 +1452,7 @@ namespace {
   // care of after we return from the split point.
 
   void sp_search(SplitPoint *sp, int threadID) {
+
     assert(threadID >= 0 && threadID < ActiveThreads);
     assert(ActiveThreads > 1);
 
@@ -1429,73 +1460,87 @@ namespace {
     SearchStack *ss = sp->sstack[threadID];
     Value value;
     Move move;
-    int moveCount = sp->moves;
     bool isCheck = pos.is_check();
-    bool useFutilityPruning =
-      UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck;
+    bool useFutilityPruning =    UseFutilityPruning
+                              && sp->depth < SelectiveDepth
+                              && !isCheck;
+
+    while (    sp->bestValue < sp->beta
+           && !thread_should_stop(threadID)
+           && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
+    {
+      assert(move_is_ok(move));
 
-    while(sp->bestValue < sp->beta && !thread_should_stop(threadID)
-          && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
-      UndoInfo u;
-      Depth ext, newDepth;
       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
       bool moveIsCapture = pos.move_is_capture(move);
       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
 
-      assert(move_is_ok(move));
-
       lock_grab(&(sp->lock));
-      sp->moves++;
-      moveCount = sp->moves;
+      int moveCount = ++sp->moves;
       lock_release(&(sp->lock));
 
       ss[sp->ply].currentMove = move;
 
       // Decide the new search depth.
-      ext = extension(pos, move, false, moveIsCheck, false, false);
-      newDepth = sp->depth - OnePly + ext;
+      Depth ext = extension(pos, move, false, moveIsCheck, false, false);
+      Depth newDepth = sp->depth - OnePly + ext;
 
       // Prune?
-      if(useFutilityPruning && ext == Depth(0) && !moveIsCapture
-         && !moveIsPassedPawnPush && !move_promotion(move)
-         && moveCount >= 2 + int(sp->depth)
-         && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
+      if (    useFutilityPruning
+          &&  ext == Depth(0)
+          && !moveIsCapture
+          && !moveIsPassedPawnPush
+          && !move_promotion(move)
+          &&  moveCount >= 2 + int(sp->depth)
+          &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
         continue;
 
       // Make and search the move.
+      UndoInfo u;
       pos.do_move(move, u, sp->dcCandidates);
-      if(ext == Depth(0) && moveCount >= LMRNonPVMoves
-         && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
-         && !move_is_castle(move)
-         && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
-        ss[sp->ply].reduction = OnePly;
-        value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1,
-                        true, threadID);
+
+      // Try to reduce non-pv search depth by one ply if move seems not problematic,
+      // if the move fails high will be re-searched at full depth.
+      if (    ext == Depth(0)
+          &&  moveCount >= LMRNonPVMoves
+          && !moveIsCapture
+          && !moveIsPassedPawnPush
+          && !move_promotion(move)
+          && !move_is_castle(move)
+          &&  move != ss[sp->ply].killer1
+          &&  move != ss[sp->ply].killer2)
+      {
+          ss[sp->ply].reduction = OnePly;
+          value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
       }
       else
-        value = sp->beta;
-      if(value >= sp->beta) {
-        ss[sp->ply].reduction = Depth(0);
-        value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true,
-                        threadID);
+          value = sp->beta; // Just to trigger next condition
+
+      if (value >= sp->beta) // Go with full depth non-pv search
+      {
+          ss[sp->ply].reduction = Depth(0);
+          value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
       }
       pos.undo_move(move, u);
 
       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
 
-      if(thread_should_stop(threadID))
-        break;
+      if (thread_should_stop(threadID))
+          break;
 
       // New best move?
       lock_grab(&(sp->lock));
-      if(value > sp->bestValue && !thread_should_stop(threadID)) {
-        sp->bestValue = value;
-        if(sp->bestValue >= sp->beta) {
-          sp_update_pv(sp->parentSstack, ss, sp->ply);
-          for(int i = 0; i < ActiveThreads; i++)
-            if(i != threadID && (i == sp->master || sp->slaves[i]))
-              Threads[i].stop = true;
-          sp->finished = true;
+      if (value > sp->bestValue && !thread_should_stop(threadID))
+      {
+          sp->bestValue = value;
+          if (sp->bestValue >= sp->beta)
+          {
+              sp_update_pv(sp->parentSstack, ss, sp->ply);
+              for (int i = 0; i < ActiveThreads; i++)
+                  if (i != threadID && (i == sp->master || sp->slaves[i]))
+                      Threads[i].stop = true;
+
+              sp->finished = true;
         }
       }
       lock_release(&(sp->lock));
@@ -1505,10 +1550,10 @@ namespace {
 
     // If this is the master thread and we have been asked to stop because of
     // a beta cutoff higher up in the tree, stop all slave threads:
-    if(sp->master == threadID && thread_should_stop(threadID))
-      for(int i = 0; i < ActiveThreads; i++)
-        if(sp->slaves[i])
-          Threads[i].stop = true;
+    if (sp->master == threadID && thread_should_stop(threadID))
+        for (int i = 0; i < ActiveThreads; i++)
+            if (sp->slaves[i])
+                Threads[i].stop = true;
 
     sp->cpus--;
     sp->slaves[threadID] = 0;
@@ -1526,6 +1571,7 @@ namespace {
   // after we return from the split point.
 
   void sp_search_pv(SplitPoint *sp, int threadID) {
+
     assert(threadID >= 0 && threadID < ActiveThreads);
     assert(ActiveThreads > 1);
 
@@ -1533,12 +1579,11 @@ namespace {
     SearchStack *ss = sp->sstack[threadID];
     Value value;
     Move move;
-    int moveCount = sp->moves;
 
-    while(sp->alpha < sp->beta && !thread_should_stop(threadID)
-          && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
-      UndoInfo u;
-      Depth ext, newDepth;
+    while (    sp->alpha < sp->beta
+           && !thread_should_stop(threadID)
+           && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
+    {
       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
       bool moveIsCapture = pos.move_is_capture(move);
       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
@@ -1549,74 +1594,88 @@ namespace {
         PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
 
       lock_grab(&(sp->lock));
-      sp->moves++;
-      moveCount = sp->moves;
+      int moveCount = ++sp->moves;
       lock_release(&(sp->lock));
 
       ss[sp->ply].currentMove = move;
 
       // Decide the new search depth.
-      ext = extension(pos, move, true, moveIsCheck, false, false);
-      newDepth = sp->depth - OnePly + ext;
+      Depth ext = extension(pos, move, true, moveIsCheck, false, false);
+      Depth newDepth = sp->depth - OnePly + ext;
 
       // Make and search the move.
+      UndoInfo u;
       pos.do_move(move, u, sp->dcCandidates);
-      if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
-         && !move_promotion(move) && !moveIsPassedPawnPush
-         && !move_is_castle(move)
-         && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
-        ss[sp->ply].reduction = OnePly;
-        value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
-                        true, threadID);
+
+      // Try to reduce non-pv search depth by one ply if move seems not problematic,
+      // if the move fails high will be re-searched at full depth.
+      if (    ext == Depth(0)
+          &&  moveCount >= LMRPVMoves
+          && !moveIsCapture
+          && !moveIsPassedPawnPush
+          && !move_promotion(move)
+          && !move_is_castle(move)
+          &&  move != ss[sp->ply].killer1
+          &&  move != ss[sp->ply].killer2)
+      {
+          ss[sp->ply].reduction = OnePly;
+          value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
       }
       else
-        value = sp->alpha + 1;
-      if(value > sp->alpha) {
-        ss[sp->ply].reduction = Depth(0);
-        value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
-                        threadID);
-        if(value > sp->alpha && value < sp->beta) {
-          if(sp->ply == 1 && RootMoveNumber == 1)
-            // When the search fails high at ply 1 while searching the first
-            // move at the root, set the flag failHighPly1.  This is used for
-            // time managment:  We don't want to stop the search early in
-            // such cases, because resolving the fail high at ply 1 could
-            // result in a big drop in score at the root.
-            Threads[threadID].failHighPly1 = true;
-          value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
-                             sp->ply+1, threadID);
-          Threads[threadID].failHighPly1 = false;
+          value = sp->alpha + 1; // Just to trigger next condition
+
+      if (value > sp->alpha) // Go with full depth non-pv search
+      {
+          ss[sp->ply].reduction = Depth(0);
+          value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
+
+          if (value > sp->alpha && value < sp->beta)
+          {
+              // When the search fails high at ply 1 while searching the first
+              // move at the root, set the flag failHighPly1.  This is used for
+              // time managment:  We don't want to stop the search early in
+              // such cases, because resolving the fail high at ply 1 could
+              // result in a big drop in score at the root.
+              if (sp->ply == 1 && RootMoveNumber == 1)
+                  Threads[threadID].failHighPly1 = true;
+
+              value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
+              Threads[threadID].failHighPly1 = false;
         }
       }
       pos.undo_move(move, u);
 
       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
 
-      if(thread_should_stop(threadID))
-        break;
+      if (thread_should_stop(threadID))
+          break;
 
       // New best move?
       lock_grab(&(sp->lock));
-      if(value > sp->bestValue && !thread_should_stop(threadID)) {
-        sp->bestValue = value;
-        if(value > sp->alpha) {
-          sp->alpha = value;
-          sp_update_pv(sp->parentSstack, ss, sp->ply);
-          if(value == value_mate_in(sp->ply + 1))
-            ss[sp->ply].mateKiller = move;
-          if(value >= sp->beta) {
-            for(int i = 0; i < ActiveThreads; i++)
-              if(i != threadID && (i == sp->master || sp->slaves[i]))
-                Threads[i].stop = true;
-            sp->finished = true;
-          }
+      if (value > sp->bestValue && !thread_should_stop(threadID))
+      {
+          sp->bestValue = value;
+          if (value > sp->alpha)
+          {
+              sp->alpha = value;
+              sp_update_pv(sp->parentSstack, ss, sp->ply);
+              if (value == value_mate_in(sp->ply + 1))
+                  ss[sp->ply].mateKiller = move;
+
+              if(value >= sp->beta)
+              {
+                  for(int i = 0; i < ActiveThreads; i++)
+                      if(i != threadID && (i == sp->master || sp->slaves[i]))
+                          Threads[i].stop = true;
+
+                  sp->finished = true;
+              }
         }
         // If we are at ply 1, and we are searching the first root move at
         // ply 0, set the 'Problem' variable if the score has dropped a lot
         // (from the computer's point of view) since the previous iteration:
-        if(Iteration >= 2 &&
-           -value <= ValueByIteration[Iteration-1] - ProblemMargin)
-          Problem = true;
+        if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
+            Problem = true;
       }
       lock_release(&(sp->lock));
     }
@@ -1625,10 +1684,10 @@ namespace {
 
     // If this is the master thread and we have been asked to stop because of
     // a beta cutoff higher up in the tree, stop all slave threads:
-    if(sp->master == threadID && thread_should_stop(threadID))
-      for(int i = 0; i < ActiveThreads; i++)
-        if(sp->slaves[i])
-          Threads[i].stop = true;
+    if (sp->master == threadID && thread_should_stop(threadID))
+        for (int i = 0; i < ActiveThreads; i++)
+            if (sp->slaves[i])
+                Threads[i].stop = true;
 
     sp->cpus--;
     sp->slaves[threadID] = 0;
@@ -1937,26 +1996,35 @@ namespace {
 
   Depth extension(const Position &pos, Move m, bool pvNode,
                   bool check, bool singleReply, bool mateThreat) {
+
     Depth result = Depth(0);
 
-    if(check)
-      result += CheckExtension[pvNode];
-    if(singleReply)
-      result += SingleReplyExtension[pvNode];
-    if(pos.move_is_pawn_push_to_7th(m))
-      result += PawnPushTo7thExtension[pvNode];
-    if(pos.move_is_passed_pawn_push(m))
-      result += PassedPawnExtension[pvNode];
-    if(mateThreat)
-      result += MateThreatExtension[pvNode];
-    if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
-       && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
-           - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
-       && !move_promotion(m))
-      result += PawnEndgameExtension[pvNode];
-    if(pvNode && pos.move_is_capture(m)
-       && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
-      result += OnePly/2;
+    if (check)
+        result += CheckExtension[pvNode];
+
+    if (singleReply)
+        result += SingleReplyExtension[pvNode];
+
+    if (pos.move_is_pawn_push_to_7th(m))
+        result += PawnPushTo7thExtension[pvNode];
+
+    if (pos.move_is_passed_pawn_push(m))
+        result += PassedPawnExtension[pvNode];
+
+    if (mateThreat)
+        result += MateThreatExtension[pvNode];
+
+    if (   pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame\r
+        && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)\r
+            - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))\r
+        && !move_promotion(m))
+        result += PawnEndgameExtension[pvNode];
+    
+    if (   pvNode
+        && pos.move_is_capture(m)
+        && pos.type_of_piece_on(move_to(m)) != PAWN
+        && pos.see(m) >= 0)
+        result += OnePly/2;
 
     return Min(result, OnePly);
   }
@@ -2044,6 +2112,30 @@ namespace {
   }
 
 
+  // ok_to_history() returns true if a move m can be stored
+  // in history. Should be a non capturing move.
+
+  bool ok_to_history(const Position& pos, Move m) {
+
+    return    pos.square_is_empty(move_to(m))
+          && !move_promotion(m)
+          && !move_is_ep(m);
+  }
+
+
+  // update_history() registers a good move that produced a beta-cutoff
+  // in history and marks as failures all the other moves of that ply.
+
+  void update_history(const Position& pos, Move m, Depth depth,
+                      Move movesSearched[], int moveCount) {
+
+    H.success(pos.piece_on(move_from(m)), m, depth);
+
+    for (int i = 0; i < moveCount - 1; i++)
+        if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
+            H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
+  }
+
   // fail_high_ply_1() checks if some thread is currently resolving a fail
   // high at ply 1 at the node below the first root node.  This information
   // is used for time managment.
@@ -2077,62 +2169,70 @@ namespace {
   // search.
 
   void poll() {
-    int t, data;
-    static int lastInfoTime;
 
-    t = current_search_time();
+    static int lastInfoTime;
+    int t = current_search_time();
 
     //  Poll for input
-    data = Bioskey();
-    if(data) {
-      char input[256];
-      if(fgets(input, 255, stdin) == NULL)
-        strcpy(input, "quit\n");
-      if(strncmp(input, "quit", 4) == 0) {
-        AbortSearch = true;
-        PonderSearch = false;
-        Quit = true;
-      }
-      else if(strncmp(input, "stop", 4) == 0) {
-        AbortSearch = true;
-        PonderSearch = false;
-      }
-      else if(strncmp(input, "ponderhit", 9) == 0)
-        ponderhit();
-    }
+    if (Bioskey())
+    {
+        // We are line oriented, don't read single chars
+        std::string command;
+        if (!std::getline(std::cin, command))
+            command = "quit";
 
-    // Print search information
-    if(t < 1000)
-      lastInfoTime = 0;
-    else if(lastInfoTime > t)
-      // HACK: Must be a new search where we searched less than
-      // NodesBetweenPolls nodes during the first second of search.
-      lastInfoTime = 0;
-    else if(t - lastInfoTime >= 1000) {
-      lastInfoTime = t;
-      lock_grab(&IOLock);
-      std::cout << "info nodes " << nodes_searched() << " nps " << nps()
-                << " time " << t << " hashfull " << TT.full() << std::endl;
-      lock_release(&IOLock);
-      if(ShowCurrentLine)
-        Threads[0].printCurrentLine = true;
+        if (command == "quit")
+        {
+            AbortSearch = true;
+            PonderSearch = false;
+            Quit = true;
+        }
+        else if(command == "stop")
+        {
+            AbortSearch = true;
+            PonderSearch = false;
+        }
+        else if(command == "ponderhit")
+            ponderhit();
     }
+    // Print search information
+    if (t < 1000)
+        lastInfoTime = 0;
+
+    else if (lastInfoTime > t)
+        // HACK: Must be a new search where we searched less than
+        // NodesBetweenPolls nodes during the first second of search.
+        lastInfoTime = 0;
 
+    else if (t - lastInfoTime >= 1000)
+    {
+        lastInfoTime = t;
+        lock_grab(&IOLock);
+        if (dbg_show_mean)
+            dbg_print_mean();
+
+        if (dbg_show_hit_rate)
+            dbg_print_hit_rate();
+
+        std::cout << "info nodes " << nodes_searched() << " nps " << nps()
+                  << " time " << t << " hashfull " << TT.full() << std::endl;
+        lock_release(&IOLock);
+        if (ShowCurrentLine)
+            Threads[0].printCurrentLine = true;
+    }
     // Should we stop the search?
-    if(!PonderSearch && Iteration >= 2 &&
-       (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
-                            (RootMoveNumber == 1 &&
-                             t > MaxSearchTime + ExtraSearchTime) ||
-                            (!FailHigh && !fail_high_ply_1() && !Problem &&
-                             t > 6*(MaxSearchTime + ExtraSearchTime)))))
-      AbortSearch = true;
+    if (PonderSearch)
+        return;
 
-    if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
-      AbortSearch = true;
+    bool overTime =     t > AbsoluteMaxSearchTime
+                     || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
+                     || (  !FailHigh && !fail_high_ply_1() && !Problem
+                         && t > 6*(MaxSearchTime + ExtraSearchTime));
 
-    if(!PonderSearch && Iteration >= 3 && MaxNodes
-       && nodes_searched() >= MaxNodes)
-      AbortSearch = true;
+    if (   (Iteration >= 2 && (!InfiniteSearch && overTime))
+        || (ExactMaxTime && t >= ExactMaxTime)
+        || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
+        AbortSearch = true;
   }