#include "crab.h"
#include "tiles.h"

static char lettervalue[NTILE + 1] =
/*  a b c d  e f g h i j k l m n o p  q r s t u v w x y  z # */
 {0,1,3,3,2, 1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10,0};

char quantity[NTILE + 1] =
/*  a b c d  e f g h i j k l m n o p  q r s t u v w x y  z # */
 {0,9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2, 1,6,4,6,4,2,2,1,2, 1,2};

struct tiles sock;
char value[BLANKBIT + NTILE + 1];

initsock ()
{
    int i;

    sock.total = 0;
    for (i = 0; i < NTILE + 1; i++) {
		sock.total += sock.count[i] = quantity[i];
		value [i] = lettervalue[i];
		value [BLANKBIT + i] = 0;
	}
}

initrack (r) struct tiles *r;
{
    int i;

    r -> total = 0;
   
    for (i = 0; i < NTILE + 1; i ++)
        r -> count[i] = 0;
}    

add_tile (s, t) struct tiles *s; char t;
{
    s -> count [TILE (t)]++;
    s -> total++;
	fixtiles (TILE (t), s);
}

addtiles (r, m) struct tiles *r; struct move *m;
{
    char *t = m -> tiles;
    while (*t)
        add_tile (r, *t++);
}

remove_tile (s, t) struct tiles *s; char t;
{
    s -> count [TILE (t)]--;
    s -> total--;
}    

removetiles (r, m) struct tiles *r; struct move *m;
{
    char *t = m -> tiles;
    while (*t)
        remove_tile (r, *t++);
}

char random_tile (s) struct tiles *s;
{
    register n = randint (s -> total);
    register char *t = s -> count;

    while (n >= 0)
        n -= *++t;

    return t - s -> count;
}

fillrack (s) struct tiles *s;
{
    while (sock.total && s -> total < RACKSIZE) {
	register t = random_tile (&sock);
	remove_tile (&sock, t);
	add_tile (s, t);
    }
}

rackpoints (r) struct tiles *r;
{
	int i, points;

	points = 0;
    for (i = 0; i < NTILE + 1; i ++)
        points += r -> count[i] * lettervalue[i];
	return points;
}
