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

static char buf[80];
static char *string;

/* Listdictionary prints out all words in the dictionary
   begining with a given prefix.
*/
static void print (char *s, register unsigned long i);

static unsigned long wseek (register char *s, unsigned long i);

void listdictionary(char *prefix)
{

    string = buf;
    while (*string++ = *prefix++);
    string--;

 /* Wseek to the start node and call print */
    print (string, wseek (buf, root));
}

/* Wseek takes a string s and a start edge i and follows the edges of
   the dawg pointed to by i labelled by chars from s.  It returns an edge
   into the dawg.
*/

static unsigned long wseek (register char *s, unsigned long i)
{
    if (*s) {
    /* not the null string */
	register unsigned long *p = dawg + ptr(i);
	do {
	    if (chr(*p) == chr(*s))/* Look for an edge */
		return wseek (s + 1, *p);/* Found the edge */
	} while (!last(*p++));
	return 0;		/* No edge - dead state */
    }
    else			/* null string */
	return i;		/* return this edge */
}

/* Print takes a pointer into stringbuf s and a start edge i and prints
   all strings represented by the sub-dawg pointed to by i.
*/

static void print (char *s, register unsigned long i)
{
    if (term(i)) {		/* edge points at a complete word */
	*s = '\0';
	printf ("%s\n", buf);	/* so print the word */
    }
    if (ptr(i))	{		/* Compute index: is it non-zero ? */
        register unsigned long *p = dawg + ptr(i);
	do {			/* for each edge out of this node */
	    *s = chr(*p) + 'a' - 1;
	    print (s + 1, *p);/* recur */
	}
	while (!last(*p++));
    }
}