
#ifdef IMPEL_GAVIOTA_DEBUG
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include "GaviotaDebug.h"

void * so_file;

char* (*GaviotaDebug_TB_Init) (int, int, const char **);
void (*GaviotaDebug_TB_Done) (void);
const char ** (*GaviotaDebug_TB_PathsInit) (void);
const char ** (*GaviotaDebug_TB_PathsAdd) (const char **, const char *);
const char ** (*GaviotaDebug_TB_PathsDone) (void);

void (*GaviotaDebug_TB_StatsReset) (void);

int (*GaviotaDebug_TB_CacheInit) (size_t, int);
void (*GaviotaDebug_TB_CacheDone) (void);

void GaviotaDebugSetUp ()
{
  const char ** paths;
  char *path1 = "gtb/gtb4"; /* valid */
  so_file = dlopen ("libGaviota.so", RTLD_LAZY);
  if (!so_file)
    {
      printf ("Buys not the libGaviota.so under debuggery?\n");
      exit (9);
    }
  GaviotaDebug_TB_Init = dlsym (so_file, "tb_init");
  GaviotaDebug_TB_Done = dlsym (so_file, "tb_done");
  GaviotaDebug_TB_StatsReset = dlsym (so_file, "tbstats_reset");

  GaviotaDebug_TB_PathsInit = dlsym (so_file, "tbpaths_init");
  GaviotaDebug_TB_PathsAdd = dlsym (so_file, "tbpaths_add");
  GaviotaDebug_TB_PathsDone = dlsym (so_file, "tbpaths_done");

  GaviotaDebug_TB_CacheDone = dlsym (so_file, "tbcache_done");
  GaviotaDebug_TB_CacheInit = dlsym (so_file, "tbcache_init");

  GaviotaDebug_TB_ProbeSoft = dlsym (so_file, "tb_probe_soft");
  GaviotaDebug_TB_ProbeHard = dlsym (so_file, "tb_probe_hard");
  GaviotaDebug_TB_ProbeSoftWDL = dlsym (so_file, "tb_probe_WDL_soft");
  GaviotaDebug_TB_ProbeHardWDL = dlsym (so_file, "tb_probe_WDL_hard");

  paths = (*GaviotaDebug_TB_PathsInit) ();
  paths = (*GaviotaDebug_TB_PathsAdd) (paths, path1);

  (*GaviotaDebug_TB_Init) (0, 4, paths);
  (*GaviotaDebug_TB_CacheInit) ((32 << 20), 96);
  (*GaviotaDebug_TB_StatsReset) ();
}

void GaviotaBugTrap /* value ? */
(unsigned stm, SQUARE ep,
 const SQUARE * wsq, const SQUARE * bsq,
 const SQ_CONTENT * wpi, const SQ_CONTENT * bpi,
 unsigned res1, unsigned res2)
{
  int i = 0;
  char P[8] = "0PNBRQK";
  printf ("GaviotaBugTrap stm:%d ep:%d ", stm, ep);
  while (wpi[i] != 0)
    {
      printf ("w%c%c%c ", P[wpi[i]], 'a' + (wsq[i] & 07), '0' + (wsq[i] >> 3));
      i++;
    }
  i = 0;
  while (bpi[i] != 0)
    {
      printf ("b%c%c%c ", P[bpi[i]], 'a' + (bsq[i] & 07), '0' + (bsq[i] >> 3));
      i++;
    }
  printf ("res1:%d res2:%d\n", res1, res2);
  /* raise (SIGTRAP); */
  exit (9);
}

void GaviotaScrub ()
{
  (*GaviotaDebug_TB_CacheDone) ();
  (*GaviotaDebug_TB_Done) ();
  (*GaviotaDebug_TB_PathsDone) ();
  dlclose (so_file);
}
#endif
