function filenames=FindFilenames(partname,startpath,dirconstraints)
%function filenames=FindFilenames(partname,startpath)
%
%partname, string that is part or all of the file to be found
%          e.g. '.mat' or '_pm' (Case sensitive)
%startpath, directory from which the path is to be started
%          default is pwd
%dirconstraints, cell array of strings giving a set of directory
%          name constraints, e.g.
%          [{'PRJ_'},{'StatisticalModels'},{template}]
%
%filenames, cell array containing path\files (as fullfile) 
%           found recursively
%
%J.Andrew Bangham, 2005
if nargin<1
    partname='';
end
if nargin<2
    startpath=pwd;
end
if nargin<3
    dirconstraints={};
end
filenames=[];
if ~isempty(partname)
    d=dir([startpath]);
    for i=3:length(d)
        if d(i).isdir
            dirname=fullfile(startpath,d(i).name);
            temp_filenames=FindFilenames(partname,dirname,dirconstraints);
            filenames=[filenames,temp_filenames];
        else
            % first check that the directory constraints are met
            ok=0;
            for j=1:length(dirconstraints)
                if findstr(startpath,dirconstraints{j})
                    ok=ok+1;
                end
            end
            if ok==length(dirconstraints) 
                if findstr(d(i).name,partname); % now that it is the right file
                    name=fullfile(startpath,d(i).name);
                    filenames=[filenames,{name}];
                    %sprintf('%s',filenames{:})
                end
            end
        end        
    end
end