/*
 * Simple card deck simulator which supports cyclical drawing
 * and reshuffling.
 *
 * Written by Timo O. Karjalainen in 2008 and placed in the
 * Public Domain. No rights reserved.
 */

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

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

char deck[52];
int deckpos;

static void init_deck(void)
{
  int i;

  for (i = 0; i < ARRAY_SIZE(deck); i++)
    deck[i] = i;
}

static void shuffle(void)
{
  int i, j, tmp;

  for (i = 0; i < ARRAY_SIZE(deck); i++) {
    j = rand() % ARRAY_SIZE(deck);
    tmp = deck[j];
    deck[j] = deck[i];
    deck[i] = tmp;
  }

  deckpos = 0;
}

static const char * const suits[4] = {
  "spades",
  "clubs",
  "hearts",
  "diamonds"
};

static const char * const names[4] = {
  "jack",
  "queen",
  "king",
  "ace"
};

static void draw(void)
{
  int card, suit, no;

  card = deck[deckpos];
  deckpos = (deckpos + 1) % ARRAY_SIZE(deck);

  suit = card / 13;
  no = card % 13;

  if (no >= 1 && no <= 9)
    printf("%d", no + 1);
  else {
    if (no == 0)
      no = 13;
    printf("%s", names[no - 10]);
  }

  printf(" of %s\n", suits[suit]);
}

int main(void)
{
  srand(time(0));

  init_deck();
  shuffle();

  for (;;) {
    char buf[80];

    printf("deck> ");
    fflush(stdout);

    if (!fgets(buf, sizeof(buf), stdin))
      break;

    if (buf[strlen(buf) - 1] == '\n')
      buf[strlen(buf) - 1] = 0;
    else
      continue;

    if (!strcmp(buf, "draw"))
      draw();
    else if (!strcmp(buf, "shuffle"))
      shuffle();
    else if (!strcmp(buf, "quit"))
      break;
    else
      puts("?? draw|shuffle|quit:");
  }
}

