%PET_ANALYSIS Apply PLS on the PET data based on the information saved in
%    the datamat file.
%
%    Usage: [resultFile, elapsed_time] = ...
%	pet_analysis(isbehav, datamat_files, num_perm, ...
%	num_boot, Clim)
%
%    see also PLS_FMRI_ANALYSIS
%

%   Called by pet_analysis_ui
%
%  INPUT:
%    isbehav - 1 if run Behavior PLS; 0 for Task PLS.
%    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_perm - 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
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [resultFile, elapsed_time] = pet_analysis(varargin)

  progress_hdl = rri_progress_ui('initialize');

  isbehav = varargin{1};
  datamat_files = varargin{2};
  num_perm = varargin{3};
  num_boot = varargin{4};
  Clim = varargin{5};
  posthoc = varargin{6};
  cond_selection = varargin{7};
  behavname = varargin{8};
  behavdata = varargin{9};
  behavdata_lst = varargin{10};
  ContrastFile = varargin{11};
  iscontrast = varargin{12};
  ismean = varargin{13};
  save_datamat = varargin{14};

  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 '_PETresult.mat'],'Saving PLS Result',350,150);

  if isequal(result_file,0)		% Cancel was clicked
%     msg1 = ['WARNING: No file is saved.'];
%%     msgbox(msg1,'Uncompleted');
     resultFile = [];
%     disp('ERROR: Result file is not saved.');
     elapsed_time = 0;
     return;
  else
     resultFile = fullfile(result_path,result_file);
  end;

  % load the session info and datamat
  %
  [behavdata_lst, newdata_lst, newcoords, dims, num_cond_lst, ...
	num_subj_lst, subj_name_lst, voxel_size, origin, ...
	behavname, behavdata] = pet_get_common(datamat_files,  ...
	cond_selection, behavname, behavdata, ...
	behavdata_lst, progress_hdl);

   if isempty(newcoords)
      disp('ERROR: There are no common voxels found.');
      return;
   else
      for i = 1:length(newdata_lst)
         if isempty(newdata_lst{i})
            disp('ERROR: Merged datamat is empty.');
            return;
         end
      end
   end

  %  start PLS Run...
  %

  perm_result = [];
  boot_result = [];
  create_ver = plsgui_vernum;

  if(isbehav)

     rri_progress_ui(progress_hdl, 'Runing Behavior PLS', 'Runing Behavior PLS ...');

     if (num_perm > 0) | (num_boot == 0)
        [brainlv,s,behavlv,brainscores,behavscores,lvcorrs, ...
		origpost, perm_result, datamatcorrs_lst] = ...
		pet_analysis_perm(behavdata_lst,newdata_lst,num_cond_lst,...
		num_subj_lst,num_perm,isbehav,posthoc);
     end

     if (num_boot > 0)
        if num_perm == 0, origpost = []; end;
        [brainlv,s,behavlv,brainscores,behavscores,lvcorrs, ...
		boot_result, datamatcorrs_lst] = ...
		pet_analysis_boot(behavdata_lst,newdata_lst,num_cond_lst,...
		num_subj_lst,num_boot,isbehav,Clim);
     end

     saved_info=['''brainlv'', ''s'', ''behavlv'', ''brainscores'', ', ...
		'''behavscores'', ''lvcorrs'', ''origpost'', ',...
		'''perm_result'', ''boot_result'', ''datamatcorrs_lst'', ', ...
		'''newcoords'', ''cond_selection'', ''dims'', ', ...
		'''voxel_size'', ''origin'', ''behavname'', ', ...
		'''num_cond_lst'', ''num_subj_lst'', ''subj_name_lst'', ', ...
		'''behavdata_lst'', ''datamat_files'', ', ...
		'''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);

     [brainlv,s,designlv,brainscores,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=['''brainlv'', ''s'', ''designlv'', ''brainscores'', ', ...
		'''designscores'', ''lvintercorrs'', ''design'', ', ...
		'''perm_result'', ''boot_result'', ', ...
		'''newcoords'', ''cond_selection'', ''dims'', ', ...
		'''voxel_size'', ''origin'', ', ...
		'''num_cond_lst'', ''num_subj_lst'', ''subj_name_lst'', ', ...
		'''datamat_files'', ''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)
        [brainlv,s,designlv,brainscores,designscores,lvcorrs, ...
		origpost, perm_result, datamatcorrs_lst] = ...
		pet_analysis_perm(behavdata_lst,newdata_lst,num_cond_lst,...
		num_subj_lst,num_perm,isbehav,posthoc);
     end

     if (num_boot > 0)
        [brainlv,s,designlv,brainscores,designscores,lvcorrs, ...
		boot_result, datamatcorrs_lst] = ...
		pet_analysis_boot(behavdata_lst,newdata_lst,num_cond_lst,...
		num_subj_lst,num_boot,isbehav,Clim);
     end

     saved_info=['''brainlv'', ''s'', ''designlv'', ''brainscores'', ', ...
		'''designscores'', ', ...
		'''perm_result'', ''boot_result'', ', ...
		'''newcoords'', ''cond_selection'', ''dims'', ', ...
		'''voxel_size'', ''origin'', ', ...
		'''num_cond_lst'', ''num_subj_lst'', ''subj_name_lst'', ', ...
		'''datamat_files'', ''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;

  if isempty(brainlv)
     resultFile = '';
     done = 1;
  else
     disp('RunPLS is done ...');
     done = 0;
  end

  while ~done
    try
       eval(['save(''', resultFile, ''',' saved_info,');']);
       done = 1;
    catch
       [result_file,result_path] = uiputfile('*PETresult.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; 					% pet_analysis

