% PURPOSE  : 	Append (join) ERPsets
% 
% FORMAT   : 
% 
% >> ERP = pop_appenderp(ALLERP, ?Erpsets?, indx, prefixes)
% 
% EXAMPLE :
% 
% >> ERP = pop_appenderp(ALLERP, ?Erpsets?, [2 3]);
% 
% 
% INPUTS     :
% 
% ALLERP     - structure array of ERP structures (ERPsets)
% Indx	     - ERPsets to append
% Prefixes   -
%  
% 
% OUTPUTS :
% 
% -	Output new appended ERPset
%
% See also pop_binoperator pop_blcerp
%
% Author: Javier Lopez-Calderon
% 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 erpcom] = pop_appenderp(ALLERP,varargin)

erpcom = '';

ERP = preloadERP;
ERPaux = ERP;

if nargin<1
      help pop_appenderp
      return
end
if nargin==1  % GUI
      if isstruct(ALLERP)
            cond1 = iserpstruct(ALLERP(1));
            if ~cond1
                  ALLERP = [];
            end
      else
            ALLERP = [];
      end
      nloadedset = length(ALLERP);
      def  = erpworkingmemory('pop_appenderp');
      if isempty(def)
            if isempty(ALLERP)
                  %inp1   = 1; %from hard drive
                  erpset = [];
            else
                  %inp1   = 0; %from erpset menu
                  erpset = 1:length(ALLERP);
            end
            isprefix   = 0;
            prefixlist = '';
            %def = {inp1 erpset isprefix prefixlist};
            def = { erpset  prefixlist};
            
      else
            if ~isempty(ALLERP)
                  if isnumeric(def{2}) % JavierLC 11-17-11
                        cerpi  = evalin('base', 'CURRENTERP'); % current erp index
                        def{1} = [cerpi unique(def{1}(def{1}~=cerpi))];
                  end
            end
      end
      
      %
      % Call GUI
      %
      answer = appenderpGUI(nloadedset, def);
      
      if isempty(answer)
            disp('User selected Cancel')
            return
      end
      
      erpset     = answer{1};
      prefixlist = answer{2}  ;
      
      if ischar(erpset)
            inp1   = 1; %from hard drive
      else
            inp1   = 0; %from erpset menu
      end
      if isempty(prefixlist)
            isprefix   = 0; % do not include prefix
      else
            isprefix   = 1; % include prefix
      end
      erpworkingmemory('pop_appenderp', {  erpset prefixlist });
      [ERP erpcom] = pop_appenderp(ALLERP,'Erpsets', erpset, 'Prefixes', prefixlist, 'Saveas', 'on');
      return
else
      p = inputParser;
      p.FunctionName  = mfilename;
      p.CaseSensitive = false;
      p.addRequired('ALLERP');
      
      p.addParamValue('Erpsets', 1); % erpset index or input file
      p.addParamValue('Prefixes', []);
      p.addParamValue('Saveas', 'off', @ischar); % 'on', 'off'
      p.parse(ALLERP, varargin{:});
      
      erpset = p.Results.Erpsets;
      prefixes = p.Results.Prefixes;
      
      if isempty(erpset)
            error('ERPLAB says: ''Erpsets'' inputs is missing.')
      end
      if ismember({p.Results.Saveas}, {'on','yes'})
            saveas    = 1;
      else
            saveas    = 0;
      end
end
if isnumeric(erpset)
      indx = erpset;
      nerp = length(indx);
else
      %
      % open file containing the erp list
      %
      fid_list = fopen( erpset );
      formcell = textscan(fid_list, '%[^\n]','CommentStyle','#', 'whitespace', '');
      lista    = formcell{:};
      lentext  = length(lista);
      fclose(fid_list);
      errorerp = 0;
      
      if lentext>1
            numpoints = zeros(1,lentext);
            numchans  = zeros(1,lentext);
            nameerp   = {''};
            clear ALLERP
            
            for j=1:lentext
                  [pname, fname, ext] = fileparts(strtrim(lista{j}));
                  ALLERP(j) = pop_loaderp('filename', [fname ext], 'filepath', pname);
                  
                  numpoints(j) = ALLERP(j).pnts;
                  numchans(j)  = ALLERP(j).nchan;
                  nameerp{j}   = ALLERP(j).filename;
                  clear ERP1
            end
            if errorerp
                  error('ERPLAB says: Loading ERP process has crashed....')
            else
                  if length(unique(numpoints))>1
                        fprintf('Detail:\n')
                        fprintf('-------\n')
                        for j=1:lentext
                              fprintf('Erpset %s has %g points per bin\n', nameerp{j}, numpoints(j));
                        end
                        msgboxText = 'ERPsets have different number of points\n';
                        etitle = 'ERPLAB: appenderpGUI inputs';
                        errorfound(sprintf(msgboxText), etitle);
                        return
                  end
                  if length(unique(numchans))>1
                        fprintf('Detail:\n')
                        fprintf('-------\n')
                        for j=1:lentext
                              fprintf('Erpset %s has %g channels\n', nameerp{j}, numchans(j));
                        end
                        msgboxText = 'ERPsets have different number of channel\n';
                        etitle = 'ERPLAB: appenderpGUI inputs';
                        errorfound(sprintf(msgboxText), etitle);
                        return
                  end
            end
      else
            msgboxText = 'File is empty!\n';
            etitle = 'ERPLAB: appenderpGUI inputs';
            errorfound(sprintf(msgboxText), etitle);
            return
      end
      nerp = length(ALLERP);
      indx = 1:nerp;
end

nprefix = length(prefixes);

if ~isempty(prefixes)
      if nerp~=nprefix
            msgboxText{1} =  'Error: prefixes must to be as large as indx';
            title = 'ERPLAB: pop_appenderp() error:';
            errorfound(msgboxText, title);
            ERP = ERPaux;
            return
      end
end

[ERP serror] = appenderp(ALLERP,indx, prefixes);

if serror==0
      %
      % Completion statement
      %
      msg2end
      
      %
      % History
      %
      skipfields = {'ALLERP', 'Saveas'};
      fn     = fieldnames(p.Results);
      erpcom = sprintf( 'ERP = pop_appenderp( %s ', inputname(1));
      for q=1:length(fn)
            fn2com = fn{q};
            if ~ismember(fn2com, skipfields)
                  fn2res = p.Results.(fn2com);
                  if ~isempty(fn2res)
                          if ischar(fn2res)
                                  if ~strcmpi(fn2res,'off')
                                          erpcom = sprintf( '%s, ''%s'', ''%s''', erpcom, fn2com, fn2res);
                                  end
                          else
                                  if iscell(fn2res)
                                          if ischar([fn2res{:}])                                                  
                                                  fn2resstr = sprintf('''%s'' ', fn2res{:});                                                 
                                          else
                                                  fn2resstr = vect2colon(cell2mat(fn2res), 'Sort','on');
                                          end
                                          fnformat = '{%s}';
                                  else
                                          fn2resstr = vect2colon(fn2res, 'Sort','on');
                                          fnformat = '%s';
                                  end
                                  erpcom = sprintf( ['%s, ''%s'', ' fnformat], erpcom, fn2com, fn2resstr);
                          end
                  end
            end
      end
      erpcom = sprintf( '%s );', erpcom);
      
      %
      % Save ERPset
      %
      if saveas
            [ERP issave erpcom_save] = pop_savemyerp(ERP,'gui','erplab');
            if issave>0
                  if issave==2
                        erpcom = sprintf('%s\n%s', erpcom, erpcom_save);
                        msgwrng = '*** Your ERPset was saved on your hard drive.***';
                  else
                        msgwrng = '*** Warning: Your ERPset was only saved on the workspace.***';
                  end
            else
                  msgwrng = 'ERPLAB Warning: Your changes were not saved';
            end
            try cprintf([1 0.52 0.2], '%s\n\n', msgwrng); catch,fprintf('%s\n\n', msgwrng);end ;
            return
      end
      
      %       if saveas==1  % open save as GUI
      %             [ERP issave erpcom_save] = pop_savemyerp(ERP,'gui','erplab');
      %
      %             if issave>0
      %                   erpcom = sprintf('ERP = pop_appenderp( %s, %s, { ', inputname(1), vect2colon(indx));
      %
      %                   for j=1:length(prefixes)
      %                         erpcom = sprintf('%s ''%s''  ', erpcom, prefixes{j} );
      %                   end;
      %
      %                   erpcom = sprintf('%s });', erpcom);
      %                   if issave==2
      %                         erpcom = sprintf('%s\n%s', erpcom, erpcom_save);
      %                         msgwrng = '*** Your ERPset was saved on your hard drive.***';
      %                   else
      %                         msgwrng = '*** Warning: Your ERPset was only saved on the workspace.***';
      %                   end
      %                   fprintf('\n%s\n\n', msgwrng)
      %             else
      %                   msgwrng = 'ERPLAB Warning: Your changes were not saved';
      %                   try cprintf([1 0.52 0.2], '%s\n\n', msgwrng);catch,fprintf('%s\n\n', msgwrng);end ;
      %                   ERP = ERPaux;
      %                   return
      %             end
      %       end
elseif serror==1
      msgboxText =  'Your ERPs do not have the same amount of channels!';
      title = 'ERPLAB: pop_appenderp() error:';
      errorfound(msgboxText, title);
      ERP = ERPaux;
      return
elseif serror==2
      msgboxText =  'Your ERPs do not have the same amount of points!';
      title = 'ERPLAB: pop_appenderp() error:';
      errorfound(msgboxText, title);
      ERP = ERPaux;
      return
else
      msgboxText =  'Error: Your ERPs are not compatibles!';
      title = 'ERPLAB: pop_appenderp() error:';
      errorfound(msgboxText, title);
      ERP = ERPaux;
      return
end
