% PURPOSE  : 	Loads ERPset(s) into the ERPset menu (at EEGLAB GUI)
% 
% FORMAT   : 
% 
% >> ERP = pop_loaderp(Parameters); 
% 
% EXAMPLE  :
% 
% >> ERP = pop_loaderp( 'filename', 'S1_ERPS.erp', 'overwrite', 'off',
% 'filepath', '/Users/etfoo/Documents/MATLAB/', 'warning', 'on'); 

% 
% PARAMETERS     :
% 
% 'filename'        - Name of ERPset
% 'filepath'        - ERPset's filepath
% 'overwrite'       - overwrite current erpset 'on' or 'off'
% 'warning'         - 'on' or 'off'
% 
% 
% OUTPUTS  :
% 
% ERP	- output ERPset
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon & Steven Luck
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2009

%b8d3721ed219e65100184c6b95db209bb8d3721ed219e65100184c6b95db209b
%
% ERPLAB Toolbox
% Copyright © 2007 The Regents of the University of California
% Created by Javier Lopez-Calderon and Steven Luck
% Center for Mind and Brain, University of California, Davis,
% javlopez@ucdavis.edu, sjluck@ucdavis.edu
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU 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 General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

function [ERP ALLERP erpcom] = pop_loaderp(varargin)

erpcom = '';
ERP = preloadERP;
try
      ALLERP   = evalin('base', 'ALLERP');
      preindex = length(ALLERP);
catch
      disp('WARNING: ALLERP structure was not found. ERPLAB will create an empty one.')
      ALLERP = [];
      %ALLERP   = buildERPstruct([]);
      preindex = 0;
end
if nargin<1
      help pop_loaderp
      return
end
if nargin==1
      filename = varargin{1};
      if strcmpi(filename,'workspace')
            filepath = '';
      else
            if isempty(filename)
                  [filename, filepath] = uigetfile({'*.erp','ERP (*.erp)';...
                        '*.mat','ERP (*.mat)'}, ...
                        'Load ERP', ...
                        'MultiSelect', 'on');
                  if isequal(filename,0)
                        disp('User selected Cancel')
                        return
                  end
                  
                  %
                  % test current directory
                  %
                  %changecd(filepath) % Steve does not like this...
            else
                  filepath = cd;
            end
      end
      
      [ERP ALLERP erpcom] = pop_loaderp('filename', filename, 'filepath', filepath, 'Warning', 'on', 'UpdateMainGui', 'on', 'Multiload', 'off');
      return
else
      % parsing inputs
      p = inputParser;
      p.FunctionName  = mfilename;
      p.CaseSensitive = false;
      p.addParamValue('filename', '');
      p.addParamValue('filepath', '', @ischar); 
      p.addParamValue('overwrite', 'off', @ischar); 
      p.addParamValue('Warning', 'off', @ischar); 
      p.addParamValue('Multiload', 'off', @ischar); 
      p.addParamValue('UpdateMainGui', 'off', @ischar); 
            
      p.parse(varargin{:});
      
      filename = strtrim(p.Results.filename);
      filepath = strtrim(p.Results.filepath);
      
      if strcmpi(filename,'workspace')
            filepath = '';
            nfile = 1;
            loadfrom = 0;  % load from workspace
      else
            loadfrom = 1; % load from: 1=hard drive; 0=workspace
      end
      if strcmpi(p.Results.Warning,'on')
            popupwin = 1;
      else
            popupwin = 0;
      end
      if strcmpi(p.Results.UpdateMainGui,'on')
            updatemaingui = 1;
      else
            updatemaingui = 0;
      end
      if strcmpi(p.Results.Multiload,'on')
            multiload = 1;
      else
            multiload = 0;
      end
end
if loadfrom==1
      if iscell(filename)
            nfile      = length(filename);
            inputfname = filename;
      else
            nfile = 1;
            inputfname = {filename};
      end
else
      inputfname = {'workspace'};
end

inputpath = filepath;
errorf    = 0; % no error found, by default
conti     = 1; % continue?  1=yes; 0=no
if strcmpi(p.Results.overwrite,'on')||strcmpi(p.Results.overwrite,'yes')
      ovatmenu = 1;
else
      ovatmenu = 0;
end

%
% load ERPsets(s)
%
for i=1:nfile
      if loadfrom==1
            L   = load(fullfile(inputpath, inputfname{i}), '-mat');
            ERP = L.ERP;
      else
            ERP = evalin('base', 'ERP');
      end
      
      [ERP conti serror] = olderpscan(ERP, popupwin);      
      if conti==0
            break
      end
      if serror
            msgboxText = ['Your erpset %s is not compatible at all with the current ERPLAB version.\n'...
                  'Please, try upgrading your ERP structure.'];
            title = 'ERPLAB: pop_loaderp() Error';
            errorfound(sprintf(msgboxText, ERP.filename), title);
            errorf = 1;
            break
      end
      
      %
      % Check (and fix) ERP structure (basic)
      %
      checking = checkERP(ERP);
      
      try
            if checking
                  if i==1 && isempty(ALLERP);
                        ALLERP = buildERPstruct([]);
                        ALLERP = ERP;
                  else
                        ALLERP(i+preindex) = ERP;
                  end
            else
                  msgboxText = ['Your erpset %s is not compatible at all with the current ERPLAB version.\n'...
                        'Please, try upgrading your ERP structure.'];
                  title = 'ERPLAB: pop_loaderp() Error';
                  errorfound(sprintf(msgboxText, ERP.filename), title);
                  errorf = 1;
                  break
            end
      catch
            msgboxText = ['Your erpset %s is not compatible at all with the current ERPLAB version.\n'...
                  'Please, try upgrading your ERP structure.'];
            title = 'ERPLAB: pop_loaderp() Error';
            errorfound(sprintf(msgboxText, ERP.filename), title);
            errorf = 1; % fatal error
            break
      end
end
if conti==0
      return
end
if nargout==1 && multiload==1
      ERP = ALLERP;
end
if errorf==0 && serror==0
      if updatemaingui % update erpset menu at main gui
            assignin('base','ALLERP',ALLERP);  % save to workspace
            updatemenuerp(ALLERP); % add a new erpset to the erpset menu
      end
      fn  = fieldnames(p.Results);
      erpcom = sprintf( 'ERP = pop_loaderp(');
      skipfields = {'UpdateMainGui'};
      
      for q=1:length(fn)
            fn2com = fn{q};
            if ~ismember(fn2com, skipfields)
                  fn2res = p.Results.(fn2com);
                  if iscell(fn2res) % 10-21-11
                        nc = length(fn2res);
                        xfn2res = sprintf('{''%s''', fn2res{1} );
                        for f=2:nc
                              xfn2res = sprintf('%s, ''%s''', xfn2res, fn2res{f} );
                        end
                        fn2res = sprintf('%s}', xfn2res);
                  else
                        fn2res = ['''' fn2res ''''];
                  end
                  if ~isempty(fn2res)
                        if ischar(fn2res)
                              if ~strcmpi(fn2res,'off')
                                    if q==1
                                          erpcom = sprintf( '%s ''%s'', %s', erpcom, fn2com, fn2res);
                                    else
                                          erpcom = sprintf( '%s, ''%s'', %s', erpcom, fn2com, fn2res);
                                    end
                              end
                        else
                              erpcom = sprintf( '%s, ''%s'', %s', erpcom, fn2com, vect2colon(fn2res,'Repeat','on'));
                        end
                  end
            end
      end
      
      erpcom = sprintf( '%s );', erpcom);
      
      %
      % Completion statement
      %
      prefunc = dbstack;
      nf = length(unique({prefunc.name}));
      if nf==1
            msg2end
      end
else
      %       if strcmpi(filename,'workspace')
      %             assignin('base','ALLERP',ALLERP);  % save to workspace
      %             updatemenuerp(ALLERP);
      %       end
end
return