// pgnfile.cpp
 
 
 
#include "common.h"
 
 
 
 
 
// handy definitions
 
#define COPY_TIL_LAST_QUOTEMARK(dest,source) \
 
{ \
 
   mbstowcs_s (&converted_count, (dest), WCHAR_SIZEOF (dest), (source), WCHAR_SIZEOF (dest)); \
 
   for (char_index = wcslen (dest) - 1; char_index >= 0; char_index--) \
 
      if ((dest)[char_index] == L'"') \
 
      { \
 
         (dest)[char_index] = 0; \
 
         break; \
 
      } \
 
}
 
 
 
 
 
// global variables used in this module only
 
static char *pgnfile_data = NULL; // mallocated
 
static size_t pgnfile_size = 0;
 
 
 
 
 
// prototypes of local functions
 
static void PGNFile_GameList_Init (int entry_count);
 
static void PGNFile_GameList_Shutdown (void);
 
static char *sgets (char *destination_line, int max_length, char *source_buffer);
 
 
 
 
 
bool PGNFile_Load (const wchar_t *pgnfile_pathname)
 
{
 
   // this function loads a PGN file and builds the game databases of the games described in this file
 
 
 
   char line_buffer[256]; // PGN files have 256 chars max per line by design
 
   char *buffer;
 
   int file_index;
 
   int char_index;
 
   int entry_count;
 
   FILE *fp;
 
   size_t converted_count; // used by the STRING_TO_CHAR macro
 
 
 
   // try to open file for reading in BINARY mode so as NOT to convert end of lines
 
   _wfopen_s (&fp, pgnfile_pathname, L"rb");
 
   if (fp == NULL)
 
      return (false); // on error, cancel
 
 
 
   // get file length
 
   fseek (fp, 0, SEEK_END);
 
   pgnfile_size = ftell (fp);
 
   fseek (fp, 0, SEEK_SET);
 
 
 
   // mallocate space for it and read it all at once
 
   pgnfile_data = (char *) SAFE_realloc (pgnfile_data, 0, pgnfile_size, sizeof (char), false);
 
   fread (pgnfile_data, pgnfile_size, 1, fp);
 
   fclose (fp); // we no longer need the file, so close it
 
 
 
   // now the file is fully loaded in memory
 
 
 
   // read line per line and count the number of games
 
   buffer = pgnfile_data;
 
   entry_count = 0;
 
   while ((buffer = sgets (line_buffer, sizeof (line_buffer), buffer)) != NULL)
 
      if (strncmp (line_buffer, "[Event \"", 8) == 0)
 
         entry_count++; // we know now one game more
 
 
 
   // now prepare the games database for "entry_count" games
 
   PGNFile_GameList_Init (entry_count);
 
 
 
   // read line per line
 
   buffer = pgnfile_data;
 
   entry_count = 0;
 
   file_index = 0;
 
   while ((buffer = sgets (line_buffer, sizeof (line_buffer), buffer)) != NULL)
 
   {
 
      // is it a new game ?
 
      if (strncmp (line_buffer, "[Event \"", 8) == 0)
 
      {
 
         COPY_TIL_LAST_QUOTEMARK (games[entry_count].event_str, &line_buffer[8]); // copy event
 
 
 
         // assume a default "standard chess" start position unless told otherwise later
 
         wcscpy_s (games[entry_count].fen_str, WCHAR_SIZEOF (games[entry_count].fen_str), FENSTARTUP_STANDARDCHESS);
 
 
 
         games[entry_count].gamedata_start = 0; // reset gamedata so far
 
         entry_count++; // we know now one game more
 
      }
 
 
 
      // else have we found a game already ?
 
      else if (entry_count > 0)
 
      {
 
         // is it one of the known tags ?
 
         if (line_buffer[0] == '[')
 
         {
 
            if (strncmp (&line_buffer[1], "Site \"", 6) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].site_str, &line_buffer[7]) // copy site
 
            else if (strncmp (&line_buffer[1], "Date \"", 6) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].date_str, &line_buffer[7]) // copy date
 
            else if (strncmp (&line_buffer[1], "Round \"", 7) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].round_str, &line_buffer[8]) // copy round
 
            else if (strncmp (&line_buffer[1], "White \"", 7) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].white_str, &line_buffer[8]) // copy white
 
            else if (strncmp (&line_buffer[1], "Black \"", 7) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].black_str, &line_buffer[8]) // copy black
 
            else if (strncmp (&line_buffer[1], "Result \"", 8) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].result_str, &line_buffer[9]) // copy results
 
            else if (strncmp (&line_buffer[1], "ECO \"", 5) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].eco_str, &line_buffer[6]) // copy ECO code
 
            else if (strncmp (&line_buffer[1], "FEN \"", 5) == 0)
 
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].fen_str, &line_buffer[6]) // copy FEN string
 
         }
 
 
 
         // else is it the beginning of a game ?
 
         else if (strncmp (line_buffer, "1.", 2) == 0)
 
            games[entry_count - 1].gamedata_start = file_index; // remember where this game starts
 
      }
 
 
 
      file_index = buffer - pgnfile_data; // save current file pointer index
 
   }
 
 
 
   return (true); // finished, return TRUE
 
}
 
 
 
 
 
bool PGNFile_LoadGame (board_t *board, const wchar_t *pgnfile_pathname, pgngame_t *game)
 
{
 
   // this function loads and parses a game data in a PGN file. If the selected game is NULL, it means that
 
   // the user didn't want to chose any game at all, so just free the games list and return a success value.
 
 
 
   static wchar_t pgn_comment[65536]; // declared static so as not to reallocate it
 
 
 
   boardmove_t new_move;
 
   int length;
 
   int char_index;
 
   int fieldstart;
 
   int fieldstop;
 
   int variation_depth;
 
   char movenumber_string[8];
 
 
 
   // did we chose NO game ?
 
   if (game == NULL)
 
   {
 
      PGNFile_GameList_Shutdown (); // free the games list
 
      SAFE_free ((void **) &pgnfile_data); // free the file data space
 
      return (true); // return success as there's nothing to load
 
   }
 
 
 
   // reset the board (but NOT the players, just their view angles)
 
   Board_Reset (board, game->fen_str);
 
   animation_endtime = current_time + 2.0f; // HACK: this sorta prevents the "load file" dialog box trailing clicks to be misinterpreted
 
 
 
   // while we've not parsed til the end of game...
 
   char_index = game->gamedata_start;
 
   new_move.source[0] = -1;
 
   new_move.source[1] = -1;
 
   new_move.target[0] = -1;
 
   new_move.target[1] = -1;
 
   new_move.promotion_type = 0;
 
   pgn_comment[0] = 0;
 
   for (;;)
 
   {
 
      // build the move number string
 
      sprintf_s (movenumber_string, sizeof (movenumber_string), "%d.", 1 + board->move_count / 2);
 
 
 
      // is it a space ?
 
      if (isspace (pgnfile_data[char_index]))
 
      {
 
         char_index++; // if so, skip it
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is what we're reading a move number ?
 
      else if (strncmp (&pgnfile_data[char_index], movenumber_string, strlen (movenumber_string)) == 0)
 
      {
 
         char_index += strlen (movenumber_string); // if so, skip it
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is it a dot ?
 
      else if (pgnfile_data[char_index] == '.')
 
      {
 
         char_index++; // if so, skip it
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is it an en passant notification ?
 
      else if (strncmp (&pgnfile_data[char_index], "e.p.", 4) == 0)
 
      {
 
         char_index += 4; // this notification is superfluous, skip it
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is it a comment ?
 
      else if (pgnfile_data[char_index] == '{')
 
      {
 
         fieldstart = char_index + 1; // skip the leading brace
 
 
 
         while ((fieldstart < (int) pgnfile_size) && isspace (pgnfile_data[fieldstart]))
 
            fieldstart++; // skip any leading spaces
 
 
 
         // move through all the other characters...
 
         for (fieldstop = fieldstart; fieldstop < (int) pgnfile_size; fieldstop++)
 
            if (pgnfile_data[fieldstop] == '}')
 
               break; // and stop at the first closing brace we find
 
 
 
         char_index = fieldstop + 1; // remember where to continue reading (that is, after the closing brace)
 
 
 
         while ((fieldstop > 0) && isspace (pgnfile_data[fieldstop]))
 
            fieldstop--; // chop off any trailing spaces
 
 
 
         pgnfile_data[fieldstop] = 0; // break the string at this location
 
 
 
         // now copy out the commentary by appending it to the one we know already
 
         if (pgn_comment[0] != 0)
 
            wcscat_s (pgn_comment, WCHAR_SIZEOF (pgn_comment), L" ");
 
         length = wcslen (pgn_comment);
 
         ConvertToWideChar (&pgn_comment[length], WCHAR_SIZEOF (pgn_comment) - length, &pgnfile_data[fieldstart]);
 
         ConvertCRLFsToSingleSpaces (pgn_comment); // linearize string
 
 
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is it a numeric annotation glyph ? if so, just ignore it (FIXME: better support this)
 
      else if (pgnfile_data[char_index] == '$')
 
      {
 
         while ((char_index < (int) pgnfile_size) && !isspace (pgnfile_data[char_index]))
 
            char_index++; // figure out where it stops
 
         while ((char_index < (int) pgnfile_size) && isspace (pgnfile_data[char_index]))
 
            char_index++; // figure out where the next word starts
 
 
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is it a variation ? if so, just ignore it (FIXME: better support this)
 
      else if (pgnfile_data[char_index] == '(')
 
      {
 
         variation_depth = 1;
 
         while ((char_index < (int) pgnfile_size) && (variation_depth != 0))
 
         {
 
            char_index++; // move through file data and cope with nested variations
 
            if      (pgnfile_data[char_index] == '(') variation_depth++;
 
            else if (pgnfile_data[char_index] == ')') variation_depth--;
 
         }
 
         char_index++; // skip the closing parenthese
 
         while ((char_index < (int) pgnfile_size) && isspace (pgnfile_data[char_index]))
 
            char_index++; // figure out where the next word starts
 
 
 
         continue; // and proceed to the next data
 
      }
 
 
 
      // else is it a game result ?
 
      else if ((strncmp (&pgnfile_data[char_index], "1/2-1/2", 7) == 0)
 
               || (strncmp (&pgnfile_data[char_index], "1-0", 3) == 0)
 
               || (strncmp (&pgnfile_data[char_index], "0-1", 3) == 0)
 
               || (pgnfile_data[char_index] == '*'))
 
      {
 
         // if there's a move pending, validate it
 
         if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
 
         {
 
            Board_AppendMove (board, new_move.source[0], new_move.source[1], new_move.target[0], new_move.target[1], new_move.promotion_type, pgn_comment); // save move
 
            board->has_playerchanged = true; // switch players
 
            new_move.part = PART_NONE;
 
            new_move.source[0] = -1;
 
            new_move.source[1] = -1;
 
            new_move.target[0] = -1;
 
            new_move.target[1] = -1;
 
            new_move.promotion_type = 0;
 
            pgn_comment[0] = 0; // reset comment
 
         }
 
 
 
         break; // we've finished reading the game
 
      }
 
 
 
      // else it must be a move data
 
      else
 
      {
 
         // if there's a move pending, validate it
 
         if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
 
         {
 
            Board_AppendMove (board, new_move.source[0], new_move.source[1], new_move.target[0], new_move.target[1], new_move.promotion_type, pgn_comment); // save move
 
            board->has_playerchanged = true; // switch players
 
            new_move.part = PART_NONE;
 
            new_move.source[0] = -1;
 
            new_move.source[1] = -1;
 
            new_move.target[0] = -1;
 
            new_move.target[1] = -1;
 
            new_move.promotion_type = 0;
 
            pgn_comment[0] = 0; // reset comment
 
         }
 
 
 
         // convert the move string data to wide char
 
         ConvertToWideChar (new_move.pgntext, WCHAR_SIZEOF (new_move.pgntext), &pgnfile_data[char_index]);
 
 
 
         // evaluate the string in Standard Algebraic Notation and find the source, destination, part type and promotion
 
         if (!Move_SetupFromSAN (&board->moves[board->move_count - 1], &new_move, Board_ColorToMove (board)))
 
         {
 
            PGNFile_GameList_Shutdown (); // free the games list
 
            SAFE_free ((void **) &pgnfile_data); // free the file data space
 
            return (false); // on error, cancel
 
         }
 
 
 
         // find where it stops
 
         while ((char_index < (int) pgnfile_size) && !isspace (pgnfile_data[char_index]))
 
            char_index++; // reach the next space
 
 
 
         char_index++; // remember where to continue reading (that is, after the next space)
 
         continue; // and proceed to the next data
 
      }
 
   }
 
 
 
   // save the players' names
 
   wcscpy_s (board->players[COLOR_WHITE].name, WCHAR_SIZEOF (board->players[COLOR_WHITE].name), game->white_str);
 
   wcscpy_s (board->players[COLOR_BLACK].name, WCHAR_SIZEOF (board->players[COLOR_BLACK].name), game->black_str);
 
 
 
   // we loaded the game we want, we no longer need the games array
 
   PGNFile_GameList_Shutdown ();
 
 
 
   // we no longer need the file data space, so free it
 
   SAFE_free ((void **) &pgnfile_data);
 
 
 
   return (true); // game loaded successfully, return TRUE
 
}
 
 
 
 
 
bool PGNFile_Save (board_t *board, const wchar_t *pgnfile_pathname)
 
{
 
   // this function writes a PGN file in the standard, international Chess format
 
 
 
   FILE *fp;
 
   wchar_t machine_name[256];
 
   unsigned long buffer_size;
 
   wchar_t result_string[16];
 
   time_t rawtime;
 
   struct tm timeinfo;
 
   boardmove_t *move;
 
   int move_index;
 
   int char_index;
 
   int length;
 
   int count;
 
   int consecutive_count;
 
   bool needs_newline;
 
 
 
   // try to open file for writing
 
   _wfopen_s (&fp, pgnfile_pathname, L"w");
 
   if (fp == NULL)
 
      return (false); // on error, cancel
 
 
 
   // get the machine name as an ASCII string
 
   buffer_size = WCHAR_SIZEOF (machine_name);
 
   GetComputerName (machine_name, &buffer_size);
 
 
 
   // get the current date and time
 
   time (&rawtime);
 
   localtime_s (&timeinfo, &rawtime);
 
 
 
   // build the result string
 
   if ((board->game_state == STATE_WHITEWIN_CHECKMATE) || (board->game_state == STATE_WHITEWIN_RESIGNORFORFEIT))
 
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1-0"); // white won
 
   else if ((board->game_state == STATE_BLACKWIN_CHECKMATE) || (board->game_state == STATE_BLACKWIN_RESIGNORFORFEIT))
 
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"0-1"); // black won
 
   else if ((board->game_state == STATE_DRAW_STALEMATE) || (board->game_state == STATE_DRAW_AGREEMENT) || (board->game_state == STATE_DRAW_OTHER))
 
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1/2-1/2"); // game is a draw
 
   else
 
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"*"); // game still in progress
 
 
 
   // write the mandatory header parts
 
   fwprintf (fp, L"[Event \"Chess Giants game\"]\n");
 
   fwprintf (fp, L"[Site \"%s\"]\n", machine_name);
 
   fwprintf (fp, L"[Date \"%d.%02d.%02d\"]\n", 1900 + timeinfo.tm_year, 1 + timeinfo.tm_mon, timeinfo.tm_mday);
 
   fwprintf (fp, L"[Round \"1\"]\n");
 
   fwprintf (fp, L"[White \"%s\"]\n", board->players[COLOR_WHITE].name);
 
   fwprintf (fp, L"[Black \"%s\"]\n", board->players[COLOR_BLACK].name);
 
   fwprintf (fp, L"[Result \"%s\"]\n", result_string);
 
   fwprintf (fp, L"[FEN \"%s\"]\n", board->moves[0].fen_string);
 
   fwprintf (fp, L"\n");
 
 
 
   // now write the game
 
   consecutive_count = 0;
 
   for (move_index = 1; move_index < board->move_count; move_index++)
 
   {
 
      // every seven move pairs, drop a carriage return
 
      if (consecutive_count == 14)
 
      {
 
         fwprintf (fp, L"\n"); // one blank line
 
         consecutive_count = 0;
 
      }
 
 
 
      move = &board->moves[move_index]; // quick access to move
 
 
 
      // white to move ?
 
      if (move->color == COLOR_WHITE)
 
         fwprintf (fp, L"%d.", (move_index + 1) / 2); // if so, display double-move number
 
 
 
      // dump move data
 
      fwprintf (fp, L"%s ", move->pgntext);
 
      consecutive_count++;
 
 
 
      // is there a comment for this move ?
 
      if ((move->comment != NULL) && (move->comment[0] != 0))
 
      {
 
         fwprintf (fp, L"\n{\n"); // dump an open brace
 
         length = wcslen (move->comment); // get comment length
 
 
 
         // for each character in comment text...
 
         needs_newline = false;
 
         count = 0;
 
         for (char_index = 0; char_index < length; char_index++)
 
         {
 
            // is it a space and do we need a newline ?
 
            if (iswspace (move->comment[char_index]) && needs_newline)
 
            {
 
               fputwc (L'\n', fp); // dump a newline
 
               needs_newline = false; // we no longer need a newline
 
               count = 0; // reset the number of characters written
 
            }
 
 
 
            // else it's a character
 
            else
 
            {
 
               fputwc (move->comment[char_index], fp); // dump it
 
               count++; // we dumped one character more on this line
 
               if (count > 80)
 
                  needs_newline = true; // if we need a newline, remember it
 
            }
 
         }
 
 
 
         fwprintf (fp, L"\n}\n"); // dump an open brace
 
         consecutive_count = 0;
 
      }
 
 
 
      // if it's the last move, dump the game results
 
      if (move_index == board->move_count - 1)
 
         fwprintf (fp, result_string);
 
   }
 
 
 
   fclose (fp); // finished, close the file
 
 
 
   return (true); // file saved successfully, return TRUE
 
}
 
 
 
 
 
static void PGNFile_GameList_Init (int entry_count)
 
{
 
   // helper function to initialize the game lists array pointer and the games count
 
 
 
   // allocate space for all the games in a row (it's faster than reallocating)
 
   games = (pgngame_t *) SAFE_malloc (entry_count, sizeof (pgngame_t), true);
 
   game_count = entry_count;
 
 
 
   return; // finished
 
}
 
 
 
 
 
static void PGNFile_GameList_Shutdown (void)
 
{
 
   // helper function to free the game lists array and reset the games count
 
 
 
   SAFE_free ((void **) &games); // free the PGN games array
 
   game_count = 0;
 
 
 
   return; // finished
 
}
 
 
 
 
 
static char *sgets (char *destination_line, int max_length, char *source_buffer)
 
{
 
   // copy a line from a given string. Kinda like fgets() when you're reading from a string.
 
   // use it like:
 
   // while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
 
 
 
   char *pointer;
 
   int char_index;
 
 
 
   if (source_buffer[0] == 0)
 
   {
 
      destination_line[0] = 0;
 
      return (NULL); // if EOS return a NULL pointer
 
   }
 
 
 
   pointer = strchr (source_buffer, '\n'); // get to the first carriage return we can find
 
 
 
   // found none ?
 
   if (pointer == NULL)
 
   {
 
      // if so, copy the line we found
 
      for (char_index = 0; char_index < max_length; char_index++)
 
      {
 
         destination_line[char_index] = source_buffer[char_index]; // copy the line we found
 
         if (source_buffer[char_index] == 0)
 
            break; // don't copy beyond the end of source
 
      }
 
 
 
      if (char_index == max_length)
 
         destination_line[max_length - 1] = 0; // ensure string is terminated
 
 
 
      return (&source_buffer[strlen (source_buffer)]); // and return a pointer to the end of the string
 
   }
 
 
 
   *pointer = 0; // temporarily turn the carriage return to an end of string
 
 
 
   for (char_index = 0; char_index < max_length; char_index++)
 
   {
 
      destination_line[char_index] = source_buffer[char_index]; // copy the line we found
 
      if (source_buffer[char_index] == 0)
 
         break; // don't copy beyond the end of source
 
   }
 
 
 
   destination_line[max_length - 1] = 0; // terminate string
 
   *pointer = '\n'; // put the carriage return back
 
 
 
   return (&pointer[1]); // and return next line's source buffer pointer
 
}