function files=ListFiles(path, varargin)
    % LISTFILES    List filenames in a directory optionally recursively   
    %   Written by Grant Elliott, June 2011
    %   Adapted from recursive directory listing code posted on StackOverflow by 'gnovice'
    %
    %   files=ListFiles(path) Returns a cell array of all file names in a folder.
    %   Absolute addresses are returned, though path may be a relative address
    %
    %   files=ListFiles(path, paramName, paramValue,...) takes additional optional parameters.
    %
    %   Accepts the following optional parameters:
    %   Recursive      - Whether to search recursively (Defaults to true)
    %   Extensions     - Cell array of extensions with no dot to filter by (Defaults to any)
    %   RegExp         - Regular expression which the absolute path must satisfy (Defaults to '.')
    %
    %   Example:
    %       ListFiles('..\..\Data','Extensions',{'xlsx','xls'})
    %       Returns all Excel files within the relative directory ..\..\Data\
    %
    %   See also dir
    p=inputParser;
    p.addParamValue('Recursive', true, @(x) islogical(x) && numel(x)==1);
    p.addParamValue('Extensions', [], @(x) (iscell(x) && all(cellfun(@(y)ischar(y),x))) || ischar(x));
    p.addParamValue('RegExp', '', @(x) (ischar(x)));
    p.parse(varargin{:});
    settings = p.Results;
    if ischar(settings.Extensions)
        settings.Extensions={settings.Extensions};
    end
    settings.Extensions=regexprep(settings.Extensions,'^\.','');
    if length(path)==0
        path=pwd;
    end
    if ~exist(path,'dir')
        error('Metabolics:FileNamesInFolder:IllegalPath','Failed to find directory %s',path);
    end
    path=cd(cd(path));
    
    if (settings.Recursive)
        files=getAllFiles(path);
    else
        f=dir(path);
        files=arrayfun(@(x)[path '\' x.name],f,'uniformoutput',false);
        files=files(cellfun(@(x)exist(x,'file')==2,files));
    end
    if ~isempty(settings.Extensions)
        filter = sprintf('.%s$|',settings.Extensions{:});
        filter = filter(1:end-1);
        files=files(cellfun(@(x)~isempty(regexpi(x,filter, 'once')),files));
    end
    if ~isempty(settings.RegExp)
        filter = settings.RegExp;
        files=files(cellfun(@(x)~isempty(regexpi(x,filter, 'once')),files));
    end
end

function fileList = getAllFiles(dirName)   
    % Recursive directory listing code posted on StackOverflow by 'gnovice'
	dirData = dir(dirName);
    dirIndex = [dirData.isdir];
    fileList = {dirData(~dirIndex).name}';
    if ~isempty(fileList)
    	fileList = cellfun(@(x) fullfile(dirName,x),fileList,'UniformOutput',false);
    end
    subDirs = {dirData(dirIndex).name};
    validIndex = ~ismember(subDirs,{'.','..'});
    for iDir = find(validIndex)
    	nextDir = fullfile(dirName,subDirs{iDir});
    	fileList = [fileList; getAllFiles(nextDir)]; %#ok<AGROW>
    end
end