#include <stdio.h>
#include <string.h>
#ifdef MSDOS
#include <io.h>
#endif
#ifndef DEMO
#include "config.h"
#include "hardware.h"
#include "proc.h"
#include "commands.h"
#endif

int searchfileFP (searchfor, fp, buf, entrysize, passes, searchlen)
register char *searchfor;
register FILE *fp;
register char *buf;
int entrysize, *passes, searchlen;
{
register int low = 0, high;
long size;
register int start;
register int result, found = 0;
int index = 0;
char *cp, origchar = 0;

	if (passes)
		*passes = 0;
	if (!searchlen)
		searchlen = strlen (searchfor);
	size = filelength (fileno(fp));
	size /= entrysize;
	high = size - 1;
	index = start = size / 2;
	for ( ; ; )	{
		pwait (NULL);
		fseek (fp, (long) ((long)index * (long)entrysize), 0);
		fread (buf, 1, (unsigned)entrysize, fp);
		if (feof(fp))
			continue;
		if (passes)
			(*passes)++;
		cp = strpbrk (buf, ".@ \t");
		if (cp)	{
			origchar = *cp;
			*cp = 0;
		}
		result = strnicmp (searchfor, buf, (unsigned)searchlen);
		if (!result)	{
			if (searchlen == strlen(buf))	{
				found = 1;
				*cp = origchar;
				break;
			}
		}
		if (start != 1)
			start /= 2;
		if (result < 0)	{
			high = index - 1;
			index -= start;
		} else	{
			low = index + 1;
			index += start;
		}
		if (index < low || index > high)
			break;
	}
	if (found)	{		/* refresh it */
		fseek (fp, (long) ((long)index * (long)entrysize), 0);
		fread (buf, 1, (unsigned) entrysize, fp);
	}
	return ((found) ? index : -1);
}


int searchfile (searchfor, fname, buf, entrysize, passes, searchlen)
register char *searchfor;
char *fname;
register char *buf;
int entrysize, *passes, searchlen;
{
int result;
FILE *fp;

	if ((fp = fopen (fname, "rb")) == NULL)
		return (-1);
	result = searchfileFP (searchfor, fp, buf, entrysize, passes, searchlen);
	fclose (fp);
	return (result);	
}


#ifdef DEMO
#define ENTRYSIZE 49

int
pwait (i)
int i;
{
	return i;
}


void
main (argc, argv)
int argc;
char *argv[];
{
int found, passes;
char buf[128], *searchfor;

	searchfor = "kp4djt";
	if (argc > 1)
		searchfor = argv[1];
	found = searchfile (searchfor, "/nos/spool/wpagebbs", buf, ENTRYSIZE, &passes);

	printf ("String '%s' %sfound - %d passes\n", searchfor, (found == -1) ? "NOT " : "", passes);
	if (found != -1)	{
		buf[ENTRYSIZE] = 0;
		puts (buf);
	}
}
#endif
