function fig = bfm_analysis_ui(varargin) 

   if (nargin == 0),

      if exist('plslog.m','file')
         plslog('Run BfMRI 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_CREATE_CONTRASTS'}
        pls_session = '';
        num_groups = 0;
        cond_selection = [];
        tmp = getappdata(gcf);
        if ~isempty(tmp.CurrGroupProfiles)
           pls_session = tmp.CurrGroupProfiles{1}.name{1};
        end

        if ~isempty(tmp.cond_selection)
           cond_selection = tmp.cond_selection;
           num_groups = length(tmp.CurrGroupProfiles);
        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({'BfMRI'},pls_session,cond_selection,num_groups);
        waitfor(contrast_ui_fig);
     case {'UPDATE_GROUP'}
        UpdateGroupProfiles;
     case {'SELECT_GROUP'}
        SelectGroupProfiles;
     case {'DELETE_GROUP'}
        DeleteGroupProfiles;
     case {'ADD_GROUP'}
        AddGroupProfiles;
     case {'MOVE_SLIDER'}
	MoveSlider;
     case {'GROUP_ANALYSIS_SELECTED'}
        SelectGroupAnalysis;
     case {'CONTRAST_NONE_SELECTED'}
	SelectMean;
     case {'CONTRAST_HELMERT_SELECTED'}
	SelectHelmert;
     case {'CONTRAST_FILE_SELECTED'}
	SelectContrastData;
     case {'BROWSE_CONTRAST_FILE'}
        dlg_title = 'Select Contrast File';
        [contrast_file,contrast_path] = uigetfile('*_BfMRIcontrast.txt',dlg_title);
        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;
     case {'BEHAV_FILE_SELECTED'}
	SelectBehavData;
     case{'EDIT_POSTHOC_DATA_FILE'}
	EditPosthocDataFile;
     case{'SELECT_POSTHOC_DATA_FILE'}
	SelectPosthocDataFile;
     case {'EDIT_NUM_BOOT'}
	EditNumBoot;
     case {'RUN_BUTTON_PRESSED'}
        if (SavePLSOptions == 1);
           ExecutePLS;
           uiresume(gcf);
        end;
     case {'CANCEL_BUTTON_PRESSED'}
        uiresume(gcf);
        return;
     case {'RESIZE_FIGURE'}
        SetObjectPositions;
        DisplayGroupProfiles;
     case {'DELETE_FIGURE'}
        calling_fig = getappdata(gcf,'CallingFigure');
        set(calling_fig,'visible','on');

        try
           load('pls_profile');
           pls_profile = which('pls_profile.mat');

           bfm_analysis_pos = get(gcbf,'position');

           save(pls_profile, '-append', 'bfm_analysis_pos');
        catch
        end
     otherwise
        disp(sprintf('ERROR: Unknown action "%s"',action));
   end;

   return; 


% --------------------------------------------------------------------
function Init()

   save_setting_status = 'on';
   bfm_analysis_pos = [];

   try
      load('pls_profile');
   catch
   end

   if ~isempty(bfm_analysis_pos) & strcmp(save_setting_status,'on')

      pos = bfm_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 Blocked fMRI sessions', ...
	'NumberTitle', 'off', ...
   	'Position',pos, ...
   	'Menubar','none', ...
        'DeleteFcn','bfm_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','Session Profiles', ...
   	'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','Edit', ...
   	'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','bfm_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','Group Total:', ...
   	'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', 1, ...
        'Position',pos, ...
        'HorizontalAlignment','left', ...
	'String','Group Analysis', ...
	'Enable','on', ...
   	'Callback','bfm_analysis_ui(''GROUP_ANALYSIS_SELECTED'');', ...
   	'Tag','GroupAnalysisRadiobutton');

   %-------------- 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','radio', ...
	'string','Mean-Centering PLS', ...
	'Value',1, ...
	'tag','SelectMean', ...
   	'Callback','bfm_analysis_ui(''CONTRAST_NONE_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','bfm_analysis_ui(''CONTRAST_FILE_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','radio', ...
	'string','Behavior PLS', ...
	'Value',0, ...
	'tag','SelectBehavData', ...
   	'Callback','bfm_analysis_ui(''BEHAV_FILE_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','', ...
	'Enable','off', ...
   	'Style','edit', ...
   	'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, ...
	'Enable','off', ...
   	'String','Browse', ...
   	'Callback','bfm_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','bfm_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','bfm_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','bfm_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','bfm_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','bfm_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','fmri_analysis_ui(''MENU_DESELECT_CONDITION'');', ...
        'Tag', 'DeselectConditionMenu');
   m1 = uimenu(h_deselect, ...
        'Label', '&Modify Behavior Data', ...
   	'Callback','fmri_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','bfm_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(''bfm_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,'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,2),'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 = '';
   delete_cbf = 'bfm_analysis_ui(''DELETE_GROUP'');';
   select_cbf = 'bfm_analysis_ui(''SELECT_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';
   for i=1:rows,
      new_g_hdls = group_hdls(i,:);

      pos = get(new_g_hdls(1),'Position'); pos(2) = v_pos(i)-0.01;
      set(new_g_hdls(1),'String','','Position',pos,'Visible',v,'UserData',i);

      pos = get(new_g_hdls(2),'Position'); pos(2) = v_pos(i);
      set(new_g_hdls(2),'String','', 'Position',pos, 'Visible',v, ...
                        'UserData',i,'Callback',edit_cbf);

      pos = get(new_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(new_g_hdls(4),'Position'); pos(2) = v_pos(i);
      set(new_g_hdls(4),'String','Edit','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);
   group_idx = top_group_idx;
   last_row = 0;

   for i=1:rows
      g_hdls = group_hdls(i,:);
      if (group_idx <= num_group),
         curr_group_name = curr_group_profiles{group_idx}.short_name;
         set(g_hdls(1),'String',sprintf('Group #%d.',group_idx),'Visible','on');
         set(g_hdls(2),'String',sprintf('%s',curr_group_name), ...
                       'Enable', 'inactive', 'Visible','on');
         set(g_hdls(3),'String','Delete','Enable','on','Visible','on');
         set(g_hdls(4),'String','Edit','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','Edit','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(2),'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');

   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','','Enable','off','Background',[0.8 0.8 0.8], ...
		 'Visible','off');

   set(a_hdls(3),'String','Add','Visible','off', ...
		     'Callback','bfm_analysis_ui(''ADD_GROUP'');');

   set(a_hdls(4),'String','Edit','Visible','off','Enable','off');

   setappdata(gcf,'AddRowHdls',a_hdls);

   return;						% CreateAddRow


%----------------------------------------------------------------------------
function ShowAddRow(group_idx,v_pos,row_idx)

   a_hdls = getappdata(gcf,'AddRowHdls');

   for j=1:length(a_hdls),
      new_pos = get(a_hdls(j),'Position'); 

      if j==1
         new_pos(2) = v_pos-0.01;
      else
         new_pos(2) = v_pos;
      end

      set(a_hdls(j),'Position',new_pos);
      set(a_hdls(j),'Visible','on');
   end;

   set(a_hdls(4),'Visible','Off');
   set(a_hdls(2),'String','');
   set(a_hdls(1),'String',sprintf('Group #%d.',group_idx),'UserData',row_idx);

   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 AddGroupProfiles()

   rows = getappdata(gcf,'NumRows');
   a_hdls = getappdata(gcf,'AddRowHdls');
   curr_group_profiles = getappdata(gcf,'CurrGroupProfiles');

   if ~isempty(curr_group_profiles) & ~isempty(curr_group_profiles{1}.name)
      [profile_dir, g_files, g_ext] = fileparts(curr_group_profiles{1}.name{1});
   else
      curr = pwd;
      if isempty(curr)
         curr = filesep;
      end

      profile_dir = curr;
   end;

   group_idx = str2num(get(a_hdls(1),'String'));

   new_group_profiles = fmri_select_profiles_ui(profile_dir,[]);

   profiles_str = [];
   for i=1:length(new_group_profiles),
       [profile_dir, g_files, g_ext] = fileparts(new_group_profiles{i});
       profiles_str = [profiles_str ' ' g_files];      
   end;
   profiles_str = deblank(strjust(profiles_str,'left'));

   if isempty(new_group_profiles)				% CANCEL
      return;
   else
      if isempty(getappdata(gcf,'cond_selection'))
         tmp = load(new_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',{});
   end;

   num_group = length(curr_group_profiles)+1;
   curr_group_profiles{num_group}.short_name = profiles_str;
   curr_group_profiles{num_group}.name = new_group_profiles;

   setappdata(gcf,'CurrGroupProfiles',curr_group_profiles);

   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;

   set(a_hdls(2),'String',profiles_str);
   
   set(findobj(gcf,'Tag','NumberGroupEdit'),'String',num2str(num_group));
   DisplayGroupProfiles;

   % not execute following block under behav pls
   %
   if get(findobj(gcf,'Tag','SelectBehavData'),'Value') == 0
      % not a singl subject analysis
      %
      if (num_group >  1)
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), ...
                                            'Value',1,'Enable','inactive');
      else
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), ...
                                            'Value',1,'Enable','on');
      end
   end;

   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));

   if ~isempty(curr_group_profiles{1}.name)
      [profile_dir, g_files, g_ext] = fileparts(curr_group_profiles{1}.name{1});
   else
      curr = pwd;
      if isempty(curr)
         curr = filesep;
      end

      profile_dir = curr;
   end;

   curr_profiles = curr_group_profiles{group_idx}.name;

   new_group_profiles = fmri_select_profiles_ui(profile_dir,curr_profiles);

   profiles_str = [];
   for i=1:length(new_group_profiles),
       [profile_dir, g_files, g_ext] = fileparts(new_group_profiles{i});
       profiles_str = [profiles_str ' ' g_files];      
   end;
   profiles_str = deblank(strjust(profiles_str,'left'));

   if ~isempty(new_group_profiles)
      curr_group_profiles{group_idx}.short_name = profiles_str;
      curr_group_profiles{group_idx}.name = new_group_profiles;
      setappdata(gcf,'CurrGroupProfiles',curr_group_profiles);

      set(group_hdls(row_idx,2),'String',profiles_str);

      tmp = load(new_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;

   return;						% SelectGroupProfiles


%----------------------------------------------------------------------------
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);

   % not execute following block under behav pls
   %
   if get(findobj(gcf,'Tag','SelectBehavData'),'Value') == 0
      % not a singl subject analysis
      %
      if (num_group >  1)
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), ...
                                            'Value',1,'Enable','inactive');
      else
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), ...
                                            'Value',1,'Enable','on');
      end
   end;

   DisplayGroupProfiles;
   UpdateSlider;

   return;						% DeleteGroupProfiles


%----------------------------------------------------------------------------
function UpdateGroupProfiles(group_idx)

   curr_group = 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_group{group_idx}.short_name = get(gcbo,'String');

   setappdata(gcf,'CurrGroupProfiles',curr_group);

   return;						% UpdateGroupProfiles


%----------------------------------------------------------------------------
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);

   DisplayGroupProfiles;

   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 SelectGroupAnalysis;

   return;

   h = findobj(gcf,'Tag','GroupAnalysisRadiobutton');

   curr_value = get(h,'Value');

   switch (get(h,'Value')),
     case {1},
   	set(findobj(gcf,'Tag','BootstrapRequipementLabel'),'String', ...
	    '(require at least 3 subjs/group)');
     case {0},
   	set(findobj(gcf,'Tag','BootstrapRequipementLabel'),'String', ...
	    '(require at least 3 subjs/group)');
   end;

   return;						% SelectGrouopAnalysis


%----------------------------------------------------------------------------
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);

   PLSoptions.profiles = cell(1,num_groups);
   for i=1:num_groups,
      PLSoptions.profiles{i} = curr_profiles{i}.name;
   end;

   if isempty(PLSoptions.profiles)
      msg = 'Group need to be added before you can run analysis';
      set(findobj(gcf,'Tag','MessageLine'),'String',msg);
      return;
   end

   h = findobj(gcf,'Tag','GroupAnalysisRadiobutton');
   PLSoptions.group_analysis = get(h, 'Value');
  
   %  contrast
   %
   if (get(findobj(gcf,'Tag','SelectMean'),'Value') == 1)
      PLSoptions.ContrastMethod = 1;
%   elseif (get(findobj(gcf,'Tag','SelectHelmert'),'Value') == 1)
 %     PLSoptions.ContrastMethod = 2;
   elseif (get(findobj(gcf,'Tag','SelectBehavData'),'Value') == 1)
      PLSoptions.ContrastMethod = 4;
   elseif (get(findobj(gcf,'Tag','SelectContrastData'),'Value') == 1)
      PLSoptions.ContrastMethod = 3;
      h = findobj(gcf,'Tag','ContrastFileEdit');
      PLSoptions.ContrastFile = get(h,'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
      disp('ERROR : Unknown contrast method');
   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;

   if (PLSoptions.num_boot > 0)
      min_subj_required = 3;
      if (PLSoptions.group_analysis == 1), 	% for group analysis
         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
      else
         if (PLSoptions.ContrastMethod == 4)	% behav pls
            num_behav_subj = 0;
            for i=1:length(PLSoptions.profiles)
               num_behav_subj = num_behav_subj + ...
			get_repetition(PLSoptions.profiles{i});
            end

            if (num_behav_subj < min_subj_required)
               msg = 'There must have at least 3 subjects for bootstrap.';
               set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ' msg]);
               return;
            end
         else
            if (get_repetition(PLSoptions.profiles{1}) < min_subj_required)
               msg = 'There must have at least 3 subjects for bootstrap.';
               set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ' msg]);
               return;
            end
         end
      end
   end;


   % make sure the conditions in each profile are the same
   %
   if 0 % (PLSoptions.ContrastMethod == 3);
      total_profiles = ValidateProfiles(PLSoptions.profiles, ...
                                             use_contrast.conditions);
   else
      total_profiles = ValidateProfiles(PLSoptions.profiles);
   end;
   if (total_profiles == -1)
      return;
   end;
   PLSoptions.TotalNumberProfiles = total_profiles;

   %  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
   else
         PLSoptions.posthoc = [];
   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;


   % save datamat
   %
   save_datamat = get(findobj(gcf,'Tag','SaveDatamatChkbox'),'Value');
   PLSoptions.save_datamat = save_datamat;


   % cond_selection & behav_modify
   %
   PLSoptions.cond_selection = getappdata(gcf,'cond_selection');
   PLSoptions.behavname = getappdata(gcf,'behavname');
   PLSoptions.behavdata = getappdata(gcf,'behavdata');
   PLSoptions.behavdata_lst = getappdata(gcf,'behavdata_lst');


   % everything should be alright, save the option now
   %
   setappdata(gcf,'PLSoptions',PLSoptions);
   % save PLSoptions PLSoptions;


   status = 1;

   return;						% SavePLSoptions


%----------------------------------------------------------------------------
function num_rep = get_repetition(profile_list), 

   num_rep = 0;

   for i=1:length(profile_list),
      load(profile_list{i},'session_info');
      rri_changepath('fmrisession');
      datamat_prefix = session_info.datamat_prefix;
      st_datamatFile = sprintf('%s_BfMRIdatamat.mat',datamat_prefix);
      st_datamatFile = fullfile(session_info.pls_data_path,st_datamatFile);

      load(st_datamatFile,'st_evt_list');
      
      num_rep = num_rep + length(find(st_evt_list == 1));
   end;

   return;						% get_repetition


%----------------------------------------------------------------------------
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;
   first_profile_idx = 2;
   for i=2:total_profiles,
      s = load(cell_buffer{i},'session_info');
      curr_condition = s.session_info.condition;
      if ~isequal(curr_condition,prev_condition),
          [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;
      end;
   end;

   if exist('use_conditions','var')
      if ~isequal(curr_condition,use_condition),
          [p_path, p_name, p_ext] = fileparts(cell_buffer{i});
          msg = sprintf('The contrast condition is not compatible.".',p_name);
          set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
          total_profiles = -1;
          return;
      end;
   end
   
   return;						% ValidateConditions


%----------------------------------------------------------------------------
function ExecutePLS(),

   PLSoptions = getappdata(gcf,'PLSoptions');

   progress_hdl = rri_progress_status('','Create','PLS Analysis');

   progress_merge_factor = 1 / (PLSoptions.TotalNumberProfiles * 2); 
   setappdata(progress_hdl,'ProgressScale',progress_merge_factor * 0.2);
   setappdata(progress_hdl,'ProgressStart',0);

   switch (PLSoptions.ContrastMethod)
     case {1}
        fmri_pls_analysis(PLSoptions.profiles, [], ...
				   PLSoptions.num_perm, ...
				   PLSoptions.num_boot, ...
				   PLSoptions.Clim, ...
				   PLSoptions.posthoc, ...
				   PLSoptions.save_datamat, ...
                                   PLSoptions.group_analysis, ...
                                   PLSoptions.cond_selection, ...
                                   PLSoptions.behavname, ...
                                   PLSoptions.behavdata, ...
                                   PLSoptions.behavdata_lst);
     case {2}
        fmri_pls_analysis(PLSoptions.profiles, 'HELMERT', ...
                                   PLSoptions.num_perm, ...
				   PLSoptions.num_boot, ...
				   PLSoptions.Clim, ...
				   PLSoptions.posthoc, ...
				   PLSoptions.save_datamat, ...
                                   PLSoptions.group_analysis, ...
                                   PLSoptions.cond_selection, ...
                                   PLSoptions.behavname, ...
                                   PLSoptions.behavdata, ...
                                   PLSoptions.behavdata_lst);
     case {3}
        fmri_pls_analysis(PLSoptions.profiles, PLSoptions.ContrastFile, ...
                                   PLSoptions.num_perm, ...
				   PLSoptions.num_boot, ...
				   PLSoptions.Clim, ...
				   PLSoptions.posthoc, ...
				   PLSoptions.save_datamat, ...
                                   PLSoptions.group_analysis, ...
                                   PLSoptions.cond_selection, ...
                                   PLSoptions.behavname, ...
                                   PLSoptions.behavdata, ...
                                   PLSoptions.behavdata_lst);
     case {4}

        close(progress_hdl);

        fmri_pls_analysis(PLSoptions.profiles, 'BEHAV', ...
                                   PLSoptions.num_perm, ...
				   PLSoptions.num_boot, ...
				   PLSoptions.Clim, ...
				   PLSoptions.posthoc, ...
				   PLSoptions.save_datamat, ...
                                   PLSoptions.group_analysis, ...
                                   PLSoptions.cond_selection, ...
                                   PLSoptions.behavname, ...
                                   PLSoptions.behavdata, ...
                                   PLSoptions.behavdata_lst);
   end;

   if exist('progress_hdl','var') & ishandle(progress_hdl)
      close(progress_hdl);
   end

   uiresume(gcf);

   return;						% ExecutePLS


%----------------------------------------------------------------------------
function SelectMean;

   if get(findobj(gcf,'Tag','SelectMean'),'Value') == 0		% click itself
      set(findobj(gcf,'Tag','SelectMean'),'Value',1);
   else
%      set(findobj(gcf,'Tag','SelectHelmert'),'Value',0);
      set(findobj(gcf,'Tag','SelectContrastData'),'Value',0);
      set(findobj(gcf,'Tag','SelectBehavData'),'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');

      num_group = str2num(get(findobj(gcf,'Tag','NumberGroupEdit'), 'String'));
      if num_group > 1
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), 'Value', 1, 'enable', 'inactive');
      else
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), 'Value', 1, 'enable', 'on');
      end

   end

   return;						% SelectMean


%----------------------------------------------------------------------------
function SelectHelmert;

   if get(findobj(gcf,'Tag','SelectHelmert'),'Value') == 0	% click itself
      set(findobj(gcf,'Tag','SelectHelmert'),'Value',1);
   else
      set(findobj(gcf,'Tag','SelectMean'),'Value',0);
      set(findobj(gcf,'Tag','SelectContrastData'),'Value',0);
      set(findobj(gcf,'Tag','SelectBehavData'),'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');

      num_group = str2num(get(findobj(gcf,'Tag','NumberGroupEdit'), 'String'));
      if num_group > 1
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), 'Value', 1, 'enable', 'inactive');
      else
         set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), 'Value', 1, 'enable', 'on');
      end

   end

   return;						% SelectHelmert


%----------------------------------------------------------------------------
function SelectContrastData;

   if get(findobj(gcf,'Tag','SelectContrastData'),'Value') == 0	% click itself
      set(findobj(gcf,'Tag','SelectContrastData'),'Value',1);
   else
      set(findobj(gcf,'Tag','SelectMean'),'Value',0);
%      set(findobj(gcf,'Tag','SelectHelmert'),'Value',0);
      set(findobj(gcf,'Tag','SelectBehavData'),'Value',0);

      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','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');

      set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), 'Value', 1, 'enable', 'off');
   end

   return;						% SelectContrastData


%----------------------------------------------------------------------------
function SelectBehavData;

   if get(findobj(gcf,'Tag','SelectBehavData'),'Value') == 0	% click itself
      set(findobj(gcf,'Tag','SelectBehavData'),'Value',1);
   else
      set(findobj(gcf,'Tag','SelectMean'),'Value',0);
%      set(findobj(gcf,'Tag','SelectHelmert'),'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

      set(findobj(gcf,'Tag','GroupAnalysisRadiobutton'), 'Value', 1, 'enable', 'off');
   end

   return;						% SelectBehavData


%----------------------------------------------------------------------------
function EditNumBoot

   if get(findobj(gcf,'Tag','SelectBehavData'),'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 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

