/*  dirfiles.C   */
/*  Copyright 1991 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <fstream.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include "dirfiles.h"

static int ValidFile(char * name, const char * Suffix)
{
	if (!Suffix) return 1 ;
	if (!name) return 0;
	int end = strlen(name);
	for (int i = end; i > -1; i--) if (name[i] == '.')
		return (!strcmp(&name[i],Suffix));
	return 0;
}

static void SetName(int index, const char * Name, const char ** FileList)
{
	char * ToSet = new char[strlen(Name)+1] ;
	strcpy(ToSet,Name);
	FileList[index]=ToSet ;
}

const char ** FileListFromDirectory(const char * DirName, const char * Suffix)
{

	DIR * Directory = opendir((char *) DirName) ;
	if (!Directory) {
		cerr << "Cannot open directory `" << DirName << "'.\n" ;
		return 0 ;
	}
	int NDirs = 0;
	struct dirent * DirRead ;
	while (DirRead = readdir(Directory) )
#ifndef __NT_VC__
		if(DirRead->d_ino)
#endif
			if(ValidFile(DirRead->d_name,Suffix))
			NDirs++;
	rewinddir(Directory) ;
	cerr << "Found " << NDirs << " `" << Suffix << "' files in directory\n"
		<< DirName << "\n" ;
	const char ** Return = new const char * [NDirs+1] ;
	int j=0;
	// cout << " In directory `" << DirName << "'\n" ;
	while (DirRead = readdir(Directory) )
#ifndef __NT_VC__
		if(DirRead->d_ino)
#endif
		if(ValidFile(DirRead->d_name, Suffix)) 
			SetName(j++,DirRead->d_name,Return);
	closedir (Directory);
	Return[j] = 0 ;
	return Return;
}

