%ERP_ANALYSIS Apply PLS on the ERP data based on the information saved in
%    the datamat file.
%
%    Usage: [resultFile, elapsed_time] = ...
%	erp_analysis(ismean, ishelmert, iscontrast, isbehav, ...
%	behavdata_col, contrastdata_col, datamat_files, ...
%	num_perm, num_boot, Clim, system, ContrastFile)
%
%    see also PLS_FMRI_ANALYSIS
%

%   Called by erp_analysis_ui
%
%  INPUT:
%    ismean - 1 if select grand mean deviation.
%    ishelmert - 1 if using helmert matrix.
%    iscontrast - 1 if using contrast data.
%    isbehav - 1 if using behavior data.
%    behavdata_col - Selected column mask for Behavior Data;
%    contrastdata_col - Selected column mask for Contrast Data;
%    posthoc - posthoc data.
%    datamat_files - a cell array, one element per group.  Each element
%               in the array is another cell array contains the names of
%               session profiles for the group.
%    num_perm - number of permutations to be performed.
%    num_boot - number of bootstrap resampling to be performed.
%    Clim - upper limit of confidence interval estimated
%
%   OUTPUT FILE:
%         - file stores the information of the PLS result.
%
%   Created July 2001 by Wilkin Chau, Rotman Research Institute
%   Modified on 02-OCT-2002 by Jimmy Shen
%   Modified on Jan 10, 03 to add contrast & helmert
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [resultFile, elapsed_time] = erp_analysis(varargin)

  progress_hdl = rri_progress_ui('initialize');

  ismean = varargin{1};
  ishelmert = varargin{2};
  iscontrast = varargin{3};
  isbehav = varargin{4};
  behavdata_col = varargin{5};
  contrastdata_col = varargin{6};
  posthoc = varargin{7};
  datamat_files = varargin{8};
  save_datamat = varargin{9};
  num_perm = varargin{10};
  num_boot = varargin{11};
  Clim = varargin{12};
  system = varargin{13};
  ContrastFile = varargin{14};
  cond_selection = varargin{15};
  behavdata_lst0 = varargin{16};
  behavname0 = varargin{17};

  datamat_files_timestamp = datamat_files;

  for i = 1:length(datamat_files)
     tmp = dir(datamat_files{i});
     datamat_files_timestamp{i} = tmp.date;
  end

  load(datamat_files{1},'session_info');
  datamat_prefix = session_info.datamat_prefix;

  [result_file,result_path] = uiputfile([datamat_prefix '_ERPresult.mat'], ...
	'Saving PLS Result',350,150);

  if isequal(result_file,0)		% Cancel was clicked
     resultFile = [];
%     msg1 = ['WARNING: No file is saved.'];
%%     uiwait(msgbox(msg1,'Uncompleted','modal'));
     elapsed_time = 0;
     return;
  else
     resultFile = fullfile(result_path,result_file);
  end;

  % load the session info and datamat
  %
  [newdata_lst, behavdata_lst, helmertdata_lst, contrastdata_lst, ...
	subj_name_lst, num_cond_lst, num_subj_lst, common_behav, ...
	common_channels, common_conditions, common_time_info, ...
	chan_order, cond_name, behavname] = erp_get_common(datamat_files, ...
	behavdata_col, contrastdata_col, cond_selection, progress_hdl);

  if ~isempty(behavdata_lst0) & ~isempty(behavname0)
     behavdata_lst = behavdata_lst0;
     behavname = behavname0;
  end

  for i = 1:length(newdata_lst)
    if isempty(newdata_lst{i})
      return;
    end
  end

  %  start PLS Run...
  %

  perm_result = [];
  boot_result = [];
  setting2 = [];
  setting3 = [];
  setting4 = [];

  create_ver = plsgui_vernum;

  if(isbehav)					% behavior analysis

     rri_progress_ui(progress_hdl, 'Runing Behavior PLS', 'Runing Behavior PLS ...');

     if (num_perm > 0) | (num_boot == 0)
        [salience,s,behavlv,scalpscores,behavscores,lvcorrs, ...
		origpost, perm_result, datamatcorrs_lst] = ...
		rri_analysis_perm(ismean, ishelmert, iscontrast, isbehav, ...
		newdata_lst,num_cond_lst,num_subj_lst, ...
		behavdata_lst, helmertdata_lst, contrastdata_lst, ...
		num_perm, posthoc);
     end

     if (num_boot > 0)
        if num_perm == 0, origpost = []; end;
        [salience,s,behavlv,scalpscores,behavscores,lvcorrs,boot_result,datamatcorrs_lst] = ...
		rri_analysis_boot(ismean, ishelmert, iscontrast, isbehav, ...
		newdata_lst,num_cond_lst,num_subj_lst, ...
		behavdata_lst, helmertdata_lst, contrastdata_lst, ...
		num_boot, Clim);
     end

     saved_info=['''salience'', ''s'', ''behavlv'', ''scalpscores'', ', ...
		'''behavscores'', ''lvcorrs'', ''origpost'', ',...
		'''perm_result'', ''boot_result'', ', ...
		'''cond_name'', ''behavname'', ''cond_selection'', ', ...
		'''common_channels'', ', ...
		'''common_conditions'', ''common_time_info'', ', ...
		'''num_cond_lst'', ''num_subj_lst'', ', ...
		'''subj_name_lst'', ''system'', ', ...
		'''chan_order'', ''setting2'', ''setting3'', ', ...
		'''setting4'', ''datamat_files'', ''isbehav'', ', ...
		'''behavdata_lst'', ''datamatcorrs_lst'', ', ...
		'''datamat_files_timestamp'', ''create_ver'''];

     if save_datamat
         saved_info = [saved_info, ', ''newdata_lst'''];
     end

  elseif(iscontrast)			% contrast analysis

     rri_progress_ui(progress_hdl, 'Runing Task PLS', 'Runing Task PLS ...');

     design = load(ContrastFile);

     [salience,s,designlv,scalpscores,designscores,lvintercorrs,design, ...
	perm_result,boot_result] = rri_taskpls_norotate(newdata_lst,design, ...
	num_subj_lst,num_cond_lst,num_boot,num_perm);

     saved_info=['''salience'', ''s'', ''designlv'', ''scalpscores'', ', ...
		'''designscores'', ''lvintercorrs'', ''design'', ', ...
		'''perm_result'', ''boot_result'', ', ...
		'''cond_name'', ''cond_selection'', ''common_channels'', ', ...
		'''common_conditions'', ''common_time_info'', ', ...
		'''num_cond_lst'', ''num_subj_lst'', ', ...
		'''subj_name_lst'', ''system'', ', ...
		'''chan_order'', ''setting2'', ''setting3'', ', ...
		'''setting4'', ''datamat_files'', ''isbehav'', ', ...
		'''datamat_files_timestamp'', ''create_ver'''];

     if save_datamat
         saved_info = [saved_info, ', ''newdata_lst'''];
     end

  else					% deviation analysis

     rri_progress_ui(progress_hdl, 'Runing Task PLS', 'Runing Task PLS ...');

     if (num_perm > 0) | (num_boot == 0)
        [salience,s,designlv,scalpscores,designscores,lvcorrs, ...
		origpost, perm_result] = ...
		rri_analysis_perm(ismean, ishelmert, iscontrast, isbehav, ...
		newdata_lst,num_cond_lst,num_subj_lst, ...
		behavdata_lst, helmertdata_lst, contrastdata_lst, ...
		num_perm, posthoc);
     end

     if (num_boot > 0)
        [salience,s,designlv,scalpscores,designscores,lvcorrs,boot_result]= ...
		rri_analysis_boot(ismean, ishelmert, iscontrast, isbehav, ...
		newdata_lst,num_cond_lst,num_subj_lst, ...
		behavdata_lst, helmertdata_lst, contrastdata_lst, ...
		num_boot, Clim);
     end

     saved_info=['''salience'', ''s'', ''designlv'', ''scalpscores'', ', ...
		'''designscores'', ', ...
		'''perm_result'', ''boot_result'', ', ...
		'''cond_name'', ''cond_selection'', ''common_channels'', ', ...
		'''common_conditions'', ''common_time_info'', ', ...
		'''num_cond_lst'', ''num_subj_lst'', ', ...
		'''subj_name_lst'', ''system'', ', ...
		'''chan_order'', ''setting2'', ''setting3'', ', ...
		'''setting4'', ''datamat_files'', ''isbehav'', ', ...
		'''datamat_files_timestamp'', ''create_ver'''];

     if save_datamat
         saved_info = [saved_info, ', ''newdata_lst'''];
     end

  end

  %  save results
  %
  msg = 'Saving to the disk ...';

  if exist('progress_hdl','var') & ishandle(progress_hdl)
     rri_progress_ui(progress_hdl, 'Save', msg);
  end

  elapsed_time = toc;
  disp('RunPLS is done ...');

  done = 0;

  while ~done
    try
       eval(['save(''', resultFile, ''',' saved_info,');']);
       done = 1;
    catch
       [result_file,result_path] = uiputfile('*ERPresult.mat', ...
			'Can not write file, please try again',350,150);

       if isequal(result_file,0)		% Cancel was clicked
          resultFile = [];
          msg1 = ['WARNING: No file is saved.'];
%          uiwait(msgbox(msg1,'Uncompleted','modal'));
          return;
       else
          resultFile = fullfile(result_path,result_file);
       end;
    end
  end

  return; 					% erp_analysis

