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

#if !defined(_lint)
static char rcsid[] OPTIONAL = "$Id: search.c,v 1.15 1997/07/31 00:44:20 root Exp $";
#endif

static int searchfileFP (register char *searchfor,register FILE *fp,register char *buf,int entrysize, int *passes, int searchlen);


static 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 theindex = 0;
char *cp, origchar = 0;

	if (passes)
		*passes = 0;
	if (!searchlen)
		searchlen = (int) strlen (searchfor);
	size = (long) filelength (fileno(fp));
	if (size < entrysize)
		return (-1);
	size /= entrysize;
	high = size - 1;
	theindex = start = size / 2;
	for ( ; ; )	{
		kwait (NULL);
		fseek (fp, (long) ((long)theindex * (long)entrysize), 0);
		(void) 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 == (int)strlen(buf))	{
				found = 1;
				if (cp)
					*cp = origchar;
				break;
			}
		}
		if (start != 1)
			start /= 2;
		if (result < 0)	{
			high = theindex - 1;
			theindex -= start;
		} else	{
			low = theindex + 1;
			theindex += start;
		}
		if (theindex < low || theindex > high)
			break;
	}
	if (found)	{		/* refresh it */
		fseek (fp, (long) ((long)theindex * (long)entrysize), 0);
		(void) fread (buf, 1, (unsigned) entrysize, fp);
	}
	return ((found) ? theindex : -1);
}


int searchfile (searchfor, fname, buf, entrysize, passes, searchlen)
register char *searchfor;
const 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);
	(void) fclose (fp);
	return (result);	
}


#ifdef DEMO
#define ENTRYSIZE 49

int
kwait (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
