%PET_ANALYSIS_UI Analyse PET data in both Behavioral & Task methods
%	and write results into a result file based on session profiles
%	and user inputs.
%
%   Usage: pet_analysis_ui
%
%   See also PLS_ANALYSIS_UI
%

%   Called by plsgui
%
%   I - the action word to call itself recursively. If none, initialize session window.
%   O - none
%
%   Modified on 30-SEP-2002 by Jimmy Shen
%   Modified on 13-NOV-2002 by Jimmy Shen to add posthoc file selection
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function fig = pet_analysis_ui(varargin)

   if (nargin == 0),

      if exist('plslog.m','file')
         plslog('Run PET Analysis');
      end

      init;

      setappdata(gcf,'CallingFigure',gcbf);
      set(gcbf,'visible','off');

      uiwait(gcf);
      close(gcf);

      return;
   end;


   %  clear the message line,
   %
   h = findobj(gcf,'Tag','MessageLine');
   set(h,'String','');

   action = upper(varargin{1});

   switch (action)
     case {'MENU_DESELECT_CONDITION'}
        deselect_condition;
     case {'MENU_MODIFY_BEHAVDATA'}
        modify_behavdata;
     case {'MENU_CREATE_CONTRASTS'}
        pls_session = '';
        num_groups = 0;
        cond_selection = [];
        tmp = getappdata(gcf);

        if ~isempty(tmp.CurrGroupProfiles)
           pls_session = tmp.CurrGroupProfiles{1};
           num_groups = length(tmp.CurrGroupProfiles);
        end

        if ~isempty(tmp.cond_selection)
           cond_selection = tmp.cond_selection;
        end

        if isempty(pls_session)
           msg = 'Group need to be added before you can open contrast window';
           set(findobj(gcf,'Tag','MessageLine'),'String',msg);
           return;
        end

        contrast_ui_fig = rri_input_contrast_ui({'PET'},pls_session,cond_selection,num_groups);
        waitfor(contrast_ui_fig);
     case {'SELECT_GROUP'}
        SelectGroupProfiles;
     case {'DELETE_GROUP'}
        DeleteGroupProfiles;
     case {'ADD_GROUP'}
        AddGroupProfiles;
     case {'MOVE_SLIDER'}
	MoveSlider;
     case {'BUTTONDOWN_GROUP'}
        msg = 'Use Add button to add the group';
        set(findobj(gcf,'Tag','MessageLine'),'String',msg);
     case {'TOGGLE_SAVE_DATAMAT'}
        SwitchSaveDatamat;
     case {'TOGGLE_FULL_PATH'}
        SwitchFullPath;
     case {'TASKPLS_SELECTED'}
	SelectTaskPLS;
     case {'CONTRASTDATA_SELECTED'}
        SelectContrastData;
     case {'BEHAVPLS_SELECTED'}
	SelectBehavPLS;
     case {'EDIT_NUM_BOOT'}
	EditNumBoot;
     case{'EDIT_POSTHOC_DATA_FILE'}
	EditPosthocDataFile;
     case{'SELECT_POSTHOC_DATA_FILE'}
	SelectPosthocDataFile;
     case {'BROWSE_CONTRAST_FILE'}
        dlg_title = 'Select Contrast File';
        [contrast_file,contrast_path] = uigetfile('*_PETcontrast.txt',dlg_title,350,150);
        if (contrast_file ~= 0)
          c_filename = fullfile(contrast_path,contrast_file);
          set(findobj(gcf,'Tag','ContrastFileEdit'),'String',c_filename);
          set(findobj(gcf,'Tag','ContrastFileEdit'),'TooltipString',c_filename);
        end;

     % Run Task and Behavioral PLS
     %
     case {'RUN_BUTTON_PRESSED'}
        if SavePLSOptions == 1
           ExecutePLS;
        end

     case {'CANCEL_BUTTON_PRESSED'}
        uiresume(gcf);
        return;
     case {'DELETE_FIGURE'}
        calling_fig = getappdata(gcf,'CallingFigure');
        set(calling_fig,'visible','on');

        try
           load('pls_profile');
           pls_profile = which('pls_profile.mat');

           pet_analysis_pos = get(gcbf,'position');

           save(pls_profile, '-append', 'pet_analysis_pos');
        catch
        end
     otherwise
        disp(sprintf('ERROR: Unknown action "%s"',action));
   end;

   return;


% --------------------------------------------------------------------
function init()

   save_setting_status = 'on';
   pet_analysis_pos = [];

   try
      load('pls_profile');
   catch
   end

   if ~isempty(pet_analysis_pos) & strcmp(save_setting_status,'on')

      pos = pet_analysis_pos;

   else

      w = 0.6;
      h = 0.8;
      x = (1-w)/2;
      y = (1-h)/2;

      pos = [x y w h];

   end

   h0 = figure('Color',[0.8 0.8 0.8], ...
	'Units','normal', ...
	'Name','PLS Analysis for PET datamat', ...
	'NumberTitle', 'off', ...
   	'Position',pos, ...
   	'Menubar','none', ...
        'DeleteFcn','pet_analysis_ui(''DELETE_FIGURE'');', ...
   	'Tag','PermutationOptionsFigure', ...
   	'ToolBar','none');

   %-------------- group frame -----------------
   %
   x = 0.04;
   y = 0.66;
   w = 0.92;
   h = 0.3;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'Style','frame', ...
   	'Tag','GroupProfileFrame');

   x = 0.06;
   h = 0.05;
   y = 0.9 - 0.2*h;
   w = 0.5;

   pos = [x y w h];

   fnt = 0.5;

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Datamat File', ...
   	'Style','text', ...
   	'Tag','SessionProfileLabel');

   x = 0.08;
   y = 0.85;
   w = 0.15;

   pos = [x y w h];

   g_h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','right', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Group #1:', ...
   	'Style','text', ...
   	'Tag','GroupLabel');

   x = x+w+0.01;
   w = 0.4;

   pos = [x y w h];

   g_h2 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.9 0.9 0.9], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','', ...
   	'Style','edit', ...
	'Enable','inactive', ...
   	'Tag','GroupEdit');

   x = x + w + 0.01;
   w = 0.1;

   pos = [x y w h];

   g_h3 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Add', ...
   	'Tag','GroupAddButton');

   x = x + w;
   w = 0.1;

   pos = [x y w h];

   g_h4 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Select', ...
   	'Tag','GroupSelectButton');

   x = x + w + 0.01;
   w = 0.04;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...		% scroll bar
	'Style', 'slider', ...
   	'Units','normal', ...
   	'Min',1, ...
   	'Max',20, ...
   	'Value',20, ...
   	'Position',pos, ...
   	'Callback','pet_analysis_ui(''MOVE_SLIDER'');', ...
   	'Tag','GroupSlider');

   x = 0.08;
   y = 0.68 - 0.2*h;
   w = 0.18;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','right', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Number of groups:', ...
   	'Style','text', ...
   	'Tag','NumGroupLabel');

   x = x+w+0.02;
   y = 0.68;
   w = 0.08;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.9 0.9 0.9], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','0', ...
   	'Style','edit', ...
	'Enable','Inactive', ...
   	'Tag','NumberGroupEdit');

   x = x+w+0.04;
   w = 0.26;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
	'Style','checkbox', ...
        'Units','normal', ...
        'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
        'ListboxTop',0, ...
	'Value', 0, ...
        'Position',pos, ...
        'HorizontalAlignment','left', ...
        'String','Save Datamats', ...
        'Tag','SaveDatamatChkbox');

   x = x+w+0.04;
   w = 0.18;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
	'Style','checkbox', ...
        'Units','normal', ...
        'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
        'ListboxTop',0, ...
	'Value', 0, ...
        'Position',pos, ...
        'HorizontalAlignment','left', ...
        'String','Full Path', ...
        'Callback','pet_analysis_ui(''TOGGLE_FULL_PATH'');', ...
        'Tag','FullPathChkbox');

   %-------------- contrast frame -----------------
   %

   x = 0.04;
   y = 0.35;
   w = 0.92;
   h = 0.3;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'Style','frame', ...
   	'Tag','ContrastFrame');

   x = 0.06;
   h = 0.05;
   y = 0.59 - 0.2*h;
   w = 0.5;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','PLS Option', ...
   	'Style','text', ...
   	'Tag','ContrastsLabel');

   x = 0.12;
   y = 0.54;
   w = 0.35;
   h = 0.05;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Style','radiobutton', ...
	'string','Mean-Centering PLS', ...
	'Value',1, ...
   	'Tag','TaskPLSBn', ...
   	'Callback','pet_analysis_ui(''TASKPLS_SELECTED'');', ...
        'Position',pos);

   y = y - h;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Style','radio', ...
	'string','Non-Rotated Task PLS', ...
	'Value',0, ...
	'tag','SelectContrastData', ...
   	'Callback','pet_analysis_ui(''CONTRASTDATA_SELECTED'');', ...
	'position',pos);

   x = 0.08;
   w = 0.25;
   y = y - h  - 0.2*h;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','right', ...
   	'ListboxTop',0, ...
   	'Style','text', ...
	'string','Contrast Data File:', ...
	'Enable','off', ...
	'Value',0, ...
	'tag','ContrastDataLabel', ...
	'position',pos);

   x = 0.12;
   w = 0.35;
   x = 1 - x - w;
   y = 0.54;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Style','radiobutton', ...
	'string','Behavior PLS', ...
	'Value',0, ...
   	'Tag','BehavPLSBn', ...
   	'Callback','pet_analysis_ui(''BEHAVPLS_SELECTED'');', ...
	'enable','on', ...
        'Position',pos);

   x = 0.38;
   y = y - h*2;
   w = 0.32;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.9 0.9 0.9], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','', ...
   	'Style','edit', ...
	'enable','off', ...
   	'Tag','ContrastFileEdit');

   x = x+w+0.03;
   w = 0.15;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','center', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Browse', ...
	'enable','off', ...
   	'Callback','pet_analysis_ui(''BROWSE_CONTRAST_FILE'');', ...
   	'Tag','ContrastFileButton');

   x = 0.08;
   h = 0.05;
   y = 0.37 - 0.2*h;
   w = 0.25;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','right', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
	'Enable','off', ...
   	'String','Posthoc Data File:', ...
   	'Style','text', ...
   	'Tag','PosthocDataLabel');

   x = x+w+0.05;
   y = 0.37;
   w = 0.32;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.9 0.9 0.9], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','', ...
	'Enable','off', ...
   	'Style','edit', ...
   	'Callback','pet_analysis_ui(''EDIT_POSTHOC_DATA_FILE'');', ...
   	'Tag','PosthocDataEdit');

   x = x+w+0.03;
   w = 0.15;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','center', ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
	'Enable','off', ...
   	'String','Browse', ...
   	'Style','push', ...
   	'Callback','pet_analysis_ui(''SELECT_POSTHOC_DATA_FILE'');', ...
   	'Tag','PosthocDataBn');

   %-------------- permutation frame -----------------
   %

   x = 0.04;
   y = 0.12;
   w = 0.92;
   h = 0.22;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'Style','frame', ...
   	'Tag','PermutationFrame');

   x = 0.06;
   h = 0.05;
   y = 0.28 - 0.2*h - 0.02;
   w = 0.3;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'Position',pos, ...
   	'String','Number of Permutation:', ...
   	'Style','text', ...
   	'Tag','NumPermutationLabel');

   x = x+w+0.01;
   y = 0.28 - 0.02;
   w = 0.08;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[1 1 1], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','0', ...
   	'Style','edit', ...
   	'Tag','NumPermutationEdit');

   x = 0.06;
   y = 0.23 - 0.2*h - 0.02;
   w = 0.3;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'Position',pos, ...
   	'String','Number of Bootstrap:', ...
   	'Style','text', ...
   	'Tag','NumBootstrapLabel');

   x = x+w+0.01;
   y = 0.23 - 0.02;
   w = 0.08;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[1 1 1], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','0', ...
   	'Style','edit', ...
   	'Callback','pet_analysis_ui(''EDIT_NUM_BOOT'');', ...
   	'Tag','NumBootstrapEdit');

   x = x+w+0.01;
   w = 0.4;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'Position',pos, ...
   	'String','(require at least 3 subjs/group)', ...
   	'Style','text', ...
   	'Tag','BootstrapRequipementLabel');

   x = 0.06;
   y = 0.18 - 0.2*h - 0.02;
   w = 0.3;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.7 0.7 0.7], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'Position',pos, ...
   	'String','Confidence Level:', ...
   	'Style','text', ...
   	'Enable','off', ...
   	'Tag','ClimLabel');

   x = x+w+0.01;
   y = 0.18 - 0.02;
   w = 0.08;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
   	'BackgroundColor',[0.9 0.9 0.9], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','95', ...
   	'Style','edit', ...
   	'Enable','off', ...
   	'Tag','ClimEdit');

   x = 0.2;
   y = 0.06;
   w = 0.15;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Run', ...
   	'Callback','pet_analysis_ui(''RUN_BUTTON_PRESSED'');', ...
   	'Tag','RUNButton');

   x = 1-x-w;
   w = 0.15;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...
   	'Units','normal', ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'ListboxTop',0, ...
   	'Position',pos, ...
   	'String','Cancel', ...
   	'Callback','pet_analysis_ui(''CANCEL_BUTTON_PRESSED'');', ...
   	'Tag','CANCELButton');

   x = 0.01;
   y = 0;
   w = 1;

   pos = [x y w h];

   h1 = uicontrol('Parent',h0, ...		% Message Line
   	'Style','text', ...
   	'Units','normal', ...
   	'BackgroundColor',[0.8 0.8 0.8], ...
   	'ForegroundColor',[0.8 0.0 0.0], ...
	'fontunit','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','left', ...
   	'Position',pos, ...
   	'String','', ...
   	'Tag','MessageLine');

   % Menu Bar
   h_deselect = uimenu('Parent',h0, ...
	'Label', '&Deselect', ...
	'Tag', 'DeselectMenu');
   m1 = uimenu(h_deselect, ...
        'Label', '&Deselect Conditions', ...
   	'Callback','pet_analysis_ui(''MENU_DESELECT_CONDITION'');', ...
        'Tag', 'DeselectConditionMenu');
   m1 = uimenu(h_deselect, ...
        'Label', '&Modify Behavior Data', ...
   	'Callback','pet_analysis_ui(''MENU_MODIFY_BEHAVDATA'');', ...
        'Tag', 'ModifyBehavdataMenu');

   h_file = uimenu('Parent',h0, ...
	'Label', '&Contrast', ...
	'Tag', 'ContrastMenu');
   m1 = uimenu(h_file, ...
        'Label', 'Open Contrast Window', ...
   	'Callback','pet_analysis_ui(''MENU_CREATE_CONTRASTS'');', ...
        'Tag', 'CreateContrastsMenu');

   Hm_topHelp = uimenu('Parent',h0, ...
           'Label', '&Help', ...
           'Tag', 'Help');

   Hm_how = uimenu('Parent',Hm_topHelp, ...
           'Label', '&How to use this window?', ...
           'Callback','rri_helpfile_ui(''pet_analysis_hlp.txt'',''How to use PLS ANALYSIS'');', ...
           'Tag', 'How');

   Hm_new = uimenu('Parent',Hm_topHelp, ...
           'Label', '&What''s new', ...
	   'Callback','rri_helpfile_ui(''whatsnew.txt'',''What''''s new'');', ...
           'Tag', 'New');

   Hm_about = uimenu('Parent',Hm_topHelp, ...
           'Label', '&About this program', ...
           'Tag', 'About', ...
           'CallBack', 'plsgui_version');

   % save handles for the group profiles
   %
   group_hdls = [g_h1, g_h2, g_h3, g_h4];
   setappdata(h0,'Group_hlist',group_hdls);

   group_template = copyobj(group_hdls,h0);
   set(group_template,'visible','off','Tag','GroupUIControls');
   setappdata(h0,'GroupTemplate',group_template);

   group_h = 0.05;
   setappdata(h0,'GroupHeight', group_h);

   lower_h = 0.08;	% vert. space for Number of groups etc.
   setappdata(h0,'lower_h',lower_h);

   setappdata(h0,'CurrGroupProfiles',[]);
   setappdata(h0,'TopGroupIdx',1);
   setappdata(h0,'full_path', 0);
   setappdata(h0,'num_selected_cond',1);
   setappdata(h0,'posthoc_data_file','');

   setappdata(h0,'cond_selection',[]);
   setappdata(gcf,'behavname',{});
   setappdata(gcf,'behavdata',[]);
   setappdata(gcf,'behavdata_lst',{});

   SetupGroupRows;
   CreateAddRow;
   DisplayGroupProfiles(0);
   UpdateSlider;

   return;							% Init


%----------------------------------------------------------------------------
function SetupGroupRows()

   group_hdls = getappdata(gcf,'Group_hlist');
   group_h = getappdata(gcf,'GroupHeight');
   lower_h = getappdata(gcf,'lower_h');

   bottom_pos = get(findobj(gcf,'Tag','GroupProfileFrame'),'Position');
   top_pos = get(group_hdls(1,1),'Position');

   rows = floor(( top_pos(2) - bottom_pos(2) - lower_h) / group_h + 1);
   v_pos = top_pos(2) - [0:rows-1]*group_h;

   group_template = getappdata(gcf,'GroupTemplate');
   edit_cbf = '';
   select_cbf = 'pet_analysis_ui(''SELECT_GROUP'');';
   delete_cbf = 'pet_analysis_ui(''DELETE_GROUP'');';
   buttondown_group = 'pet_analysis_ui(''BUTTONDOWN_GROUP'');';

   nr = size(group_hdls,1);
   if (rows < nr)			% too many rows
      for i=rows+1:nr,
          delete(group_hdls(i,:));
      end;
      group_hdls = group_hdls(1:rows,:);
   else					% add new rows
      for i=nr+1:rows,
         new_g_hdls = copyobj(group_template,gcf);
         group_hdls = [group_hdls; new_g_hdls'];
      end;
   end;

   v = 'off';
   top_g_hdls = group_hdls(1,:);
   for i=1:rows,
      new_g_hdls = group_hdls(i,:);
      pos = get(top_g_hdls(1),'Position'); pos(2) = v_pos(i);
      set(new_g_hdls(1),'String','?','Position',pos,'Visible',v,'UserData',i);

      pos = get(top_g_hdls(2),'Position'); pos(2) = v_pos(i);
      set(new_g_hdls(2),'String','', 'Position',pos, 'Visible',v, ...
                        'UserData',i, 'Callback',edit_cbf, ...
			'ButtonDownFcn',buttondown_group);

      pos = get(top_g_hdls(3),'Position'); pos(2) = v_pos(i);
      set(new_g_hdls(3),'String','Delete','Position',pos,'Visible',v, ...
                        'UserData',i,'Callback',delete_cbf);

      pos = get(top_g_hdls(4),'Position'); pos(2) = v_pos(i);
      set(new_g_hdls(4),'String','Select','Position',pos,'Visible',v, ...
                        'UserData',i,'Callback',select_cbf);

   end;


   %  setup slider position
   %
   slider_hdl = findobj(gcf,'Tag','GroupSlider');
   s_pos = get(slider_hdl,'Position');

   s_pos(2) = v_pos(end);
   s_pos(4) = group_h * rows;
   set(slider_hdl,'Position',s_pos);


   setappdata(gcf,'Group_hlist',group_hdls);
   setappdata(gcf,'NumRows',rows);

   return;					% SetupGroupRows


%----------------------------------------------------------------------------
function DisplayGroupProfiles(full_path)

   curr_group_profiles = getappdata(gcf,'CurrGroupProfiles');
   top_group_idx = getappdata(gcf,'TopGroupIdx');
   group_hdls = getappdata(gcf,'Group_hlist');
   rows = getappdata(gcf,'NumRows');

   num_group = length(curr_group_profiles);

   last_row = 0;
   group_idx = top_group_idx;

   for i=1:rows
      g_hdls = group_hdls(i,:);
      if (group_idx <= num_group),
         set(g_hdls(1),'String',sprintf('Group #%d:',group_idx),'Visible','on');

         curr_group_name = sprintf('%s',curr_group_profiles{group_idx});
         if(full_path)
            set(g_hdls(2), 'String', curr_group_name, ...
                       'Visible','on');
         else
            [p_path, p_name, p_ext] = fileparts(curr_group_name);
            curr_group_name = [p_name p_ext];
            set(g_hdls(2), 'String', curr_group_name, ...
                       'Visible','on');
         end

         set(g_hdls(3),'String','Delete','Enable','on','Visible','on');
         set(g_hdls(4),'String','Select','Enable','on','Visible','on');

         group_idx = group_idx + 1;
         last_row = i;
      else
         set(g_hdls(1),'String','','Visible','off');
         set(g_hdls(2),'String','','Visible','off');
         set(g_hdls(3),'String','Delete','Visible','off');
         set(g_hdls(4),'String','Select','Visible','off');
      end;
   end;

   %  display or hide the add row
   %
   if (last_row < rows)
      row_idx = last_row+1;
      g_hdls = group_hdls(row_idx,:);
      pos = get(g_hdls(1),'Position');
      ShowAddRow(group_idx,pos(2),row_idx);
   else
      HideAddRow;
   end;

   %  display or hide the slider
   %
   if (top_group_idx ~= 1) | (last_row == rows)
     ShowSlider;
   else
     HideSlider;
   end;

   return;						% DisplayGroupProfiles


%----------------------------------------------------------------------------
function CreateAddRow()

   group_template = getappdata(gcf,'GroupTemplate');
   buttondown_group = 'pet_analysis_ui(''BUTTONDOWN_GROUP'');';

   a_hdls = copyobj(group_template,gcf);

   set(a_hdls(1),'String','','Foreground',[0.4 0.4 0.4],'Visible','off', ...
                 'UserData',1);

   set(a_hdls(2),'String','','Background',[0.9 0.9 0.9], 'Visible','off',...
		 'ButtonDownFcn',buttondown_group,'enable','inactive');

   set(a_hdls(3),'String','Add','Visible','off', ...
		     'Callback','pet_analysis_ui(''ADD_GROUP'');');

   set(a_hdls(4),'Visible','off','Enable','off');

   setappdata(gcf,'AddRowHdls',a_hdls);

   return;						% CreateAddRow


%----------------------------------------------------------------------------
function ShowAddRow(group_idx,v_pos,row_idx)

   a_hdls = getappdata(gcf,'AddRowHdls');
   g_hdls = getappdata(gcf,'Group_hlist');

   for j=1:length(a_hdls),
      new_pos = get(g_hdls(1,j),'Position');
      new_pos(2) = v_pos;

      set(a_hdls(j),'Position',new_pos);
      set(a_hdls(j),'Visible','on');
   end;

   set(a_hdls(1),'String',sprintf('Group #%d:',group_idx), ...
		'Visible','On','UserData',row_idx);
   set(a_hdls(2),'String','');
   set(a_hdls(4),'Visible','Off');


   return;						% ShowAddRow


%----------------------------------------------------------------------------
function HideAddRow()

   a_hdls = getappdata(gcf,'AddRowHdls');
   for j=1:length(a_hdls),
      set(a_hdls(j),'Visible','off');
   end;

   return;						% HideAddRow


%----------------------------------------------------------------------------
function DeleteGroupProfiles()

   curr_group_profiles = getappdata(gcf,'CurrGroupProfiles');
   group_hdls = getappdata(gcf,'Group_hlist');

   row_idx = get(gcbo,'UserData');
   group_id = get(group_hdls(row_idx,1),'String');
   start_idx = findstr(group_id,'#')+1;
   group_idx = str2num(group_id(start_idx:end-1));

   mask = ones(1,length(curr_group_profiles));  mask(group_idx) = 0;
   idx = find(mask == 1);
   curr_group_profiles = curr_group_profiles(idx);

   num_group = length(curr_group_profiles);
   set(findobj(gcf,'Tag','NumberGroupEdit'),'String',num2str(num_group));

   setappdata(gcf,'CurrGroupProfiles',curr_group_profiles);

   full_path = getappdata(gcf,'full_path');
   DisplayGroupProfiles(full_path);

   UpdateSlider;

   return;						% DeleteGroupProfiles


%----------------------------------------------------------------------------
function AddGroupProfiles()

   curr_group_profiles = getappdata(gcf,'CurrGroupProfiles');
   num_group = length(curr_group_profiles)+1;

   rows = getappdata(gcf,'NumRows');
   a_hdls = getappdata(gcf,'AddRowHdls');

   group_id = get(a_hdls(1),'String');
   start_idx = findstr(group_id,'#')+1;
   group_idx = str2num(group_id(start_idx:end-1));

   group_profile = get(a_hdls(2),'String');

   curr = pwd;
   if isempty(curr)
      curr = filesep;
   end

   pf_path = curr;
   pf_name = '';

   % if no pre-entry, open rri_getfiles window
   % otherwise, just read from pre-entry
   %
   if isempty(group_profile)

      if(group_idx ~= 1)
         [pf_path pf_name pf_ext] = fileparts(curr_group_profiles{group_idx-1});
      end

      pf_path = fullfile(pf_path, '*_PETdatamat.mat');
      [pf_name pf_path] = uigetfile(pf_path, 'Select a session profile',350,150);

	% if there is error, uigetfile return 0 for pf_name or pf_path
	% isstr(0) return 0
        %
      if (~isstr(pf_name) | ~isstr(pf_path))
         return;
      end

      curr_group_profiles{num_group} = fullfile(pf_path, pf_name);

   elseif exist(group_profile) ~= 2
      msg = 'ERROR: Could not find the session profile you specified.';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   else
      curr_group_profiles{num_group} = group_profile;
   end;

   if isempty(getappdata(gcf,'cond_selection'))
      tmp = load(curr_group_profiles{1});
      cond_selection = ones(1, tmp.session_info.num_conditions);
      setappdata(gcf, 'cond_selection', cond_selection);
   end

   setappdata(gcf,'behavname',{});
   setappdata(gcf,'behavdata',[]);
   setappdata(gcf,'behavdata_lst',{});

   setappdata(gcf,'CurrGroupProfiles',curr_group_profiles);
   set(findobj(gcf,'Tag','NumberGroupEdit'),'String',num2str(num_group));

   new_group_row = get(a_hdls(1),'UserData');
   if (new_group_row == rows),  	% the new group row is the last row
      top_group_idx = getappdata(gcf,'TopGroupIdx');
      setappdata(gcf,'TopGroupIdx',top_group_idx+1);
   end;

   group_hdls = getappdata(gcf,'Group_hlist');

   full_path = getappdata(gcf,'full_path');
   DisplayGroupProfiles(full_path);

   UpdateSlider;

   return;						% AddGroupProfiles


%----------------------------------------------------------------------------
function SelectGroupProfiles(group_idx)

   curr_group_profiles = getappdata(gcf,'CurrGroupProfiles');
   group_hdls = getappdata(gcf,'Group_hlist');

   row_idx = get(gcbo,'UserData');
   group_id = get(group_hdls(row_idx,1),'String');
   start_idx = findstr(group_id,'#')+1;
   group_idx = str2num(group_id(start_idx:end-1));

   curr_profile = curr_group_profiles{group_idx};
   [pf_path pf_name pf_ext] = fileparts(curr_profile);
   pf_path = fullfile(pf_path, '*_PETdatamat.mat');
   [pf_name pf_path] = uigetfile(pf_path, 'Select a session profile',350,150);

   curr_group_profiles{group_idx} = fullfile(pf_path, pf_name);

	% if there is error, uigetfile return 0 for pf_name or pf_path
	% isstr(0) return 0
        %
      if (~isstr(pf_name) | ~isstr(pf_path))
         return;
      end;

   profiles_str = fullfile(pf_path, pf_name);

   if ~isempty(profiles_str)
      curr_group_profiles{group_idx} = profiles_str;
      setappdata(gcf,'CurrGroupProfiles',curr_group_profiles);
      set(group_hdls(row_idx,2),'String',profiles_str);

      tmp = load(curr_group_profiles{1});
      cond_selection = ones(1, tmp.session_info.num_conditions);
      setappdata(gcf, 'cond_selection', cond_selection);
      setappdata(gcf,'behavname',{});
      setappdata(gcf,'behavdata',[]);
      setappdata(gcf,'behavdata_lst',{});
   end;

   full_path = getappdata(gcf,'full_path');
   DisplayGroupProfiles(full_path);

   UpdateSlider;

   return;						% SelectGroupProfiles


%----------------------------------------------------------------------------
function MoveSlider()

   slider_hdl = findobj(gcf,'Tag','GroupSlider');
   curr_value = round(get(slider_hdl,'Value'));
   total_rows = round(get(slider_hdl,'Max'));

   top_group_idx = total_rows - curr_value + 1;

   setappdata(gcf,'TopGroupIdx',top_group_idx);

   full_path = getappdata(gcf,'full_path');
   DisplayGroupProfiles(full_path);

   return;						% MoveSlider


%----------------------------------------------------------------------------
function UpdateSlider()

   top_group_idx = getappdata(gcf,'TopGroupIdx');
   rows = getappdata(gcf,'NumRows');

   curr_group_profiles = getappdata(gcf,'CurrGroupProfiles');
   num_groups = length(curr_group_profiles);

   total_rows = num_groups + 1;
   slider_hdl = findobj(gcf,'Tag','GroupSlider');

   if (total_rows > 1)           % don't need to update when no group
       set(slider_hdl,'Min',1,'Max',total_rows, ...
                  'Value',total_rows-top_group_idx+1, ...
                  'Sliderstep',[1/(total_rows-1)-0.00001 1/(total_rows-1)]);
   end;

   return;                                              % UpdateSlider


%----------------------------------------------------------------------------
function ShowSlider()

   slider_hdl = findobj(gcf,'Tag','GroupSlider');
   set(slider_hdl,'visible','on'); 

   return;						% ShowSlider


%----------------------------------------------------------------------------
function HideSlider()

   slider_hdl = findobj(gcf,'Tag','GroupSlider');
   set(slider_hdl,'visible','off');

   return;						% HideSlider


%----------------------------------------------------------------------------
function SelectTaskPLS;

   if get(findobj(gcf,'Tag','TaskPLSBn'),'Value') == 0		% click itself
      set(findobj(gcf,'Tag','TaskPLSBn'),'Value',1);
   else
      set(findobj(gcf,'Tag','SelectContrastData'),'Value',0);
      set(findobj(gcf,'Tag','BehavPLSBn'),'Value',0);

      set(findobj(gcf,'Tag','ContrastFileEdit'),'BackGroundColor',[0.9 0.9 0.9]);
      set(findobj(gcf,'Tag','ContrastDataLabel'),'Enable','off');
      set(findobj(gcf,'Tag','ContrastFileEdit'),'Enable','off');
      set(findobj(gcf,'Tag','ContrastFileButton'),'Enable','off');

      set(findobj(gcf,'Tag','PosthocDataEdit'),'BackGroundColor',[0.9 0.9 0.9]);
      set(findobj(gcf,'Tag','PosthocDataLabel'),'Enable','off');
      set(findobj(gcf,'Tag','PosthocDataEdit'),'Enable','off');
      set(findobj(gcf,'Tag','PosthocDataBn'),'Enable','off');

      set(findobj(gcf,'Tag','ClimEdit'),'BackGroundColor',[0.9 0.9 0.9]);
      set(findobj(gcf,'Tag','ClimLabel'),'Enable','off');
      set(findobj(gcf,'Tag','ClimEdit'),'Enable','off');
   end

   return;						% SelectTaskPLS


%----------------------------------------------------------------------------
function SelectContrastData;

   if get(findobj(gcf,'Tag','SelectContrastData'),'Value') == 0	% click itself
      set(findobj(gcf,'Tag','SelectContrastData'),'Value',1);
   else
      set(findobj(gcf,'Tag','TaskPLSBn'),'Value',0);
      set(findobj(gcf,'Tag','BehavPLSBn'),'Value',0);

      set(findobj(gcf,'Tag','PosthocDataEdit'),'BackGroundColor',[0.9 0.9 0.9]);
      set(findobj(gcf,'Tag','PosthocDataLabel'),'Enable','off');
      set(findobj(gcf,'Tag','PosthocDataEdit'),'Enable','off');
      set(findobj(gcf,'Tag','PosthocDataBn'),'Enable','off');

      set(findobj(gcf,'Tag','ContrastFileEdit'),'BackGroundColor',[1 1 1]);
      set(findobj(gcf,'Tag','ContrastDataLabel'),'Enable','on');
      set(findobj(gcf,'Tag','ContrastFileEdit'),'Enable','on');
      set(findobj(gcf,'Tag','ContrastFileButton'),'Enable','on');

      set(findobj(gcf,'Tag','ClimEdit'),'BackGroundColor',[0.9 0.9 0.9]);
      set(findobj(gcf,'Tag','ClimLabel'),'Enable','off');
      set(findobj(gcf,'Tag','ClimEdit'),'Enable','off');
   end

   return;						% SelectContrastData


%----------------------------------------------------------------------------
function SelectBehavPLS

   if get(findobj(gcf,'Tag','BehavPLSBn'),'Value') == 0		% click itself
      set(findobj(gcf,'Tag','BehavPLSBn'),'Value',1);
   else
      set(findobj(gcf,'Tag','TaskPLSBn'),'Value',0);
      set(findobj(gcf,'Tag','SelectContrastData'),'Value',0);

      set(findobj(gcf,'Tag','ContrastFileEdit'),'BackGroundColor',[0.9 0.9 0.9]);
      set(findobj(gcf,'Tag','ContrastDataLabel'),'Enable','off');
      set(findobj(gcf,'Tag','ContrastFileEdit'),'Enable','off');
      set(findobj(gcf,'Tag','ContrastFileButton'),'Enable','off');

      set(findobj(gcf,'Tag','PosthocDataEdit'),'BackGroundColor',[1 1 1]);
      set(findobj(gcf,'Tag','PosthocDataLabel'),'Enable','on');
      set(findobj(gcf,'Tag','PosthocDataEdit'),'Enable','on');
      set(findobj(gcf,'Tag','PosthocDataBn'),'Enable','on');

      num_boot = str2num(get(findobj(gcf,'Tag','NumBootstrapEdit'),'String'));
      if  ~isempty(num_boot) & num_boot ~= 0
         set(findobj(gcf,'Tag','ClimEdit'),'BackGroundColor',[1 1 1]);
         set(findobj(gcf,'Tag','ClimLabel'),'Enable','on');
         set(findobj(gcf,'Tag','ClimEdit'),'Enable','on');
      end

   end

   return;						% SelectBehavPLS


%----------------------------------------------------------------------------
function EditNumBoot

   if get(findobj(gcf,'Tag','BehavPLSBn'),'Value') == 1		% behavpls
      num_boot = str2num(get(findobj(gcf,'Tag','NumBootstrapEdit'),'String'));
      if  ~isempty(num_boot) & num_boot ~= 0
         set(findobj(gcf,'Tag','ClimEdit'),'BackGroundColor',[1 1 1]);
         set(findobj(gcf,'Tag','ClimLabel'),'Enable','on');
         set(findobj(gcf,'Tag','ClimEdit'),'Enable','on');
      else
         set(findobj(gcf,'Tag','ClimEdit'),'BackGroundColor',[0.9 0.9 0.9]);
         set(findobj(gcf,'Tag','ClimLabel'),'Enable','off');
         set(findobj(gcf,'Tag','ClimEdit'),'Enable','off');
      end
   end

   return;						% EditNumBoot


%----------------------------------------------------------------------------
function SelectContrastNone;

   if get(findobj(gcf,'Tag','ContrastNoneChkBox'),'Value') == 0		% click itself
      set(findobj(gcf,'Tag','ContrastNoneChkBox'),'Value',1);
   else
      set(findobj(gcf,'Tag','ContrastHelmertChkBox'),'Value',0);

      set(findobj(gcf,'Tag','ContrastFileChkBox'),'Value',0);
      set(findobj(gcf,'Tag','ContrastFileEdit'),'Enable','off');
      set(findobj(gcf,'Tag','ContrastFileButton'),'Enable','off');
   end

   return;						% SelectContrastNone


%----------------------------------------------------------------------------
function SelectContrastHelmert

   if get(findobj(gcf,'Tag','ContrastHelmertChkBox'),'Value') == 0
      set(findobj(gcf,'Tag','ContrastHelmertChkBox'),'Value',1);
   else
      set(findobj(gcf,'Tag','ContrastNoneChkBox'),'Value',0);

      set(findobj(gcf,'Tag','ContrastFileChkBox'),'Value',0);
      set(findobj(gcf,'Tag','ContrastFileEdit'),'Enable','off');
      set(findobj(gcf,'Tag','ContrastFileButton'),'Enable','off');
   end

   return;						% SelectContrastHelmert


%----------------------------------------------------------------------------
function SelectContrastFile

   if get(findobj(gcf,'Tag','ContrastFileChkBox'),'Value') == 0
      set(findobj(gcf,'Tag','ContrastFileChkBox'),'Value',1);
   else
      set(findobj(gcf,'Tag','ContrastNoneChkBox'),'Value',0);
      set(findobj(gcf,'Tag','ContrastHelmertChkBox'),'Value',0);

      set(findobj(gcf,'Tag','ContrastFileEdit'),'Enable','on');
      set(findobj(gcf,'Tag','ContrastFileButton'),'Enable','on');
   end

   return;						% SelectContrastFile

%----------------------------------------------------------------------------
function status = SavePLSOptions

   status = -1;
   setappdata(gcf,'PLSoptions',[]);

   %  profiles
   %
   curr_profiles = getappdata(gcf,'CurrGroupProfiles');
   num_groups = length(curr_profiles);

   if num_groups == 0
      msg = 'ERROR: Datamat group is not specified.';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end

   save_datamat = get(findobj(gcf,'Tag','SaveDatamatChkbox'),'Value');
   isbehav = get(findobj(gcf,'Tag','BehavPLSBn'),'Value');
   iscontrast = get(findobj(gcf,'Tag','SelectContrastData'),'Value');

   PLSoptions.save_datamat = save_datamat;
   PLSoptions.cond_selection = getappdata(gcf,'cond_selection');
   PLSoptions.behavname = getappdata(gcf,'behavname');
   PLSoptions.behavdata = getappdata(gcf,'behavdata');
   PLSoptions.behavdata_lst = getappdata(gcf,'behavdata_lst');

   %  Check data integrity for behav PLS analysis
   %
   PLSoptions.profiles = cell(1,num_groups);

   for i=1:num_groups
      PLSoptions.profiles{i} = curr_profiles{i};

      behavname = {};

      warning off;
      try
         load(curr_profiles{i},'behavname');
      catch
      end
      warning on;

%      if isbehav & isempty(behavname) & isempty(PLSoptions.behavdata)
%         msg = ['ERROR: Behav data is required for BehavPLS'];
%%		curr_profiles{i}, '.'];
%         set(findobj(gcf,'Tag','MessageLine'),'String',msg);
%         return;
%      end
   end

   % make sure the conditions in each profile are the same
   %
   total_profiles = ValidateProfiles(PLSoptions.profiles);

   if (total_profiles == -1)
      return;
   end;

   PLSoptions.TotalNumberProfiles = total_profiles;

   if (isbehav == 1)

      PLSoptions.ismean = 0;
      PLSoptions.isbehav = 1;
      PLSoptions.iscontrast = 0;
      PLSoptions.ContrastFile = [];

      %  posthoc data file
      %
      posthoc_data_file = getappdata(gcf, 'posthoc_data_file');
      if ~isempty(posthoc_data_file)
         try
            PLSoptions.posthoc = load(posthoc_data_file);
         catch
            msg = sprintf('Invalid posthoc data file.');
            set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
            return;
         end
         [r_posthoc,c_posthoc] = size(PLSoptions.posthoc);
         if r_posthoc ~= getappdata(gcf,'num_selected_behav') * getappdata(gcf,'num_selected_cond') * num_groups
            msg = sprintf('Rows in Posthoc data file do not match.');
            set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
            return;
         end
      else
         PLSoptions.posthoc = [];
      end

   elseif (iscontrast == 1)			% contrast

      PLSoptions.ismean = 0;
      PLSoptions.isbehav = 0;
      PLSoptions.iscontrast = 1;
      PLSoptions.posthoc = [];
      PLSoptions.ContrastFile = get(findobj(gcf,'tag','ContrastFileEdit'),'string');

      if isempty(PLSoptions.ContrastFile),
          msg = 'ERROR: Contrast file is not specified.';
          set(findobj(gcf,'Tag','MessageLine'),'String',msg);
          return;
      end;

      try
          use_contrast = load(PLSoptions.ContrastFile,'conditions');
          cond_selection = getappdata(gcf,'cond_selection');

          if size(use_contrast,1) ~= sum(cond_selection)*num_groups
             msg = 'ERROR: incompetible number of condition in contrast.';
             set(findobj(gcf,'Tag','MessageLine'),'String',msg);
             return;
          end
      catch
          msg = 'ERROR: cannot load the contrast file.';
          set(findobj(gcf,'Tag','MessageLine'),'String',msg);
          return;
      end;

      %  check if the contrast matrix is rank deficient
      %
      if (rank(use_contrast) ~= size(use_contrast,2))
         msg = 'Your Contrast matrix is rank deficient. Please check your contrasts and run the program again';
         uiwait(msgbox(msg,'Warning: Contrasts are not linear independent','modal'));
%         set(findobj(gcf,'Tag','MessageLine'),'String',msg);
%         return;	
      end;

      %  check if the contrast matrix is orthogonal
      %
      if abs(sum(sum(use_contrast'*use_contrast-diag(diag(use_contrast'*use_contrast))))) > 1e-6
         msg = 'Effects expressed by each contrast are not independent. Check variable lvintercorrs in result file to see overlap of effects between LVs';
         uiwait(msgbox(msg,'Warning: Contrasts are not orthogonal','modal'));
%         set(findobj(gcf,'Tag','MessageLine'),'String',msg);
%         return;	
      end

   else						% deviation

      PLSoptions.ismean = 1;
      PLSoptions.isbehav = 0;
      PLSoptions.iscontrast = 0;
      PLSoptions.posthoc = [];
      PLSoptions.ContrastFile = [];

   end

   %  number of permutation
   %
   h = findobj(gcf,'Tag','NumPermutationEdit');
   PLSoptions.num_perm = str2num(get(h,'String'));
   if isempty(PLSoptions.num_perm)
      msg = 'ERROR: Invalid number of permutation specified.';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end;

   %  number of bootstrap
   %
   h = findobj(gcf,'Tag','NumBootstrapEdit');
   PLSoptions.num_boot = str2num(get(h,'String'));
   if isempty(PLSoptions.num_boot)
      msg = 'ERROR: Invalid number of bootstrap specified.';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end;

   %  upper limit of confidence interval estimated
   %
   h = findobj(gcf,'Tag','ClimEdit');
   PLSoptions.Clim = str2num(get(h,'String'));
   if isempty(PLSoptions.Clim)
      msg = 'ERROR: Invalid upper limit of confidence specified.';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end;

%   if (PLSoptions.num_boot > 0)
%      min_subj_required = 3;
%         for i=1:num_groups,
%           if (length(PLSoptions.profiles{i}) < min_subj_required)
%              msg = 'All groups must have at least 3 subjects for bootstrap.';
%              set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ' msg]);
%              return;
%           end
%         end
%   end;

   % everything should be alright, save the option now
   %
   setappdata(gcf,'PLSoptions',PLSoptions);
   % save PLSoptions PLSoptions;

   status = 1;

   return;						% SavePLSoptions


%----------------------------------------------------------------------------
function total_profiles = ValidateProfiles(group_profiles,conditions),

   num_groups = length(group_profiles);

   cell_buffer = [];
   for i=1:num_groups,
      cell_buffer = [cell_buffer; group_profiles(i)];
   end;

   % check for duplicated profile
   %
   total_profiles = length(cell_buffer);
   for i=1:total_profiles-1,
      for j=i+1:total_profiles,
         if isequal(cell_buffer{i},cell_buffer{j}),
            [p_path, p_name, p_ext] = fileparts(cell_buffer{i});
            msg = sprintf('"%s" has been used for more than 1 group',p_name);
            set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
            total_profiles = -1;
            return;
         else
            set(findobj(gcf,'Tag','MessageLine'),'String','');
         end;
      end;
   end;


   % make sure all conditions are the same
   %
   s = load(cell_buffer{1},'session_info');
   prev_condition = s.session_info.condition;
   prev_select = getappdata(gcf,'cond_selection');
   for i=2:total_profiles,
      s = load(cell_buffer{i},'session_info');
      curr_condition = s.session_info.condition;
      curr_select = getappdata(gcf,'cond_selection');
      if ~isequal(curr_condition,prev_condition)...
	 | ~isequal(curr_select, prev_select)
          [p_path, p_name, p_ext] = fileparts(cell_buffer{i});
          msg = sprintf('Incompatible conditions found in "%s".',p_name);
          set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
          total_profiles = -1;
          return;
      else
          prev_condition = curr_condition;
          prev_select = curr_select;
      end;
   end;

   setappdata(gcf,'num_selected_cond',sum(prev_select));


   isbehav = get(findobj(gcf,'Tag','BehavPLSBn'),'Value');

   if isbehav
      % make sure all behaviors are the same
      %
      newbehavdata = getappdata(gcf,'behavdata');
      s = load(cell_buffer{1},'behavdata','behavname');

      if(~exist('behavname','var'))
         s.behavname = {};
         for j=1:size(s.behavdata, 2)
            s.behavname = [s.behavname, {['behav', num2str(j)]}];
         end
      end
      
      prev_behavname = s.behavname;
      for i=2:total_profiles,
         s = load(cell_buffer{i},'behavdata','behavname');

         if(~exist('behavname','var'))
            s.behavname = {};
            for j=1:size(s.behavdata, 2)
               s.behavname = [s.behavname, {['behav', num2str(j)]}];
            end
         end

         curr_behavname = s.behavname;
         if ~isequal(curr_behavname,prev_behavname) & isempty(newbehavdata)
             [p_path, p_name, p_ext] = fileparts(cell_buffer{i});
             msg = sprintf('Incompatible behaviors found in "%s".',p_name);
             set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
             total_profiles = -1;
             return;
         else
             prev_behavname = curr_behavname;
         end;
      end;

      setappdata(gcf,'num_selected_behav',size(s.behavdata,2));

   end


   return;						% ValidateProfiles


%----------------------------------------------------------------------------
function SwitchFullPath()

   h = findobj(gcf,'Tag','FullPathChkbox');
   full_path = get(h,'Value');

   setappdata(gcf,'full_path',full_path);
   DisplayGroupProfiles(full_path);

   return;					% SwitchFullPath


%----------------------------------------------------------------------------
function ExecutePLS()

   tic
   PLSoptions = getappdata(gcf,'PLSoptions');
   progress_hdl = rri_progress_ui('initialize','Loading datamat');

   [resultFile, elapsed_time] = pet_analysis(PLSoptions.isbehav, ...
	PLSoptions.profiles, PLSoptions.num_perm, ...
	PLSoptions.num_boot, PLSoptions.Clim, PLSoptions.posthoc, ...
	PLSoptions.cond_selection, PLSoptions.behavname, ...
	PLSoptions.behavdata, PLSoptions.behavdata_lst, PLSoptions.ContrastFile, ...
	PLSoptions.iscontrast, PLSoptions.ismean, PLSoptions.save_datamat);

   if exist('progress_hdl','var') & ishandle(progress_hdl)
      close(progress_hdl);
   end

   msg1 = ['Result file "',resultFile,'" has been created and saved on your hard drive.'];
   msg2 = ['The total elapse time to build this datamat is ',num2str(elapsed_time),' seconds.'];

   if ~isempty(resultFile)
      uiwait(msgbox({msg1;'';msg2},'Completed','modal'));
%      uiwait(msgbox(msg1,'Completed','modal'));
   end

   uiresume;
   return;						% ExecutePLS


%----------------------------------------------------------------------------
function EditPosthocDataFile

   posthoc_data_file = deblank(strjust(get(gcbo,'String'),'left'));

   set(gcbo,'String',posthoc_data_file);

   if ~isempty(posthoc_data_file)
      if ( exist(posthoc_data_file,'file') == 2 )		% specified file exists
         setappdata(gcf,'posthoc_data_file',posthoc_data_file);
         return;
      end;

      if ( exist(posthoc_data_file,'dir') == 7 )		% it is a directory!
         msg = 'ERROR: The specified file is a direcotry!';
         set(findobj(gcf,'Tag','MessageLine'),'String',msg);
         setappdata(gcf,'posthoc_data_file','');
         return;
      end;
   else
%      msg = 'ERROR: Invalid input file!';
%      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      setappdata(gcf,'posthoc_data_file','');
      return;
   end;

   return;						% EditPosthocDataFile


%----------------------------------------------------------------------------
function SelectPosthocDataFile

   h = findobj(gcf,'Tag','PosthocDataEdit');

   [filename,pathname]=uigetfile('*.*','Select Posthoc Data File',350,150);

   if isequal(filename,0) | isequal(pathname,0)
      return;
   end;

   posthoc_data_file = [pathname, filename];

   set(h,'String',posthoc_data_file);
   set(h,'TooltipString',posthoc_data_file);
   setappdata(gcf,'posthoc_data_file',posthoc_data_file);

   return;						% SelectPosthocDataFile


%----------------------------------------------------------------------------
function deselect_condition

   curr_profiles = getappdata(gcf,'CurrGroupProfiles');

   if isempty(curr_profiles)
      msg = 'Group need to be added before you can deselect condition';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end

   tmp = load(curr_profiles{1});
   condition = tmp.session_info.condition;
   cond_selection = getappdata(gcf,'cond_selection');
   new_cond_selection = rri_deselect_cond_ui(condition, cond_selection);

   if ~isequal(new_cond_selection, cond_selection)
      setappdata(gcf,'cond_selection',new_cond_selection);
      setappdata(gcf,'behavname',{});
      setappdata(gcf,'behavdata',[]);
      setappdata(gcf,'behavdata_lst',{});
   end

   return;						% deselect_condition


%----------------------------------------------------------------------------
function modify_behavdata

   curr_profiles = getappdata(gcf,'CurrGroupProfiles');

   if isempty(curr_profiles)
      msg = 'Group need to be added before you can modify behavior data';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end

   cond_selection = getappdata(gcf,'cond_selection');
   behavname = getappdata(gcf,'behavname');
   behavdata = getappdata(gcf,'behavdata');
   behavdata_lst = getappdata(gcf,'behavdata_lst');
   new_evt_list = getappdata(gcf,'new_evt_list');
   newdata_lst = getappdata(gcf,'newdata_lst');

   if isempty(behavdata)
      [status,behavname,behavdata,behavdata_lst,new_evt_list,newdata_lst] = ...
		pet_get_behavior(curr_profiles, cond_selection);
   else
      status = 1;
   end

   if status == 0
      msg = 'Condition or behavior incompatible in datamat file.';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   else
      nr = length(new_evt_list);
      [new_behavdata, new_behavname] = rri_edit_behav(num2str(behavdata), ...
		behavname, 'Edit Behavior Data');
      new_behavdata = str2num(new_behavdata);

      while ~isempty(new_behavdata) & size(new_behavdata, 1) ~= nr
         if size(new_behavdata, 1) ~= nr
            msg = ['Number of rows should be equal to ' num2str(nr)];
            % set(findobj(gcf,'Tag','MessageLine'),'String',msg);
            uiwait(msgbox(msg, 'Error'));
         end

         [new_behavdata, new_behavname] = rri_edit_behav(num2str(behavdata), ...
		behavname, 'Edit Behavior Data');
         new_behavdata = str2num(new_behavdata);
      end

      if isempty(new_behavdata)
         msg = ['Behavior Data is not set'];
         set(findobj(gcf,'Tag','MessageLine'),'String',msg);
         return;
      elseif ~isequal(new_behavdata, behavdata) | ...
		~isequal(new_behavname, behavname)
         behavname = new_behavname;
         behavdata = new_behavdata;
         behavdata_lst = {};

         for i = 1:length(newdata_lst)
            mask = [];

            for j = 1:length(newdata_lst)
               if j == i
                  mask = [mask;ones(length(newdata_lst{j}),1)];
               else
                  mask = [mask;zeros(length(newdata_lst{j}),1)];
               end
            end

            behavdata_lst{i} = behavdata(find(mask),:);
         end
      end
   end

   setappdata(gcf,'behavname',behavname);
   setappdata(gcf,'behavdata',behavdata);
   setappdata(gcf,'behavdata_lst',behavdata_lst);
   setappdata(gcf,'new_evt_list',new_evt_list);
   setappdata(gcf,'newdata_lst',newdata_lst);

   return;						% modify_behavdata

