#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "scrabble.h"

void
printdict(int node, int pos)
{
/* Print the whole dictionary in human readable form for debug.
 */
	int		edge;
	char	buf[LLEN];

	do {
		edge = dict[node++];
		buf[pos] = LET(edge)+'a';
		if(TERM(edge))
			print("%.*s\n", pos+1, buf);
		if(NODE(edge))
			printdict(NODE(edge), pos+1);
	} while (!LAST(edge));
}

void
initdict(char *fname)
{
/* Read dictionary in text form into "dict" aray.
 */
	FILE	*fp;
	char	buf[LLEN];
	int	j;
	
	fp = fopen(fname, "r");
	if (!fp)
		error("open %s", fname);

	fgets(buf, LLEN, fp);

	if(sscanf(buf, "%d %d", &total, &root) != 2)
		error("invalid dfa header");

	DPRINT("total %d root %d\n", total, root);

	dict = (int*) malloc((total+2)*sizeof(int));
	if(!dict)
		error("malloc DFA");

	j=1;
	while(fgets(buf, LLEN, fp)){
		assert(j<=total);
		dict[j++] = atoi(buf);
	}
}

void
initbinary(char *fname)
{
/* Read dictionary in binary form into "dict" aray.
 */
	int		fd,s;

	print("INBINARY\n");
	fd = open(fname, O_RDONLY);
	if(fd<0)
		error("open %s", fname);

	s = sizeof(int);
	if(read(fd, &total, s)<s)
		error("read total");
	if(read(fd, &root, s)<s)
		error("read root");

	s =  (total+2)*sizeof(int);
	dict = (int*) malloc(s);
	if(!dict)
		error("malloc dict");

	if(read(fd, dict, s)<s)
		error("read array");
	close(fd);
}

void
outbinary(char *fname)
{
/* Convert dictionary in text form to binary form.
 * This is simply to make startup faster.
 */
	char	newname[100];
	int		fd,s;

	print("OUTBINARY\n");
	sprint(newname, "%s%s", fname, ".BIN");
	fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if(fd<0)
		error("create %s", newname);

	s = sizeof(int);
	if(write(fd, &total, s)<s)
		error("write total");
	if(write(fd, &root, s)<s)
		error("write root");
	s =  (total+2)*sizeof(int);
	if(write(fd, dict, s)<s)
		error("write dict");
	close(fd);
	exits(0);
}

