/* 
	Directory List Builder
	Made by Ismo Horppu on 1996 - 1997
*/

#include <dos.h>
#include <stdio.h>
#include <dir.h>
#include "types.h"
#include "xfile.h"

FileName::FileName ()
{
	long cnt;
	
	Next = NULL;
	FileNames = 1;
}

long FileName::AddName (void)
{
	if (!(Current->Next = new FileName)){
		return -1;
	}
	
	Last = Current->Next;
	Current = Last;
	FileNames++;
	return 0;
}

long FileName::FreeNames (void)
{
	Current = First;
	
	for (cnt = 0; cnt < FileNames; cnt++){
		Last = Current;
		delete Last;
		Current = Current->Next;
	}
	
	FileNames = 0;
	return 0;
}

long FileName::CopyName (char CopyName[13])
{
	long cnt;
	
	for (cnt = 0; cnt < 13; cnt++){
		Current->Name[cnt] = CopyName[cnt];
	}
}

char *FileName::GetName (long FN_index)
{
	long cnt;

	Current = First;
		
	for (cnt = 0; cnt < FN_index; cnt++){
		Current = Current->Next;
	}
	
	return Current->Name;
}

long FileName::FindName (char *seekname)
{
	long cnt;

	Current = First;
		
	for (cnt = 0; cnt < FileNames; cnt++){
		if (strcmp (Current->Name, seekname) == 0) return cnt;
		Current = Current->Next;
	}
	
	return -1;
}

long FileName::SelectName (long nameindex)
{
	long cnt;

	Selected = First;
		
	for (cnt = 0; cnt < nameindex; cnt++){
		Selected = Selected->Next;
	}
}

long ReadDirectoryList (char *seek)
{
	char t1, t2;
	long stat;
	
	done = findfirst (seek, &ffb, FA_ARCH);
	
	while (!done){
		t1 = (char) (ffb.ff_fsize >> 16);
		realname[0] = t1;
		t2 = (char) (ffb.ff_fsize >> 24);
		realname[1] = t2;

		for (cnt = 0; cnt < 10; cnt++){
			realname[2 + cnt] = ffb.ff_name[cnt];
		}
	
		realname[12] = 0;	// end of text
		
		XFN->CopyName (realname);
		stat = XFN->AddName ();
		
		if (stat != 0) return stat;
		
		done = findnext (&ffb);
	}
	
	return 0;
}

long DisplayDL (void)
{
	long cnt;
	
	for (cnt = 0; cnt < XFN->FileNames - 1; cnt++){
		printf ("%lu. %s\n", cnt + 1, XFN->GetName (cnt));
	}
}

long InitFileNames (void)
{
	if (!(XFN = new FileName)){
		printf ("Not enough memory for a new filename class\n");
		return -1;
	}
	
	First = XFN;
	Current = XFN;
	Last = XFN;
	return 0;
}

long FreeFileNames (void)
{
	XFN->FreeNames ();
}