// chessengine.cpp
 
 
 
#include "common.h"
 
 
 
 
 
// global variables used in this module only
 
static wchar_t chessengine_path[MAX_PATH];
 
static wchar_t chessengine_shellcommand[MAX_PATH];
 
static wchar_t chessengineinitfile_pathname[MAX_PATH];
 
static int current_obstinacy;
 
static int max_cores;
 
static bool is_hint_pending;
 
static bool should_initialize;
 
FILE *fpipe;
 
 
 
// prototypes of local functions
 
static void PlayerEngine_Recv (player_t *player);
 
static void PlayerEngine_Send (player_t *player);
 
static wchar_t *Move_BuildString (boardmove_t *move);
 
 
 
 
 
bool PlayerEngine_Init (player_t *player)
 
{
 
   // this function starts a chess engine as a child process. This process's stdin and
 
   // stdout are redirected to the handles we give it, so that we may read/write to it.
 
 
 
   engineprogram_t *program;
 
   wchar_t current_path[MAX_PATH];
 
   wchar_t widechar_buffer[1024];
 
   SYSTEM_INFO sysinfo;
 
   FILE *fp;
 
 
 
   // reset stuff first
 
   player->wants_hint = false;
 
 
 
   // quick access to engine program
 
   program = &options.engine.programs[options.engine.selected_program];
 
 
 
   // build the chess engine module path and pathname
 
   swprintf_s (chessengine_path, WCHAR_SIZEOF (chessengine_path), L"%s/engines/%s", app_path, program->folder);
 
   swprintf_s (chessengine_shellcommand, WCHAR_SIZEOF (chessengine_shellcommand), L"\"%s/%s\" %s", chessengine_path, program->executable_name, program->executable_arguments);
 
 
 
   // start the engine behind a bidirectional I/O pipe
 
   GetCurrentDirectory (WCHAR_SIZEOF (current_path), current_path); // save current directory
 
   SetCurrentDirectory (chessengine_path); // temporarily set chess engine's startup directory as current directory
 
   fpipe = pipe_open (chessengine_shellcommand, L"r+");
 
   SetCurrentDirectory (current_path); // restore current directory
 
   if (fpipe == NULL)
 
   {
 
      messagebox.hWndParent = hMainWnd;
 
      wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
 
      wcscpy_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"));
 
      messagebox.flags = MB_ICONWARNING | MB_OK;
 
      DialogBox_Message (&messagebox); // display a modeless error message box
 
 
 
      PlayerEngine_Shutdown (player); // on error, shutdown the engine
 
      return (false);
 
   }
 
 
 
   // SMP HACK -- save the max CPUs to use to core max - 1 (the computer will look like hung if all CPU is taken)
 
   GetSystemInfo (&sysinfo); // get the number of cores
 
   max_cores = max (1, sysinfo.dwNumberOfProcessors - 1);
 
 
 
   // optionally initialize the debug log file
 
   Debug_Init (L"Chess engine output.txt");
 
   Debug_Log (L"===Using engine: %s [%s]===\n", program->friendly_name, chessengine_shellcommand);
 
 
 
   // build the init file full qualified path name and try to open it
 
   swprintf_s (chessengineinitfile_pathname, WCHAR_SIZEOF (chessengineinitfile_pathname), L"%s/engines/%s/init.txt", app_path, program->folder);
 
   _wfopen_s (&fp, chessengineinitfile_pathname, L"r");
 
 
 
   // could the init file be opened ?
 
   if (fp != NULL)
 
   {
 
      Debug_Log (L"===Found initialization file, parsing...===\n", chessengineinitfile_pathname);
 
 
 
      // read line per line
 
      while (fgetws (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), fp) != NULL)
 
      {
 
         if ((widechar_buffer[0] == L'#') || (widechar_buffer[0] == L'\n'))
 
            continue; // skip comments and empty lines
 
 
 
         // new command line found, append it to the send buffer
 
         Player_SendBuffer_Add (player, 1000, widechar_buffer);
 
      }
 
 
 
      fclose (fp); // finished, close the file
 
   }
 
 
 
   // everything's okay, set engine name as the player's name
 
   wcscpy_s (player->name, WCHAR_SIZEOF (player->name), program->friendly_name);
 
 
 
   should_initialize = true; // remember the engine should be initialized
 
   return (true); // finished
 
}
 
 
 
 
 
void PlayerEngine_Shutdown (player_t *player)
 
{
 
   // this function terminates the chess engine process and releases all handles attached to it
 
 
 
   int attempt_index;
 
 
 
   // send the engine a quit command
 
   Player_SendBuffer_Add (player, 1000, options.engine.programs[options.engine.selected_program].command_quit);
 
   Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
   PlayerEngine_Send (player);
 
 
 
   // check 10 times if the engine process has ended cleanly
 
   for (attempt_index = 0; attempt_index < 10; attempt_index++)
 
   {
 
      if (!pipe_isalive (fpipe))
 
         break; // break as soon as we've told the process exited cleanly
 
 
 
      Sleep (100); // else wait one tenth second
 
   }
 
 
 
   // close the pipe (this will terminate the child process if it hasn't terminated yet)
 
   pipe_close (fpipe);
 
 
 
   Debug_Log (L"===Engine closed===\n");
 
   return; // finished
 
}
 
 
 
 
 
bool PlayerEngine_Think (player_t *player)
 
{
 
   // this function reads and writes any necessary data from and to the chess engine. Returns TRUE if scene needs to be updated.
 
 
 
   engineprogram_t *program;
 
   wchar_t line_buffer[1024];
 
   wchar_t *line_pointer;
 
   wchar_t *move_string;
 
   int char_index;
 
   int length;
 
   boardmove_t move;
 
   player_t *current_player;
 
   player_t *opposite_player;
 
   bool do_update;
 
 
 
   // quick access to chess engine program
 
   program = &options.engine.programs[options.engine.selected_program];
 
 
 
   // don't update the scene until told otherwise
 
   do_update = false;
 
 
 
   // get current and opposite players
 
   current_player = Player_GetCurrent ();
 
   opposite_player = Player_GetOpposite ();
 
 
 
   // is the game still alive AND has the engine just died ?
 
   if ((the_board.game_state == STATE_PLAYING) && !pipe_isalive (fpipe))
 
   {
 
      Debug_Log (L"===Unrecoverable engine error: opponent wins!===\n");
 
 
 
      // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
 
      Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
 
 
 
      // display a crash notification dialog box
 
      if (MessageBox (hMainWnd, LOCALIZE (L"Error_EngineCrashed"), LOCALIZE (L"ImportantMessage"), MB_ICONWARNING | MB_YESNO) == IDYES)
 
         if (Debug_SendLogToAuthor (true))
 
            MessageBox (hMainWnd, LOCALIZE (L"MessageSent"), PROGRAM_NAME, MB_ICONINFORMATION | MB_OK); // send the game engine history to the author
 
         else
 
            MessageBox (hMainWnd, LOCALIZE (L"NoInternetConnection"), LOCALIZE (L"FatalError"), MB_ICONWARNING | MB_OK); // and display an error message if failed
 
 
 
      // and display the game over dialog box
 
      the_board.game_state = (opposite_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
 
      DialogBox_EndGame ();
 
 
 
      do_update = true; // remember to update the 3D scene
 
   }
 
 
 
   // read from pipe (non-blocking)
 
   PlayerEngine_Recv (player);
 
 
 
   ////////////////
 
   // START PARSING
 
 
 
   // read line per line...
 
   line_pointer = player->recvbuffer; // start at the first character
 
   while ((line_pointer = ReadACompleteLine (line_buffer, WCHAR_SIZEOF (line_buffer), line_pointer)) != NULL)
 
   {
 
      // is it an empty line or engine noise ?
 
      if ((line_buffer[0] == 0) || iswspace (line_buffer[0]))
 
         continue; // skip empty lines and engine noise
 
 
 
      // is the engine offering us a draw ?
 
      if (wcsncmp (line_buffer, L"offer draw", 10) == 0)
 
         continue; // if so, discard its offer (engine draws are unsupported) and proceed to the next line
 
 
 
      // else is it an *irrevocable* draw ? (at this point there's nothing we can do but accept it)
 
      else if (wcsstr (line_buffer, L"1/2-1/2") != NULL)
 
      {
 
         Debug_Log (L"===Engine tells us that it's a draw: nobody wins!===\n");
 
 
 
         // play defeat sound (a draw is always a sort of defeat...) at the center of the board
 
         Audio_PlaySound (SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
 
 
 
         // display the game over dialog box
 
         the_board.game_state = STATE_DRAW_OTHER;
 
         DialogBox_EndGame ();
 
 
 
         do_update = true; // remember to update the 3D scene
 
         continue; // we processed that line
 
      }
 
 
 
      // else is the engine *irrevocably* resigning ? (at this point there's nothing we can do but accept it)
 
      else if (wcsncmp (line_buffer, L"resign", 6) == 0)
 
      {
 
         Debug_Log (L"===Engine tells us that %s resigns: %s wins!===\n", (current_player->color == COLOR_BLACK ? "black" : "white"), (current_player->color == COLOR_BLACK ? "white" : "black"));
 
 
 
         // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
 
         Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
 
 
 
         // display the game over dialog box
 
         the_board.game_state = (current_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
 
         DialogBox_EndGame ();
 
 
 
         do_update = true; // remember to update the 3D scene
 
         continue; // we processed that line
 
      }
 
 
 
      // is engine allowed to resign ? if so, check if it's a game results
 
      if (options.engine.obstinacy_level >= 0)
 
      {
 
         // is it a game result AND are we still in play ?
 
         if ((wcsstr (line_buffer, L"1-0") != NULL) && (the_board.game_state == STATE_PLAYING))
 
         {
 
            // have we NOT been obstinate enough ?
 
            if (current_obstinacy < options.engine.obstinacy_level)
 
               current_obstinacy++; // if so, discard this resign and go on
 
            else
 
            {
 
               Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
 
 
 
               // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
 
               Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
 
 
 
               // display the game over dialog box
 
               the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
 
               DialogBox_EndGame ();
 
 
 
               do_update = true; // remember to update the 3D scene
 
            }
 
 
 
            continue; // we processed that line
 
         }
 
         else if ((wcsstr (line_buffer, L"0-1") != NULL) && (the_board.game_state == STATE_PLAYING))
 
         {
 
            // have we NOT been obstinate enough ?
 
            if (current_obstinacy < options.engine.obstinacy_level)
 
               current_obstinacy++; // if so, discard this resign and go on
 
            else
 
            {
 
               Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
 
 
 
               // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
 
               Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
 
 
 
               // display the game over dialog box
 
               the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
 
               DialogBox_EndGame ();
 
 
 
               do_update = true; // remember to update the 3D scene
 
            }
 
 
 
            continue; // we processed that line
 
         }
 
      }
 
 
 
      // has the game ended already ?
 
      if (the_board.game_state > STATE_PLAYING)
 
         continue; // ignore all that the engine tells us. Game is over already.
 
 
 
      // else is it an unrecoverable engine error ?
 
      else if ((wcsstr (line_buffer, L"illegal") != NULL) || (wcsstr (line_buffer, L"invalid") != NULL))
 
      {
 
         Debug_Log (L"===Unrecoverable engine error: opponent wins!===\n");
 
 
 
         // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
 
         Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
 
 
 
         // display a crash notification dialog box
 
         if (MessageBox (hMainWnd, LOCALIZE (L"Error_EngineCrashed"), LOCALIZE (L"ImportantMessage"), MB_ICONWARNING | MB_YESNO) == IDYES)
 
            if (Debug_SendLogToAuthor (true))
 
               MessageBox (hMainWnd, LOCALIZE (L"MessageSent"), PROGRAM_NAME, MB_ICONINFORMATION | MB_OK); // send the game engine history to the author
 
            else
 
               MessageBox (hMainWnd, LOCALIZE (L"NoInternetConnection"), LOCALIZE (L"FatalError"), MB_ICONWARNING | MB_OK); // and display an error message if failed
 
 
 
         // and display the game over dialog box
 
         the_board.game_state = (opposite_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
 
         DialogBox_EndGame ();
 
 
 
         do_update = true; // remember to update the 3D scene
 
      }
 
 
 
      // else is it a normal move ?
 
      else if ((move_string = wcsstr (line_buffer, program->replystring_move)) != NULL)
 
         move_string += wcslen (program->replystring_move); // go to the parsable data
 
 
 
      // else it's any other sort of line
 
      else
 
         continue; // skip lines that don't contain any valid move data
 
 
 
      // now we are sure it's either a hint or a move (or some pondering)
 
 
 
      length = wcslen (move_string);
 
      if (length < 2)
 
         continue; // if string is too short to be a move, skip it
 
 
 
      // there must be valid move data on that line.
 
 
 
      // evaluate the engine move string
 
      memcpy (move.slots, the_board.moves[the_board.move_count - 1].slots, sizeof (move.slots));
 
      char_index = 0;
 
      while ((move_string[char_index] != 0) && !iswspace (move_string[char_index]))
 
      {
 
         move.pgntext[char_index] = move_string[char_index];
 
         char_index++;
 
      }
 
      move.pgntext[char_index] = 0;
 
      if (!Move_SetupFromSAN (&the_board.moves[the_board.move_count - 1], &move, Board_ColorToMove (&the_board)))
 
      {
 
         Debug_Log (L"===Skipping line (invalid move syntax)===\n%s", move_string);
 
         continue; // so now, if there are NOT two digits AND it's not a kind of castle, it can't be a move so skip that line
 
      }
 
 
 
      // is it NOT a hint, are blunders allowed, should we do one now AND can we do one now ?
 
      if (!is_hint_pending && (options.engine.blunder_chances > 0) && (rand () % 100 < options.engine.blunder_chances)
 
          && Move_FindRandomMove (&the_board.moves[the_board.move_count - 1], player->color, &move))
 
      {
 
         if (program->command_force[0] != 0)
 
         {
 
            Player_SendBuffer_Add (player, 1000, program->command_force, Move_BuildString (&move)); // send the blunderous move to the engine
 
            Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
            if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
 
               Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
 
         }
 
         Debug_Log (L"===Discarding engine move, forcing a blunderous move (%s) instead===\n", Move_BuildString (&move)); // blunder
 
      }
 
 
 
      // mark the engine's selected and hovered squares
 
      Board_SetSelectedAndHovered (&the_board, move.source[0], move.source[1], move.target[0], move.target[1]);
 
 
 
      // was it NOT a hint ?
 
      if (!is_hint_pending)
 
      {
 
         the_scene.gui.central_text.disappear_time = current_time + 1.0f; // fade the "thinking" phrase out now (FIXME: ugly)
 
         the_scene.gui.want_spinwheel = false; // stop spinning wheel
 
 
 
         Board_AppendMove (&the_board, the_board.selected_position[0], the_board.selected_position[1], the_board.hovered_position[0], the_board.hovered_position[1], move.promotion_type, NULL);
 
         Player_GetOpposite ()->should_wakeup = true; // do the movement and switch players
 
 
 
         // forget the hovered and selected positions
 
         Board_SetSelectedAndHovered (&the_board, -1, -1, -1, -1);
 
         animation_endtime = current_time + ANIMATION_DURATION; // wait for animation time seconds
 
      }
 
 
 
      // else it was a hint
 
      else
 
      {
 
         the_scene.gui.central_text.disappear_time = current_time + 0.1f; // fade the "thinking" phrase out now quickly (FIXME: ugly)
 
         the_scene.gui.want_spinwheel = false; // stop spinning wheel
 
 
 
         highlight_endtime = current_time + 2.0f; // just highlight this part for a little more than one second
 
         is_hint_pending = false; // remember no hint is pending any longer
 
 
 
         // we must now restore the board to its last state. Just set up the board again from its current Forsyth-Edwards notation
 
         Debug_Log (L"===Hint received, rebuilding board and telling engine to backup 1 move===\n");
 
         Debug_Log (L"===setting up board using FEN string===\n");
 
 
 
         // get the current game state in FEN format and feed it to the engine
 
         Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
 
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
 
 
         if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
 
            Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
 
      }
 
 
 
      do_update = true; // remember to update the 3D scene
 
   }
 
 
 
   // now clean the input buffer of all the lines we parsed
 
   line_pointer = wcsrchr (player->recvbuffer, L'\n'); // reach the last carriage return
 
   if (line_pointer != NULL)
 
   {
 
      line_pointer++; // skip the carriage return
 
      length = wcslen (line_pointer); // get the remaining string length
 
      for (char_index = 0; char_index < length; char_index++)
 
         player->recvbuffer[char_index] = line_pointer[char_index]; // and recopy the remaining string at the beginning of the buffer
 
      player->recvbuffer[char_index] = 0; // finish the string ourselves
 
   }
 
 
 
   // END PARSING
 
   //////////////
 
 
 
   /////////////////////////////////
 
   // START NOTIFICATIONS PROCESSING
 
 
 
   // have we been notified that the board was just set up ?
 
   if (the_board.was_setup)
 
   {
 
      Debug_Log (L"===Got board setup notification from interface===\n");
 
 
 
      // send a new game command to the chess engine
 
      Player_SendBuffer_Add (player, 1000, program->command_new);
 
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
 
 
      // just set up the board from its Forsyth-Edwards notation
 
      Debug_Log (L"===setting up board using FEN string===\n");
 
 
 
      // get the current game state in FEN format and feed it to the engine
 
      Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
 
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
 
 
      current_obstinacy = 0; // reset current obstinacy
 
      is_hint_pending = false; // no hint was requested so far
 
 
 
      if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
 
         Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
 
   }
 
 
 
   // have we been notified that players are swapping colors ? (N.B. when this happens in human vs. computer mode, it's always that the human player is *GIVING* his turn)
 
   if (the_board.want_playerswap)
 
   {
 
      Debug_Log (L"===Got player SWAP notification from interface===\n");
 
      Player_SendBuffer_Add (player, 1000, program->command_go); // tell engine it's now the current player
 
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
   }
 
 
 
   // have we been notified that the current player just changed AND is the animation finished ?
 
   if (player->should_wakeup && (animation_endtime < current_time))
 
   {
 
      Debug_Log (L"===Got player change notification from interface===\n");
 
 
 
      // is the current player our color ? (meaning is it engine's turn to play) ?
 
      if (Board_ColorToMove (&the_board) == player->color)
 
      {
 
         // is it NOT a board setup AND has at least one move been played (meaning it was just the other's turn before) ?
 
         if (!the_board.was_setup && (the_board.move_count > 1))
 
         {
 
            Debug_Log (L"===Player just played, sending the chosen move to engine===\n");
 
            if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
 
               Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
 
 
 
            // build the move string, and send the move string to the engine
 
            Player_SendBuffer_Add (player, 1000, program->command_move, Move_BuildString (&the_board.moves[the_board.move_count - 1]));
 
            Player_SendBuffer_Add (player, 1000, L"\n"); // end the send buffer with a carriage return
 
         }
 
 
 
         // else game has not started yet, but it's our turn
 
         else
 
         {
 
            Player_SendBuffer_Add (player, 1000, program->command_go); // so let's start the game
 
            Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
         }
 
      }
 
 
 
      player->should_wakeup = false; // remember we taken this notification in account
 
   }
 
 
 
   // END NOTIFICATIONS PROCESSING
 
   ///////////////////////////////
 
 
 
   // is it NOT our turn ?
 
   if (current_player != player)
 
   {
 
      // does our opponent want a hint ?
 
      if (current_player->wants_hint)
 
      {
 
         current_player->wants_hint = false; // don't ask twice
 
         Debug_Log (L"===Hint requested, asking engine for it===\n");
 
         Player_SendBuffer_Add (player, 1000, program->command_go); // tell the computer to analyze this position
 
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
         is_hint_pending = true; // remember a hint is pending
 
 
 
         // FIXME: move to scene.cpp
 
         Scene_UpdateText (&the_scene.gui.central_text, RGBA_TO_RGBACOLOR (255, 255, 255, 191), DURATION_INFINITE, true, LOCALIZE (L"Thinking")); // display the "thinking" phrase in the middle of the screen
 
         the_scene.gui.want_spinwheel = true; // start spinning wheel
 
         do_update = true; // remember to update the 3D scene
 
      }
 
 
 
      // does our opponent want to cancel a move ?
 
      if (current_player->wants_cancel)
 
      {
 
         current_player->wants_cancel = false; // don't ask twice (remember now before we switch players)
 
         Debug_Log (L"===Move cancellation requested, rebuilding board and telling engine to backup 2 moves===\n");
 
 
 
         // rewind game 2 moves back
 
         the_board.moves = (boardmove_t *) SAFE_realloc (the_board.moves, the_board.move_count, max (1, the_board.move_count - 2), sizeof (boardmove_t), false);
 
         the_board.move_count = max (1, the_board.move_count - 2); // figure out how many moves we have now
 
         the_board.viewed_move = the_board.move_count - 1; // take us back to the last move
 
         the_board.game_state = STATE_PLAYING; // remember the game is now playing (in case we wanted to cancel the closing move of a finished game, this opens the game again)
 
 
 
         // just set up the board from its Forsyth-Edwards notation
 
         Debug_Log (L"===setting up board using FEN string===\n");
 
 
 
         // get the current game state in FEN format and feed it to the engine
 
         Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
 
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
 
 
 
         if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
 
            Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
 
 
 
         do_update = true; // remember to update the 3D scene
 
      }
 
   }
 
 
 
   // write to pipe (when we're allowed to)
 
   if (!player->sendbuffer_locked && (animation_endtime + 1.0f < current_time))
 
      PlayerEngine_Send (player);
 
 
 
   return (do_update); // finished, return whether we should update the scene or not
 
}
 
 
 
 
 
static void PlayerEngine_Recv (player_t *player)
 
{
 
   // helper function to read data from the pipe communicating with the game engine process
 
 
 
   //unsigned long amount_to_read;
 
   unsigned long read_count;
 
   int length;
 
   unsigned int initial_pos;
 
 
 
   // get reception buffer's initial end position
 
   initial_pos = wcslen (player->recvbuffer);
 
   length = initial_pos;
 
 
 
   // as long as the pipe reports us there is data to read, read one byte at a time
 
   while (pipe_hasdata (fpipe))
 
   {
 
      read_count = pipe_read (fpipe, player->ascii_recvbuffer, 1);
 
      if (read_count == 0)
 
         break; // read the pipe; if it fails, stop trying
 
      if ((player->ascii_recvbuffer[0] == '\r') || (player->ascii_recvbuffer[0] == '%'))
 
         continue; // ignore carriage returns and percent signs
 
 
 
      // convert the received character to wide char and append it to recvbuffer
 
      player->ascii_recvbuffer[1] = 0; // terminate the received string ourselves
 
      player->recvbuffer[length] = (wchar_t) player->ascii_recvbuffer[0];
 
      //ConvertToWideChar (&player->recvbuffer[length], player->recvbuffer_size - length, player->ascii_recvbuffer);
 
      length++; // there's one more character in the player's recv buffer
 
      player->recvbuffer[length] = 0; // terminate the string ourselves
 
   }
 
 
 
   // write what we received (if we received anything)
 
   if (wcslen (player->recvbuffer) > initial_pos)
 
      Debug_Log (L"===================================RECEIVED:===================================\n%s\n", &player->recvbuffer[initial_pos]);
 
 
 
   return; // finished
 
}
 
 
 
 
 
int wcs_replace (wchar_t *haystack, wchar_t *needle, wchar_t *replacement)
 
{
 
   size_t replacement_length;
 
   size_t replacement_count;
 
   size_t pattern_length;
 
   wchar_t *line_pointer;
 
 
 
   replacement_count = 0;
 
   while ((line_pointer = wcsstr (haystack, needle)) != NULL)
 
   {
 
      pattern_length = wcslen (needle);
 
      replacement_length = wcslen (replacement);
 
      memmove (&line_pointer[replacement_length], &line_pointer[pattern_length], (wcslen (&line_pointer[pattern_length]) + 1) * sizeof (wchar_t));
 
      memcpy (line_pointer, replacement, replacement_length * sizeof (wchar_t));
 
      replacement_count++;
 
   }
 
 
 
   return (replacement_count);
 
}
 
 
 
 
 
static void PlayerEngine_Send (player_t *player)
 
{
 
   // helper function to send data through the pipe communicating with the game engine process
 
 
 
   static wchar_t replacement_string[65536];
 
   static wchar_t widechar_buffer[65536]; // needs to be big enough to hold game history
 
   static char ascii_buffer[65536]; // needs to be big enough to hold game history
 
   wchar_t *line_pointer;
 
   unsigned long amount_written;
 
   int move_index;
 
   int try_index;
 
 
 
   player->sendbuffer_locked = true; // lock the buffer
 
 
 
   // perform variable replacements on sendbuffer
 
   if (the_board.move_count > 0)
 
   {
 
      wcs_replace (player->sendbuffer, L"${CURRENT_POS}", (/*the_board.move_count == 2 ? L"startpos" : */the_board.moves[the_board.move_count - 1].fen_string));
 
      wcs_replace (player->sendbuffer, L"${LAST_MOVE}", Move_BuildString (&the_board.moves[the_board.move_count - 1]));
 
      while (wcsstr (player->sendbuffer, L"${MAX_CORES}") != NULL)
 
      {
 
         swprintf_s (replacement_string, WCHAR_SIZEOF (replacement_string), L"%d", max_cores);
 
         wcs_replace (player->sendbuffer, L"${MAX_CORES}", replacement_string);
 
      }
 
      while (wcsstr (player->sendbuffer, L"${SEARCH_DEPTH}") != NULL)
 
      {
 
         swprintf_s (replacement_string, WCHAR_SIZEOF (replacement_string), L"%d", options.engine.depth);
 
         wcs_replace (player->sendbuffer, L"${SEARCH_DEPTH}", replacement_string);
 
      }
 
      while (wcsstr (player->sendbuffer, L"${GAME_HISTORY}") != NULL)
 
      {
 
         replacement_string[0] = 0;
 
         for (move_index = 1; move_index < the_board.move_count; move_index++)
 
         {
 
            if (move_index > 1)
 
               wcscat_s (replacement_string, WCHAR_SIZEOF (replacement_string), L" ");
 
            wcscat_s (replacement_string, WCHAR_SIZEOF (replacement_string), Move_BuildString (&the_board.moves[move_index]));
 
         }
 
         wcs_replace (player->sendbuffer, L"${GAME_HISTORY}", replacement_string);
 
      }
 
   }
 
 
 
   // write what we're sending (if we're sending anything)
 
   if (player->sendbuffer[0] != 0)
 
      Debug_Log (L"====================================SENDING:===================================\n%s\n", player->sendbuffer);
 
 
 
   // now read line per line...
 
   line_pointer = player->sendbuffer; // start at the first character
 
   while ((line_pointer = wcsgets (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), line_pointer)) != NULL)
 
   {
 
      wcscat_s (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), L"\n"); // put the carriage return back
 
      ConvertTo7BitASCII (ascii_buffer, sizeof (ascii_buffer), widechar_buffer); // convert to ASCII
 
      amount_written = pipe_write (fpipe, ascii_buffer, strlen (ascii_buffer)); // send data
 
   }
 
 
 
   player->sendbuffer[0] = 0; // what we had to send has been sent, reset the send buffer
 
   player->sendbuffer_locked = false; // and unlock it
 
 
 
   // should the engine be initialized ?
 
   if (should_initialize)
 
   {
 
      // wait for the engine process to display something (which will mean it's ready). Try for 5 seconds.
 
      for (try_index = 0; try_index < 50; try_index++)
 
      {
 
         // read from pipe (non-blocking)
 
         PlayerEngine_Recv (player);
 
         if (player->recvbuffer[0] != 0)
 
            break; // break as soon as we get something
 
         Sleep (100); // next try in 100 milliseconds
 
      }
 
 
 
      // has the engine process not spoken yet ?
 
      if (player->recvbuffer[0] == 0)
 
      {
 
         messagebox.hWndParent = hMainWnd;
 
         wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
 
         swprintf_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"), options.engine.programs[options.engine.selected_program].folder);
 
         messagebox.flags = MB_ICONWARNING | MB_OK;
 
         DialogBox_Message (&messagebox); // display a modeless error message box
 
 
 
         PlayerEngine_Shutdown (player); // on error, shutdown the engine
 
      }
 
 
 
      should_initialize = false; // remember this is no longer to be done (until the next call to PlayerEngine_Init())
 
   }
 
 
 
   return; // finished
 
}
 
 
 
 
 
static wchar_t *Move_BuildString (boardmove_t *move)
 
{
 
   // helper function to build a move string to send to the engine from a particular board move. NOT THREAD SAFE.
 
 
 
   static wchar_t output_string[8];
 
 
 
   // construct the four first characters
 
   swprintf_s (output_string, WCHAR_SIZEOF (output_string), L"%c%c%c%c",
 
               L'a' + move->source[1], L'1' + move->source[0],
 
               L'a' + move->target[1], L'1' + move->target[0]);
 
 
 
   // append any eventual promotion
 
   if (move->promotion_type == PART_ROOK)
 
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"r");
 
   else if (move->promotion_type == PART_KNIGHT)
 
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"n");
 
   else if (move->promotion_type == PART_BISHOP)
 
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"b");
 
   else if (move->promotion_type == PART_QUEEN)
 
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"q");
 
 
 
   return (output_string); // finished, return the move string
 
}