/*>>> sangtc.c: SAN project game termination handling  */

/* Revised: 1993.05.16 */

#include <stdio.h>
#include <string.h>
#include <time.h>

#include "sandef.h"
#include "sanvar.h"

#include "sangtc.h"
#include "sanrst.h"
#include "santag.h"
#include "sanutl.h"

/*--> SANGTCDetermine: check if new gtc available from input gtim */
nonstatic
gtcT
SANGTCDetermine (gtimT gtim)
{
  gtcT new_gtc;

  if (gtim == gtim_nil)
    new_gtc = gtc_nil;
  else
    {
      new_gtc = cv_gtc_gtimv[gtim];
      if (new_gtc == gtc_nil)
	switch (gtim)
	  {
	  case gtim_res0:
	  case gtim_res1:
	    if (curr_e.e_actc == c_w)
	      new_gtc = gtc_bwin;
	    else
	      new_gtc = gtc_wwin;
	    break;

	  default:
	    SANSwitchFault ("SANGTCDetermine");
	    break;
	  };
    };

  return (new_gtc);
}

/*--> SANGTCConsistent: check if new gtc is consistent with environment */
nonstatic
siT
SANGTCConsistent (gtcT new_gtc)
{
  siT flag;
  gsT gs;

  gs = SANStatus ();
  flag = 0;
  switch (new_gtc)
    {
    case gtc_norm:
      flag = (gs == gs_norm) ||
	(gs == gs_wres) || (gs == gs_bres) || (gs == gs_dagr);
      break;

    case gtc_draw:
      switch (gs)
	{
	case gs_dhmc:
	case gs_drep:
	case gs_dmat:
	case gs_dagr:
	case gs_wsmt:
	case gs_bsmt:
	case gs_norm:
	  flag = 1;
	  break;

	default:
	  flag = 0;
	  break;
	};
      break;

    case gtc_wwin:
      flag = (((gs == gs_norm) && (curr_e.e_actc == c_b)) ||
	      (gs == gs_bcmt));
      break;

    case gtc_bwin:
      flag = (((gs == gs_norm) && (curr_e.e_actc == c_w)) ||
	      (gs == gs_wcmt));
      break;

    default:
      SANSwitchFault ("SANGTCConsistent");
      break;
    };

  return (flag);
}

/*--> SANGTCSet: set the new game termination code */
nonstatic
void
SANGTCSet (gtcT new_gtc)
{
  gtc = new_gtc;
  SANTagUpdate (SANTagLocate (rsvtagv[rsvtag_result]), gtcstrv[gtc]);

  return;
}

/*--> SANGTCAutoSet: check and set a new game termination code */
nonstatic
void
SANGTCAutoSet (void)
{
  gsT gs;

  if (gtc == gtc_norm)
    {
      gs = SANStatus ();
      if (gs != gs_norm)
	switch (gs)
	  {
	  case gs_bust:
	    SANGTCSet (gtc_norm);
	    break;

	  case gs_wsmt:
	  case gs_bsmt:
	  case gs_dhmc:
	  case gs_drep:
	  case gs_dmat:
	  case gs_over:
	    SANGTCSet (gtc_draw);
	    break;

	  case gs_wcmt:
	    SANGTCSet (gtc_bwin);
	    break;

	  case gs_bcmt:
	    SANGTCSet (gtc_wwin);
	    break;

	  default:
	    SANSwitchFault ("SANGTCAutoSet");
	    break;
	  };
    };

  return;
}

/*--> SANMatchGTIM: match string as a game termination imput marker */
nonstatic
gtimT
SANMatchGTIM (charptrT s)
{
  gtimT gtim;
  siT flag;

  if (strlen (s) == 0)
    gtim = gtim_nil;
  else
    {
      flag = 0;
      gtim = 0;
      while (!flag && (gtim < gtimL))
	{
	  if (strcmp (s, gtimstrv[gtim]) == 0)
	    flag = 1;
	  else
	    gtim++;
	};
      if (!flag)
	gtim = gtim_nil;
    };

  return (gtim);
}

/*<<< gt.c: EOF */
