/* TTYMGR      - tty (terminal) manager
 */

#include "local.h"
#include "bj.h"
#include "hndmgr.h"
#include "ttymgr.h"

#define NMSGS 4
#define LENMSG 15

static bool askedhit = NO;
static bool wanthit = NO;
static char qchar[NMSGS+1] = "dsih";
static char qmsg[NMSGS][LENMSG+1] =
   {  "Double down",
      "Split pair",
      "Insurance",
      "Hit",
   };
static short nmsg[NMSGS] = {0};

/* query  -  get player's response for DBLDN, SPLIT, HIT
 */
short query()
{
   short ask(), val();
   short ret;        /* return from ask() */

   if (val(1, 0) == val(1, 1))
      ret = ask("dsh");
   else
      ret = ask("dh");
   askedhit = (ret != SPLIT);
   wanthit = (ret == HIT);
   if (wanthit)
      ret = NONE;
   return (ret);
}

/* takes    - gets a YES or NO reply to question
 */
bool takes(s)
   char s[];
{
   short ask();
   int strcmp();

   if (askedhit && strcmp(s, "h") == 0) {
      askedhit = NO;
      return(wanthit);
   }
   return (ask(s) != NONE);
}

/* ask      - gets a choice among alternatives
 */
static short ask(s)
   char s[];
{
   bool  isbrief;             /* is prompt brief? */
   char ans[BUFSIZ];          /* player's reply line */
   char c;                    /* player's one-char answer */
   short i;                   /* index over chars of s */
   short j;                   /* index over chars of qchar */
   short slen;                /* length of s */
   static short msglim = 5;   /* verbosity limit */

   unsigned strscn();         /* gives the index of c in s */
   int   strlen();
   void  error();

   isbrief = YES;
   slen = strlen(s);
   for (i = 0; i < slen; ++i) {
      j = strscn(qchar, s[i]);
      if (++nmsg[j] <= msglim)
         isbrief = NO;
   }
   if (isbrief) {
      for (i = 0; i < slen; ++i)
         printf("%c?", s[i]);
      printf("\n");
   }
   FOREVER {
      if (!isbrief) {
         printf("Type\n");
         for (i = 0; i < slen; ++i)
            printf("%c      For %s\n", s[i], qmsg[strscn(qchar, s[i])]);
         printf("RETURN for None\n");
      }
      if (getln(ans, BUFSIZ) == EOF)
         error("Bye!", "");
      c = tolower(ans[0]);
      if (c == '\n')
         return(NONE);
      for (i = 0; i < slen; ++i)
         if (s[i] == c)
            return ((short)(1 + strscn(qchar, c)));
      isbrief = NO;
   }
}

/* strscn      - return the index of c in string s
 */
unsigned strscn(s, c)
   char s[];      /* string to be scanned */
   char c;        /* char to be matched */
{
   register unsigned i;

   for (i = 0; s[i] != c && s[i] != '\0'; ++i)
      ;
   return(i);
}

