/* 05_play_unplay.c -- playing and retracting moves, and game history.
 *
 * Functions demonstrated:
 *   SANPlayMove()   -- play a legal move (updates board, history,
 *                      hash, active color, move counters...)
 *   SANUnplayMove() -- undo the most recently played move
 *   hn              -- global count of moves currently on the
 *                      history stack (declared in sanvar.h)
 *
 * SANPlayMove()/SANUnplayMove() are the "game level" way to make and
 * take back moves: they maintain the move-history stack (used for
 * repetition detection and for producing PGN game text) as well as
 * the board itself. This is different from the lower-level
 * SANExecute()/SANRetract() pair used internally by search routines
 * such as SANEnumerate() (see 07_perft_enumerate.c), which do not
 * touch the history stack.
 */

#include "_common.h"

#include "sanint.h"
#include "sanmnd.h"
#include "sanmpu.h"
#include "sanfen.h"

static void
play (const char *text)
{
  sanT buf;
  mptrT mptr;

  strncpy (buf, text, sanL - 1);
  buf[sanL - 1] = '\0';

  mptr = SANDecodeAux (buf);
  if (mptr == NULL)
    {
      fprintf (stderr, "not a legal move: %s\n", text);
      exit (1);
    };
  SANPlayMove (mptr);

  return;
}

int
main (void)
{
  SANInit ();
  optnv[optn_nabd] = 1;
  optnv[optn_namd] = 1;

  printf ("moves on history stack: %d\n", hn);

  play ("e4");
  play ("e5");
  play ("Nf3");
  printf ("after 1.e4 e5 2.Nf3   : %s  (history: %d)\n",
          SANFENGen (), hn);

  SANUnplayMove ();
  printf ("after retracting 2.Nf3: %s  (history: %d)\n",
          SANFENGen (), hn);

  SANUnplayMove ();
  SANUnplayMove ();
  printf ("after retracting all  : %s  (history: %d)\n",
          SANFENGen (), hn);

  return (0);
}
