// 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 wchar_t *PGNFile_NAGTextFromCode (int nag_code);
 
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;
 
   char *ptr;
 
   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)
 
      {
 
         memset (&games[entry_count], 0, sizeof (games[entry_count]));
 
         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 a tag ? (i.e: line BEGINS with a opening bracket and the first closing bracket ENDS it)
 
         if ((line_buffer[0] == '[') && (ptr = strchr (line_buffer, ']')) && ((ptr[1] == '\r') || (ptr[1] == 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
 
         else if ((ptr = strstr (line_buffer, "} 1.")) != NULL)
 
            games[entry_count - 1].gamedata_start = (ptr + 2 - pgnfile_data); // 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 nag_code;
 
   int length;
 
   int char_index;
 
   int fieldstart;
 
   int fieldstop;
 
   int program_index;
 
   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
 
   }
 
 
 
   // if either of the players is a chess engine, start it
 
   for (program_index = 0; program_index < options.engine.program_count; program_index++)
 
   {
 
      if (wcscmp (game->black_str, options.engine.programs[program_index].name) == 0)
 
      {
 
         options.engine.selected_program = program_index; // update the preferred chess engine (FIXME: we should not)
 
         Player_Shutdown (&board->players[COLOR_BLACK]);
 
         Player_Init (&board->players[COLOR_BLACK], COLOR_BLACK, PLAYER_COMPUTER);
 
      }
 
      if (wcscmp (game->white_str, options.engine.programs[program_index].name) == 0)
 
      {
 
         options.engine.selected_program = program_index; // update the preferred chess engine (FIXME: we should not)
 
         Player_Shutdown (&board->players[COLOR_WHITE]);
 
         Player_Init (&board->players[COLOR_WHITE], COLOR_WHITE, PLAYER_COMPUTER);
 
      }
 
   }
 
 
 
   // 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 ?
 
      else if (pgnfile_data[char_index] == '$')
 
      {
 
         nag_code = atoi (&pgnfile_data[char_index + 1]); // read it
 
 
 
         // now copy out as a comment
 
         if (pgn_comment[0] != 0)
 
            wcscat_s (pgn_comment, WCHAR_SIZEOF (pgn_comment), L" ");
 
         length = wcslen (pgn_comment);
 
         swprintf_s (&pgn_comment[length], WCHAR_SIZEOF (pgn_comment) - length, L"[NAG: %s]", PGNFile_NAGTextFromCode (nag_code));
 
 
 
         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 wchar_t *PGNFile_NAGTextFromCode (int nag_code)
 
{
 
   // helper function that returns the NAG (numeric annotation glyph) text that corresponds to a particular code
 
 
 
   typedef struct nag_s
 
   {
 
      int code;
 
      wchar_t *text;
 
   } nag_t;
 
   nag_t nag_codes[] = 
 
   {
 
      { 1, L"good move" },
 
      { 2, L"poor move or mistake" },
 
      { 3, L"very good or brilliant move" },
 
      { 4, L"very poor move or blunder" },
 
      { 5, L"speculative or interesting move" },
 
      { 6, L"questionable or dubious move" },
 
      { 7, L"forced move (all others lose quickly) or only move" },
 
      { 8, L"singular move (no reasonable alternatives)" },
 
      { 9, L"worst move" },
 
      { 10, L"drawish position or even" },
 
      { 11, L"equal chances, quiet position" },
 
      { 12, L"equal chances, active position" },
 
      { 13, L"unclear position" },
 
      { 14, L"White has a slight advantage" },
 
      { 15, L"Black has a slight advantage" },
 
      { 16, L"White has a moderate advantage" },
 
      { 17, L"Black has a moderate advantage" },
 
      { 18, L"White has a decisive advantage" },
 
      { 19, L"Black has a decisive advantage" },
 
      { 20, L"White has a crushing advantage (Black should resign)" },
 
      { 21, L"Black has a crushing advantage (White should resign)" },
 
      { 22, L"White is in zugzwang" },
 
      { 23, L"Black is in zugzwang" },
 
      { 24, L"White has a slight space advantage" },
 
      { 25, L"Black has a slight space advantage" },
 
      { 26, L"White has a moderate space advantage" },
 
      { 27, L"Black has a moderate space advantage" },
 
      { 28, L"White has a decisive space advantage" },
 
      { 29, L"Black has a decisive space advantage" },
 
      { 30, L"White has a slight time (development) advantage" },
 
      { 31, L"Black has a slight time (development) advantage" },
 
      { 32, L"White has a moderate time (development) advantage" },
 
      { 33, L"Black has a moderate time (development) advantage" },
 
      { 34, L"White has a decisive time (development) advantage" },
 
      { 35, L"Black has a decisive time (development) advantage" },
 
      { 36, L"White has the initiative" },
 
      { 37, L"Black has the initiative" },
 
      { 38, L"White has a lasting initiative" },
 
      { 39, L"Black has a lasting initiative" },
 
      { 40, L"White has the attack" },
 
      { 41, L"Black has the attack" },
 
      { 42, L"White has insufficient compensation for material deficit" },
 
      { 43, L"Black has insufficient compensation for material deficit" },
 
      { 44, L"White has sufficient compensation for material deficit" },
 
      { 45, L"Black has sufficient compensation for material deficit" },
 
      { 46, L"White has more than adequate compensation for material deficit" },
 
      { 47, L"Black has more than adequate compensation for material deficit" },
 
      { 48, L"White has a slight center control advantage" },
 
      { 49, L"Black has a slight center control advantage" },
 
      { 50, L"White has a moderate center control advantage" },
 
      { 51, L"Black has a moderate center control advantage" },
 
      { 52, L"White has a decisive center control advantage" },
 
      { 53, L"Black has a decisive center control advantage" },
 
      { 54, L"White has a slight kingside control advantage" },
 
      { 55, L"Black has a slight kingside control advantage" },
 
      { 56, L"White has a moderate kingside control advantage" },
 
      { 57, L"Black has a moderate kingside control advantage" },
 
      { 58, L"White has a decisive kingside control advantage" },
 
      { 59, L"Black has a decisive kingside control advantage" },
 
      { 60, L"White has a slight queenside control advantage" },
 
      { 61, L"Black has a slight queenside control advantage" },
 
      { 62, L"White has a moderate queenside control advantage" },
 
      { 63, L"Black has a moderate queenside control advantage" },
 
      { 64, L"White has a decisive queenside control advantage" },
 
      { 65, L"Black has a decisive queenside control advantage" },
 
      { 66, L"White has a vulnerable first rank" },
 
      { 67, L"Black has a vulnerable first rank" },
 
      { 68, L"White has a well protected first rank" },
 
      { 69, L"Black has a well protected first rank" },
 
      { 70, L"White has a poorly protected king" },
 
      { 71, L"Black has a poorly protected king" },
 
      { 72, L"White has a well protected king" },
 
      { 73, L"Black has a well protected king" },
 
      { 74, L"White has a poorly placed king" },
 
      { 75, L"Black has a poorly placed king" },
 
      { 76, L"White has a well placed king" },
 
      { 77, L"Black has a well placed king" },
 
      { 78, L"White has a very weak pawn structure" },
 
      { 79, L"Black has a very weak pawn structure" },
 
      { 80, L"White has a moderately weak pawn structure" },
 
      { 81, L"Black has a moderately weak pawn structure" },
 
      { 82, L"White has a moderately strong pawn structure" },
 
      { 83, L"Black has a moderately strong pawn structure" },
 
      { 84, L"White has a very strong pawn structure" },
 
      { 85, L"Black has a very strong pawn structure" },
 
      { 86, L"White has poor knight placement" },
 
      { 87, L"Black has poor knight placement" },
 
      { 88, L"White has good knight placement" },
 
      { 89, L"Black has good knight placement" },
 
      { 90, L"White has poor bishop placement" },
 
      { 91, L"Black has poor bishop placement" },
 
      { 92, L"White has good bishop placement" },
 
      { 93, L"Black has good bishop placement" },
 
      { 94, L"White has poor rook placement" },
 
      { 95, L"Black has poor rook placement" },
 
      { 96, L"White has good rook placement" },
 
      { 97, L"Black has good rook placement" },
 
      { 98, L"White has poor queen placement" },
 
      { 99, L"Black has poor queen placement" },
 
      { 100, L"White has good queen placement" },
 
      { 101, L"Black has good queen placement" },
 
      { 102, L"White has poor piece coordination" },
 
      { 103, L"Black has poor piece coordination" },
 
      { 104, L"White has good piece coordination" },
 
      { 105, L"Black has good piece coordination" },
 
      { 106, L"White has played the opening very poorly" },
 
      { 107, L"Black has played the opening very poorly" },
 
      { 108, L"White has played the opening poorly" },
 
      { 109, L"Black has played the opening poorly" },
 
      { 110, L"White has played the opening well" },
 
      { 111, L"Black has played the opening well" },
 
      { 112, L"White has played the opening very well" },
 
      { 113, L"Black has played the opening very well" },
 
      { 114, L"White has played the middlegame very poorly" },
 
      { 115, L"Black has played the middlegame very poorly" },
 
      { 116, L"White has played the middlegame poorly" },
 
      { 117, L"Black has played the middlegame poorly" },
 
      { 118, L"White has played the middlegame well" },
 
      { 119, L"Black has played the middlegame well" },
 
      { 120, L"White has played the middlegame very well" },
 
      { 121, L"Black has played the middlegame very well" },
 
      { 122, L"White has played the ending very poorly" },
 
      { 123, L"Black has played the ending very poorly" },
 
      { 124, L"White has played the ending poorly" },
 
      { 125, L"Black has played the ending poorly" },
 
      { 126, L"White has played the ending well" },
 
      { 127, L"Black has played the ending well" },
 
      { 128, L"White has played the ending very well" },
 
      { 129, L"Black has played the ending very well" },
 
      { 130, L"White has slight counterplay" },
 
      { 131, L"Black has slight counterplay" },
 
      { 132, L"White has moderate counterplay" },
 
      { 133, L"Black has moderate counterplay" },
 
      { 134, L"White has decisive counterplay" },
 
      { 135, L"Black has decisive counterplay" },
 
      { 136, L"White has moderate time control pressure" },
 
      { 137, L"Black has moderate time control pressure" },
 
      { 138, L"White has severe time control pressure" },
 
      { 139, L"Black has severe time control pressure" }
 
   };
 
   int nag_index;
 
 
 
   // cycle through all known NAGs and return the text that corresponds to the requested code
 
   for (nag_index = 0; nag_index < sizeof (nag_codes) / sizeof (nag_t); nag_index++)
 
      if (nag_codes[nag_index].code == nag_code)
 
         return (nag_codes[nag_index].text); // return the text as soon as we find it
 
 
 
   return (L"undocumented code"); // not found, return a placeholder string
 
}
 
 
 
 
 
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
 
}