/* 12_hashing.c -- position hashing.
 *
 * Functions demonstrated:
 *   SANHashCreate() -- recompute the current position's hash
 *                      address/signature from scratch
 *   curr_e.e_mhca / curr_e.e_mhcs -- the position's hash address and
 *                      signature, normally maintained *incrementally*
 *                      (updated move by move) rather than recomputed
 *
 * The SAN Kit keeps a running Zobrist-style hash of the position as
 * moves are played, for fast repetition/transposition checks. This
 * example plays a short sequence of moves and then double-checks the
 * incrementally maintained hash against one freshly computed from
 * the raw board with SANHashCreate() -- they must always agree.
 */

#include "_common.h"

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

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

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

  return;
}

int
main (void)
{
  hcpaT incremental_address;
  hcpsT incremental_signature;

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

  play ("d4"); play ("Nf6"); play ("c4"); play ("g6");
  play ("Nc3"); play ("Bg7"); play ("e4"); play ("d6");

  incremental_address = curr_e.e_mhca;
  incremental_signature = curr_e.e_mhcs;

  printf ("Incrementally maintained hash:\n");
  printf ("  address:   %08lx\n", incremental_address);
  printf ("  signature: %08lx\n", incremental_signature);

  SANHashCreate ();

  printf ("Freshly recomputed from the board:\n");
  printf ("  address:   %08lx\n", curr_e.e_mhca);
  printf ("  signature: %08lx\n", curr_e.e_mhcs);

  printf ("\nThey match: %s\n",
          ((incremental_address == curr_e.e_mhca) &&
           (incremental_signature == curr_e.e_mhcs)) ? "yes" : "no");

  return (0);
}
