/*
 *  kd_freq.library NewPatMatch() Test
 *
 *  This demonstrates the use of NewPatMatch() in reading the
 *  FindDB:find.codes file.
 *
 *  You need to assemble and link  glue.asm with this, or use the
 *  appropriate #pragmas!
 *
 */


#include "KDBase.h"

struct Library *KD_FReqBase, *OpenLibrary();

main(argc,argv)
	int argc;
	char *argv[];
	{
	if (argc < 2)
		{
		print("WFind:\n\nUsage:   WFind pattern\n");
		}
	else if (KD_FReqBase = OpenLibrary(KLIBNAME,KLIBVERSION))
		{
		FindFiles(argv[1]);
		CloseLibrary(KD_FReqBase);
		}
	else
		{
		print("Can't Open 'kd_freq.library'.  Make sure it is in LIBS:\n");
		}
	}


long FileSize(filename)
	char *filename;
	{
	struct FileInfoBlock *FIB;
	struct FileLock *lock;
	long size = 0L;
	
	FIB = (struct FileInfoBlock *)
		AllocMem((long) sizeof(struct FileInfoBlock), MEMF_PUBLIC|MEMF_CLEAR);
		
	if (FIB)
		{
		if (lock = (struct FileLock *) Lock(filename,ACCESS_READ))
			{
			if (Examine(lock,FIB))
				size = FIB->fib_Size;
			UnLock(lock);
			}
		FreeMem(FIB, (long) sizeof(struct FileInfoBlock));
		}

	return(size);
	}

#define FILE "FindDB:find.codes"

FindFiles(pattern)
	UBYTE *pattern;
	{
	long status, buffersize;
	struct FileHandle *in, *Open();
	UBYTE *buffer;

	buffersize = FileSize(FILE);

	if (in = (struct FileHandle *)Open(FILE,MODE_OLDFILE))
		{
		if (buffer = (UBYTE *) AllocMem(buffersize,MEMF_PUBLIC|MEMF_CLEAR))
			{
			status = Read(in,buffer,buffersize);

			print("\n\nDirectories:\n------------");

			ScanFiles(pattern,buffer,status,1);

			print("\n\nFiles:\n------");
			ScanFiles(pattern,buffer,status,2);

			FreeMem(buffer,buffersize);
			}

		Close(in);
		}
	else
		print("Couldn't find FindDB:find.codes!!");
	}


/* pass 1  shows directories,  pass 2 shows files..
   this code is slow... and could be improved a lot with some
   work...  You are very welcome to optimize it...
   I'm too busy on something else.. (grin)

*/

ScanFiles(pattern,buf,size,pass)
	UBYTE *pattern;
	UBYTE *buf;
	LONG size;
	USHORT pass;
	{
	UBYTE *ptr = buf, temp;
	ULONG len;
	UBYTE directory[128];
	UBYTE path[160];
	long i;

	while(ptr < (buf+size))
		{
		len  = strlen(ptr);

		temp = ptr[len-1];

		if ((temp == '/') || (temp == ':'))
			{
			strcpy(directory,ptr);
			directory[strlen(directory)-1] = 0;

			for (i = strlen(directory); i >= 0; i--)
				{
				temp = directory[i];				
				if ((temp == '/') || (temp == ':'))
					break;
				}

			i++;

			if (pass == 1)
				if (NewPatMatch(pattern, directory+i) == 1)
					print(directory);

			strcpy(directory,ptr);
			}
		else 
			if (pass == 2)
				if (NewPatMatch(pattern, ptr) == 1)
				{
				strcpy(path,directory);
				strcat(path,ptr);
				print(path);					
				}

		while(*ptr++)
			;

		}
	}


/* to save some code size... */

print(string)
	UBYTE *string;
	{
	struct FileHandle *Output();

	Write(Output(),string,strlen(string));
	Write(Output(),"\n",1);
	}
