// This is the basis of a the plugin scanner.
// We scan a given directory and build a list of available files
// with the filename extension provided
// 
// The class assumes that dos.library has been opened

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <stdio.h>
#include <string.h>

#include <misc/systemdefs.h>
#include <misc/dirscan.h>

extern void OmegaError(char *,char *, char *);

DirScanner::DirScanner(){
	block=(FileInfoBlock *)AllocDosObject(DOS_FIB,NULL);
	numFiles=0;
	for (int n=0;n<MAXPLUGINS;n++)
		fileNames[n]=NULL;
}	

DirScanner::~DirScanner(){
	if (block)
		FreeDosObject(DOS_FIB,block);
	for (int n=0;n<numFiles;n++){
		if (fileNames[n])
//			delete [] fileNames[n];
	}
}

void DirScanner::CheckBlock(char *ext){
	char *name=&(block->fib_FileName[0]);
	UINT nameLength=strlen(name);
		
	if (block->fib_DirEntryType<0){
		if (strstr(name+nameLength-4,ext)){		// Only look at last 4 characters of name
			fileNames[numFiles]=new char[nameLength+1];
			strcpy(fileNames[numFiles],name);	// Cpy filename into a new item of our array
			numFiles++;
		}
	}
}

char **DirScanner::ScanDir(char *dir, char *ext){
	BPTR lock;
	numFiles=0;
	
	lock=Lock(dir,ACCESS_READ);
	if(lock && block){
		if(Examine(lock,block)){
			while(ExNext(lock,block))
				CheckBlock(ext);
		}
		else
			OmegaError("Scanner Error","Couldn't examine lock",NULL);
		UnLock(lock);
	}
	else
		OmegaError("Scanner Error","Couldn't obtain lock on directory","Does plugin directory exist?");
	return fileNames;
}