/* Make a list of files */

#include "global.h"
#include "misc.h"
#include "readdir.h"

/***********************************************/

struct FileNode *FileList;

/***********************************************/

BOOL AddFile(char *Directory, char *File)
{
	struct FileNode *NewNode, *OldNode;

	if (NewNode = AllocVec(sizeof(struct FileNode) + strlen(Directory) + strlen(File) + 1, 0))
	{
		NewNode->Node.Name = (char *) (NewNode + 1);
		stpcpy(stpcpy(NewNode->Node.Name, Directory), File);
		OldNode = FileList;
		while (OldNode && stricmp(OldNode->Node.Name, NewNode->Node.Name))
		{
			OldNode = (struct FileNode *) (OldNode->Node.Next);
		}
		if (OldNode)
		{
			printf("Error: file %s found twice.\n", NewNode->Node.Name);
			FreeVec(NewNode);
			return (FALSE);
		}
		NewNode->Node.Next = (struct AnyNode *) FileList;
		FileList = NewNode;
		return (TRUE);
	}
	PrintFault(ERROR_NO_FREE_STORE, NULL);
	return (FALSE);
}

/***********************************************/

BOOL ReadDir(BPTR Directory, char *DirName, char *Extension, BOOL(*Function) (char *Name))
{
	struct FileInfoBlock __aligned FileInfoBlock;
	BPTR OldCurrentDir;
	long Length;
	int ExtensionLength;
	char NewName[200];
	BPTR NewDirectory;
	BOOL Success;

	OldCurrentDir = CurrentDir(Directory);
	if (Examine(Directory, &FileInfoBlock))
	{
		Success = TRUE;
		ExtensionLength = strlen(Extension);
		while (Success && ExNext(Directory, &FileInfoBlock))
		{
			if (Break())
			{
				Success = FALSE;
			}
			else
			{
				if (FileInfoBlock.fib_DirEntryType < 0)
				{
					Length = strlen(FileInfoBlock.fib_FileName);
					if (Length >= ExtensionLength && !stricmp(FileInfoBlock.fib_FileName + Length - ExtensionLength, Extension))
					{
						if (!AddFile(DirName, FileInfoBlock.fib_FileName) || !Function(FileInfoBlock.fib_FileName))
						{
							Success = FALSE;
						}
					}
				}
				else
				{
					if (sprintf(NewName, "%s%s/", DirName, FileInfoBlock.fib_FileName))
					{
						if (NewDirectory = Lock(FileInfoBlock.fib_FileName, ACCESS_READ))
						{
							Success = ReadDir(NewDirectory, NewName, Extension, Function);
							UnLock(NewDirectory);
						}
						else
						{
							PrintFault(IoErr(), NewName);
							Success = FALSE;
						}
						/* FreeVec(NewName); */
					}
					else
					{
						PrintFault(ERROR_NO_FREE_STORE, NULL);
						Success = FALSE;
					}
				}
			}
		}
		if (Success)
		{
			if (IoErr() == ERROR_NO_MORE_ENTRIES)
			{
				Success = TRUE;
			}
			else
			{
				PrintFault(IoErr(), DirName);
				Success = FALSE;
			}
		}
	}
	else
	{
		PrintFault(IoErr(), DirName);
		Success = FALSE;
	}
	CurrentDir(OldCurrentDir);
	return (Success);
}
