/* 11_pgn_reading.c -- reading a game from a PGN file.
 *
 * Function demonstrated:
 *   SANRGSingle(filename, &game_count) -- read and replay exactly
 *       one game from a PGN file, leaving the SAN Kit's global game
 *       state (board, tags, history) exactly as it was at the end
 *       of that game.
 *
 * This is the routine behind the interactive "lfer" command and the
 * "tfg*" batch-translation commands (see the user guide); it's the
 * normal entry point for loading an existing game into memory.
 *
 * Usage: 11_pgn_reading <file.pgn>
 */

#include "_common.h"

#include "sanint.h"
#include "sanrdr.h"
#include "sanfen.h"
#include "santag.h"

static void
print_tag (char *name)
{
  tagptrT tagptr;

  tagptr = SANTagLocate (name);
  if ((tagptr != NULL) && (tagptr->tag_value != NULL))
    printf ("  %-8s%s\n", name, tagptr->tag_value);

  return;
}

int
main (int argc, char *argv[])
{
  siT flag, gn;

  if (argc != 2)
    {
      fprintf (stderr, "usage: %s <file.pgn>\n", argv[0]);
      return (1);
    };

  SANInit ();
  optnv[optn_nabd] = 1;
  optnv[optn_namd] = 1;

  flag = SANRGSingle (argv[1], &gn);
  if (!flag)
    {
      fprintf (stderr, "%s: could not read a game from %s\n",
               argv[0], argv[1]);
      return (1);
    };

  printf ("Read %d game(s) from %s. Tags of the last one read:\n",
          gn, argv[1]);
  print_tag ("Event");
  print_tag ("White");
  print_tag ("Black");
  print_tag ("Result");

  printf ("\nFinal position: %s\n", SANFENGen ());

  return (0);
}
