function L=listfiles(dirname,varargin)
% listfiles - list files in a directory
%
% listfiles :: 
%    text ~'directory path',
%    options {
%       'pattern':text 	~'pattern to match files against',
%       'regext':text 	~'regular expression to match files against',
%       'ext':text      ~'file names must in end in this'
%       'rec':bool/0    ~'recursive search?'
%    }
% -> {[N]->text}        ~'cell array of N paths'.

opts=options('rec',0,varargin{:});

if isfield(opts,'pattern'),
	dirpat = fullfile(dirname,opts.pattern);
else
	dirpat = dirname;
end

if isfield(opts,'regexp'),
	filter=@(f)(~isempty(regexp(f,opts.regexp)));
elseif isfield(opts,'ext'),
	filter=@(f)endswith(f,opts.ext);
else
	filter=@(f)true;
end

D=dir(dirpat);
L={};

for i=1:length(D)
	f=D(i);
	if ~f.isdir && feval(filter,f.name),
		L=[L {fullfile(dirname,f.name)}];
	end
end

if opts.rec
	if strcmp(dirname,dirpat), DX=D; else DX=dir(dirname); end
	for i=1:length(DX)
		f=DX(i);
		if f.isdir && ~strcmp(f.name,'.') && ~strcmp(f.name,'..')
			L=[L,listfiles(fullfile(dirname,f.name),opts)];
		end
	end
end
