%PR_LOADMATFILE  Load matfile for this mfile, if it exist
%
%    A = PR_LOADMATFILE(MATFILE)
%
% Loads the dataset stored in the matfile. Default matfile is the name of
% the calling routine. The output A is empty if MATFILE does not exist.
%
%    [A1,A2,..] = PR_LOADMATFILE(MATFILE,NARGOUTCOUNT)
%
% In case multiple matfiles are stored for the calling routine, it is
% assumed they all contain a dataset: train set, test set, validation set,
% etcetera. In case NARGOUTCOUNT (NARGOUT of the calling routine) equals 1,
% the combined dataset is loaded and returned in A (A1). 
% In case NARGOUTCOUNT > 1, the subsets are are loaded into A1, A2, ... 
%
% SEE ALSO
% DATASETS, PRDATASETS, PR_SAVEMATFILE, PR_DOWNLOAD_UCI

function varargout = pr_loadmatfile(name)

varargout = cell(1,nargout);

if nargin < 1 || isempty(name)
  name = pr_callername;
end
matfile = fullfile(fullfile(fileparts(which(mfilename)),'data'),name);
if exist([matfile '.mat'],'file') ~= 2,
  return
end

if nargout == 1
%   varargout{1} = loadmatf([matfile '.mat']);
  varargout{1} = file2dset([matfile '.mat']);
else
  for i=1:nargout
%     varargout{i} = loadmatf([matfile '_' num2str(i) '.mat']);
    varargout{i} = file2dset([matfile '_' num2str(i) '.mat']);
  end
end

return
  
function a = loadmatf(matfile)
  if exist(matfile,'file') == 2
    warning('OFF','MATLAB:indeterminateFields');
    s = prload(matfile);
    warning('ON','MATLAB:indeterminateFields');
    fields = fieldnames(s);
    a = s.(fields{1});
    a = pr_dataset(a); % take care of prtools4 and prtools5 datasets
  else
    a = [];
  end
return
