function varargout = getFiles(directory, varargin)
% get m-files in current directory.
%
% getfiles(..., 'extension', extension) does list all files matching the
%   given extension.
%
% getfiles(..., 'descend', descend) limits the number of descended 
%   folders. Example: descend = 2 descends into directory/foo/bar and 
%   value = 0 prevents from descending into subdirectories completely. 
%   Default value is descend = -1 for unlimited descending.
%
% files = getfiles(..) gives a cell array of files including full path,
%   instead of printing to screen.
%
% THIS IS NOT YET A USER FUNCTION

% MDT: MATLAB developement toolbox - for the everyday programmer
%   Copyright (C) 2013 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU Lesser General Public License as published 
%   by the Free Software Foundation, either version 3 of the License, or 
%   (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License 
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.

%% set parameters
if nargin == 0, directory = cd;end
optionStruct = mapOptionStruct(varargin,...
    'extension', '.m',...
    'descend', -1);

% initialize for loop
fileList = dir(directory);
files = {};
for i = 1:length(fileList)
    %% is directory >> descend recursively
    if fileList(i).isdir && ~strcmp(fileList(i).name(1), '.')
        if optionStruct.descend ~= 0
            add_files = getFiles([directory filesep fileList(i).name],...
                'descend', optionStruct.descend - 1, 'extension', optionStruct.extension);
            files(end+1:end+length(add_files)) = add_files;
        end
    %% is proper file >> add to list
    elseif length(fileList(i).name) >= length(optionStruct.extension)...
            && strcmp(fileList(i).name(end + 1 + ...
                                       (-length(optionStruct.extension):-1)...
                                      ), optionStruct.extension)
        files{end+1} = ['' directory filesep fileList(i).name];
    end
end

%% output
if nargout == 1
    varargout{1} = files;
else
    printFiles(files);
end
   
