/* -*- Mode:Text -*- */
/*
 * lookup.c - see if a word appears in the dictionary
 *
 * Pace Willisson, 1983
 */

#include <stdio.h>
#include <ctype.h>
#include "ispell.h"


struct dent *hashtbl;
int hashsize;
char *hashstrings;
struct dent *lastdent;

static inited = 0;

linit ()
{
	int hashfd;
	struct hashheader hashheader;
	char hashname[100];

#ifdef AMIGA
	strcat (hashname, "ISPELL:ispell.hash");
#else
	strcpy (hashname, LIBDIR);
	strcat (hashname, "/ispell.hash");
#endif

	if (inited)
		return;

	if ((hashfd = open ("ispell.hash", 0)) < 0 &&
	    (hashfd = open (hashname, 0)) < 0) {
		fprintf (stderr, "can't open %s\r\n", hashname);
		return (-1);
	}

	read (hashfd, &hashheader, sizeof hashheader);

	if (hashheader.magic != MAGIC) {
		fprintf (stderr, "Illegal format hash table\r\n");
		return (-1);
	}
	hashstrings = (char *) malloc (hashheader.stringsize);
	hashtbl = (struct dent *) malloc (hashheader.tblsize * sizeof (struct dent));
	hashsize = hashheader.tblsize;

	read (hashfd, hashstrings, hashheader.stringsize);
	read (hashfd, hashtbl, hashheader.tblsize * sizeof (struct dent));
	close (hashfd);

	inited = 1;
	return (0);
}

/* n is length of s */
struct dent *
lookup (s, n)
register char *s;
{
	register int i;
	register struct dent *dp;
	register char *s1, *s2;

	for (i = hash (s, n, hashsize); i > 0; i = (int)(dp->next)) {
		dp = &hashtbl[i];
		/* quick strcmp, but only for equality */
		s1 = &hashstrings [ (int)(dp->word) ];
		s2 = s;
		while (*s1 == *s2++)
			if (*s1++=='\0') {
				lastdent = &hashtbl[i];
				return (lastdent);
			}
	}
	return (NULL);
}

