#!/usr/perl5/bin/perl -- -*-perl-*-

# -------------------------------------------------------------------------------------
# FILE		:	directory_list_lib.pl
# Author	:	Oyewole, Olanrewaju J.
# Version	:	1.0
# Date		:	18/03/2002
# -------------------------------------------------------------------------------------
# Description	:
# -------------------------------------------------------------------------------------
#            	:	This library provides a single service, to wit,
#		:	to retrieve all entries within a given directory tree.
#		:	The subroutine directory_list should be called with
# 		:	the name of a directory to be scanned.
#		:	The second input parameter is a flag that determines
#		:	what entries are returned from the Directory tree.
#		:	The third parameter provides an array of valid
#		:	file patterns to match.
#		:
#		:	NULL/0	= Files and Directories
#		:	1	= Files ONLY
#		:	-1	= Directories ONLY
# -------------------------------------------------------------------------------------
# Version	:	1.1
# Date		:	28/04/2002
# -------------------------------------------------------------------------------------
# Description	:
# -------------------------------------------------------------------------------------
#            	:	Added third parameter, to provide an array of file patterns
#		:	to filter the list of returned files.
# -------------------------------------------------------------------------------------



use File::Find;

	my $match_string = '';

	sub directory_list {
		# NULL/0 = Files and Directories
		# 1	 = Files ONLY
		# -1	 = Directories ONLY
		my ($directory_root, $files_and_or_directories, @file_patterns) = @_;
		return (wantarray ? () : '') if (!-d $directory_root); # Exit now if Directory does not exist!

		@file_patterns = ('.*') if (!(@file_patterns));	# default to match all files, if no pattern specified
		$match_string = join('|', @file_patterns);
		find(\&process_directory, $directory_root) if (!$files_and_or_directories);
		find(\&process_directory_files_only, $directory_root) if ($files_and_or_directories >= 1);
		find(\&process_directory_only, $directory_root) if ($files_and_or_directories <= -1);
		return wantarray ? @arrayOfEntries : join("\n", @arrayOfEntries);
	}


	sub process_directory {
		my $file_found = $File::Find::name;
		push(@arrayOfEntries, $file_found) if ($file_found =~ /$match_string/);
	}

	sub process_directory_files_only {
		my $file_found = $File::Find::name;
		push(@arrayOfEntries, $file_found) if ((-f $file_found) && ($file_found =~ /$match_string/));
	}

	sub process_directory_only {
		my $file_found = $File::Find::name;
		push(@arrayOfEntries, $file_found) if ((-d $file_found) && ($file_found =~ /$match_string/));
	}

1;

