#include <stdio.h>
#include "globals.h"
#include "trie.h"

unsigned row, column;

unsigned long (*check)[17], *checkrow;
char       (*fill)[17],  *fillrow;
int        (*trans)[17], *transrow;

void prefix(register unsigned long loc, int lim);
void extend (register unsigned int loc, register unsigned int col);

void firstmove(void)
{
    check = acheck;
    fill = afill;
    fillrow = fill[8];
    checkrow = check[8];
    trans = atrans;
    transrow = trans[8];
    row = 8;
    column = 8;
    prefix(root, 6);
}

char currentmovearea[10]={0}, *currentmove=currentmovearea;

void putp (unsigned long (*xcheck)[17], char (*xfill)[17], int (*xtrans)[17])
{
    int     lastanchor;

    check = xcheck;
    fill = xfill;
    trans = xtrans;
    for (row = 1; row <= 15; row++) {
	checkrow = check[row];
	fillrow = fill[row];
	lastanchor = 0;
	for (column = 1; column <= 15; column++)
	    if (!fillrow[column]
		    && (fill[row - 1][column] | fill[row + 1][column]
			| fillrow[column - 1] | fillrow[column + 1])
		) {
		if (fillrow[column - 1])
		    extend (root, lastanchor + 1);
		else
		    prefix (root, column - lastanchor - 1);
		lastanchor = column;

	    }
    }
}

void prefix(register unsigned long loc, int lim)
{
   register unsigned long *l;

   extend(unterm(loc), column);
   if (lim && ptr (loc)) {
	    l = dawg + ptr (loc);
	    do {register d, c = chr (*l);
		    if (rack[c])
			rack[d = c]--;
		    else if (rack[BLANK]) {
			c |= BLANKBIT;
			rack[d = BLANK]--;
		    }
		    else continue;
		    *++currentmove = c;
		    prefix(*l, lim-1);
		    currentmove--;
		    rack[d]++;
	    } while (!last (*l++));
   }
}

void extend (register unsigned int loc, register unsigned int col)
{
    register unsigned long *l,
                        c,
                        d;
    if (fillrow[col] && ptr (loc)) {
	l = dawg + ptr (loc);
	do 
	   if (chr (*l) >= chr (fillrow[col]))
		if (chr (*l) == chr (fillrow[col]))
		    extend (*l, col + 1);
		else
		    return;
	while (!last (*l++));
    }
    else {
	if (term (loc) && !fillrow[col])
	    eval (fill, trans, row, col);
	if (ptr (loc)) {
	    l = dawg + ptr (loc);
	    do {
		c = chr (*l);
		if (checkrow[col] & (1 << c)) {
		    if (rack[c])
			rack[d = c]--;
		    else if (rack[BLANK]) {
			c |= BLANKBIT;
			rack[d = BLANK]--;
		    }
		    else continue;
		    *++currentmove = c;
		    extend (*l, col + 1);
		    currentmove--;
		    rack[d]++;
		}
	    } while (!last (*l++));
	}
    }
}