%
%   Usage: fig = pet_plot_scores_ui(LINK, fname, is_design_plot);
%   Called by pet_result_ui
%
function score_fig = pet_plot_scores_ui(varargin)

   if ~ischar(varargin{1})
      h = findobj(gcbf,'Tag','ResultFile');
      result_file = get(h,'UserData');
      is_design_plot = varargin{1};

      [tmp tit_fn] = rri_fileparts(get(gcf,'name'));
      score_fig = init(result_file, is_design_plot, tit_fn);

      old_pointer = get(gcf,'Pointer');
      set(gcf,'Pointer','watch');

      PlotDesignScores;
      PlotBrainDesignScores;

      set(gcf,'Pointer',old_pointer);

      return;
   end

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

   action = varargin{1};

   switch (action),
     case {'re_select'}
         old_pointer = get(gcf,'Pointer');
         set(gcf,'Pointer','watch');
         PlotBrainDesignScores;
         PlotDesignScores;
         PlotDesignLV;

         dlv_fig_user = [];
         try
            dlv_fig_user = get(getappdata(gcf,'dlv_fig'),'user');
         catch
         end

         if ~isempty(dlv_fig_user) & strcmp(dlv_fig_user,'LV Plot')
            set(gcf,'Pointer',old_pointer);
            view_dlv
         end

         set(gcf,'Pointer',old_pointer);
     case {'toggle_axis'}
         toggle_axis;
     case {'toggle_dlv'}
         toggle_dlv;
     case {'ToggleLegend'},
         ToggleLegend;
     case {'ToggleBrainDesignScores'},
         ToggleBrainDesignScores;
     case {'ToggleDesignScores'},
         ToggleDesignScores;
     case {'ToggleDesignLV'},
         ToggleDesignLV;
     case {'zoom'}
         zoom_on_state = get(gcbo,'Userdata');
         if (zoom_on_state == 1)                   % zoom on
            zoom on;
            set(gcbo,'Userdata',0,'Label','&Zoom off');
            set(gcf,'pointer','crosshair');
         else                                      % zoom off
            zoom off;
            set(gcf,'buttondown','pet_plot_scores_ui(''fig_bt_dn'');');
            set(gcbo,'Userdata',1,'Label','&Zoom on');
            set(gcf,'pointer','arrow');
         end
     case {'fig_bt_dn'}
         fig_bt_dn;
     case {'select_subj'}
  	 select_subj;
     case {'delete_fig'}
  	 delete_fig;
     otherwise
	 msgbox(sprintf('ERROR: Unknown action "%s"',action),'modal');
   end;

   return;					% pet_plot_scores_ui


%
%
%---------------------------------------------------------------------------

function h0 = init(result_file, is_design_plot, tit_fn)

   tit = ['PLS Scores Plot  [', tit_fn, ']'];
   cond_selection = getappdata(gcf,'cond_selection');

   h0 = [];
   [brainscores, designscores, designlv, ...
	cond_name, subj_name_lst, ...
	num_cond_lst, num_subj_lst, s, perm_result, datamat_files] = ...
		load_pls_scores(result_file, is_design_plot);

   if isempty(brainscores)
      return;
   end

   num_grp = length(num_cond_lst);
   num_lv = size(brainscores,2);

   grp_str = [];
   for i=1:num_grp
%      grp_str = [grp_str, {['Group ', num2str(i)]}];
      file_name = datamat_files{i};
      [tmp file_name] = fileparts(file_name);
      grp_str = [grp_str, {file_name}];

      subj_select_lst{i} = ones(1, num_subj_lst(i));
   end

   lv_str = [];
   for i=1:num_lv
      lv_str = [lv_str, {['LV ', num2str(i)]}];
   end

   % ----------------------- Figure --------------------------

   save_setting_status = 'on';
   pet_plot_scores_pos = [];

   try
      load('pls_profile');
   catch
   end

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

      pos = pet_plot_scores_pos;

   else

      w = 0.85;
      h = 0.75;
      x = (1-w)/2;
      y = (1-h)/2;

      pos = [x y w h];

   end

   xp = 0.0227273;
   yp = 0.0294118;
   wp = 1-2*xp;
   hp = 1-2*yp;

   pos_p = [xp yp wp hp];

   h0 = figure('units','normal', ...
        'paperunit','normal', ...
        'paperorient','land', ...
        'paperposition',pos_p, ...
        'papertype','usletter', ...
	'numberTitle','off', ...
	'menubar', 'none', ...
	'toolbar', 'none', ...
	'user','PLS Scores Plot', ...
	'name',tit, ...
	'color', [0.8 0.8 0.8], ...
	'deleteFcn', 'pet_plot_scores_ui(''delete_fig'');', ...
	'doubleBuffer','on', ...
	'position',pos);

   % ----------------------- Menu --------------------------

   %  file
   %
   h_file = uimenu('parent',h0, ...
        'visible','on', ...
        'label','&File');
   h1 = uimenu('parent', h_file, ...
        'callback','rri_file_menu(''print_fig'');', ...
        'label','&Print');
   h1 = uimenu('parent', h_file, ...
        'callback','rri_file_menu(''export_fig'');', ...
        'label','&Save Figure');

   h1 = uimenu('parent', h_file, ...
        'callback','close(gcbf);', ...
        'label','&Close');

   %  view
   %
   h_view = uimenu('parent',h0, ...
	'label','&View', ...
	'tag','ViewMenu');

   hm_axis = uimenu('parent',h_view, ...
	'userdata', 0, ...
	'callback', 'pet_plot_scores_ui(''toggle_axis'');', ...
	'label','&Plot Current Figure');

   hm_dlv = uimenu('parent',h_view, ...
	'userdata', 0, ...
	'callback', 'pet_plot_scores_ui(''toggle_dlv'');', ...
	'label','&Plot Design LV Figure');

   if(is_design_plot)
      h1 = uimenu('parent',h_view, ...
	'sepa','on', ...
	'label','Hide &Brain vs Design Scores', ...
	'userdata',1, ...		% show brain vs design scores
	'callback', 'pet_plot_scores_ui(''ToggleBrainDesignScores'');', ...
	'tag','BrainDesignMenu');
      h1 = uimenu('parent',h_view, ...
	'label','Show &Design Scores', ...
	'userdata',0, ...		% show design scores
	'callBack', 'pet_plot_scores_ui(''ToggleDesignScores'');', ...
	'tag','DesignMenu');
      h1 = uimenu('parent',h_view, ...
	'label','Show Design &Latent Variables', ...
	'userdata',0, ...		% show design lv
	'callBack', 'pet_plot_scores_ui(''ToggleDesignLV'');', ...
	'tag','DesignLVMenu');
   else
      h1 = uimenu('parent',h_view, ...
	'sepa','on', ...
	'label','Hide &Brain vs Behavior Scores', ...
	'userdata',1, ...		% show brain vs behavior scores
	'callback', 'pet_plot_scores_ui(''ToggleBrainDesignScores'');', ...
	'tag','BrainBehavMenu');
      h1 = uimenu('parent',h_view, ...
	'label','Show Be&havior Scores', ...
	'userdata',0, ...		% show behavior scores
	'callBack', 'pet_plot_scores_ui(''ToggleDesignScores'');', ...
	'tag','BehavMenu');
      h1 = uimenu('parent',h_view, ...
	'label','Show Behavior &Latent Variables', ...
	'userdata',0, ...		% show behavior lv
	'callBack', 'pet_plot_scores_ui(''ToggleDesignLV'');', ...
	'tag','BehavLVMenu');
   end

   h1 = uimenu('parent',h_view, ...
	'sepa','on', ...
	'label','&Hide Legend', ...
	'userdata',1, ...		% show legend
	'callBack', 'pet_plot_scores_ui(''ToggleLegend'');', ...
	'tag','LegendMenu');

   %  zoom
   %
   h2 = uimenu('parent',h0, ...
        'userdata', 1, ...
        'callback','pet_plot_scores_ui(''zoom'');', ...
        'label','&Zoom on');

   pause(0.01);

   % ---------------------- Left Panel ------------------------

   x = 0.03;
   y = 0.9;
   w = 0.18;
   h = 0.05;
   pos = [x y w h];

   h1 = uicontrol('parent',h0, ...
	'units','normal', ...
	'back', [0.8 0.8 0.8], ...
	'style', 'text', ...
	'fontunit', 'normal', ...
	'fontsize', 0.5, ...
	'string', 'Group List', ...
	'position', pos);

   y = 0.57;
   h = 0.33;
   pos = [x y w h];

   grp_hdl = uicontrol('Parent',h0, ...
	'unit','normal', ...
	'style', 'list', ...
	'string', grp_str, ...
	'fontunit', 'normal', ...
	'fontsize', 0.07, ...
	'callback', 'pet_plot_scores_ui(''re_select'');', ...
	'position', pos);

   y = 0.49;
   h = 0.05;
   pos = [x y w h];

   h1 = uicontrol('parent',h0, ...
	'units','normal', ...
	'back', [0.8 0.8 0.8], ...
	'style', 'text', ...
	'fontunit', 'normal', ...
	'fontsize', 0.5, ...
	'string', 'LV List', ...
	'position', pos);

   y = 0.16;
   h = 0.33;
   pos = [x y w h];

   lv_hdl = uicontrol('parent',h0, ...
	'unit','normal', ...
	'style', 'list', ...
	'string', lv_str, ...
	'fontunit', 'normal', ...
	'fontsize', 0.07, ...
	'callback', 'pet_plot_scores_ui(''re_select'');', ...
	'position', pos);

   x = x+0.04;
   y = 0.07;
   w = 0.1;
   h = 0.05;
   pos = [x y w h];

   h1 = uicontrol('parent',h0, ...
	'units','normal', ...
	'style', 'push', ...
	'fontunit', 'normal', ...
	'fontsize', 0.5, ...
	'string', 'Close', ...
	'callback', 'close(gcf)', ...
	'position', pos);

   % ----------------------- Axes --------------------------

   %  set up the axes for plotting
   %
%	   'FontUnits', 'normal', ...
%	   'FontSize', 0.07, ...
%    axes were not normalized because the Legend can't display properly
%
   %
   x = 0.28;
   y = 0.1;
   w = 0.69;
   h = 0.85;

   pos = [x y w h];

   main_axes = axes('units', 'normal', ...
        'box', 'on', ...
        'tickdir', 'out', ...
        'ticklength', [0.005 0.005], ...
	'fontsize', 10, ...
	'xtickmode', 'auto', ...
	'xticklabelmode', 'auto', ...
	'ytickmode', 'auto', ...
	'yticklabelmode', 'auto', ...
	'visible', 'off', ...
	'position',pos);

   h = 0.37;

   pos = [x y w h];

   bottom_axes = axes('units','normal', ...
        'box', 'on', ...
        'tickdir', 'out', ...
        'ticklength', [0.005 0.005], ...
	'fontsize', 10, ...
	'xtickmode', 'auto', ...
	'xticklabelmode', 'auto', ...
	'ytickmode', 'auto', ...
	'yticklabelmode', 'auto', ...
	'position',pos);

   y = 0.58;

   pos = [x y w h];

   top_axes = axes('units','normal', ...
        'box', 'on', ...
        'tickdir', 'out', ...
        'ticklength', [0.005 0.005], ...
	'fontsize', 10, ...
	'xtickmode', 'auto', ...
	'xticklabelmode', 'auto', ...
	'ytickmode', 'auto', ...
	'yticklabelmode', 'auto', ...
	'position',pos);

   x = 0.01;
   y = 0;
   w = .5;
   h = 0.04;

   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], ...
	'FontUnits', 'normal', ...
	'FontSize', 0.6, ...
	'HorizontalAlignment','left', ...
	'Position',pos, ...
	'String','', ...
	'Tag','MessageLine');

   setappdata(gcf,'tit_fn',tit_fn);
   setappdata(gcf,'brainscores',brainscores);
   setappdata(gcf,'designscores',designscores);
   setappdata(gcf,'designlv',designlv);
   setappdata(gcf, 'conditions', cond_name);
   setappdata(gcf, 'subj_name_lst', subj_name_lst);
   setappdata(gcf, 'num_cond_lst', num_cond_lst);
   setappdata(gcf, 'num_subj_lst', num_subj_lst);
   setappdata(gcf,'s',s);
   setappdata(gcf,'perm_result',perm_result);
   setappdata(gcf, 'datamat_files', datamat_files);
   setappdata(gcf, 'is_design_plot', is_design_plot);

   setappdata(gcf, 'num_grp', num_grp);
   setappdata(gcf, 'num_lv', num_lv);
   setappdata(gcf, 'subj_select_lst', subj_select_lst);

   setappdata(gcf, 'hm_axis', hm_axis);
   setappdata(gcf, 'hm_dlv', hm_dlv);
   setappdata(gcf, 'grp_hdl', grp_hdl);
   setappdata(gcf, 'lv_hdl', lv_hdl);
   setappdata(gcf, 'main_axes', main_axes);
   setappdata(gcf, 'bottom_axes', bottom_axes);
   setappdata(gcf, 'top_axes', top_axes);

   setappdata(gcf, 'PlotDesignState',1);
   setappdata(gcf, 'PlotBrainDesignState',1)
   setappdata(gcf, 'PlotDesignLVState',0);

   setappdata(gcf, 'cond_selection', cond_selection);

   return;					% init


% --------------------------------------------------------------------

function PlotBrainDesignScores

   if (getappdata(gcf,'PlotBrainDesignState') == 0)
      return;
   end;

   s = getappdata(gcf,'s');
   cb = erp_per(s);
   perm_result = getappdata(gcf,'perm_result');
   subj_select_lst = getappdata(gcf, 'subj_select_lst');
   brainscores = getappdata(gcf, 'brainscores');
   designscores = getappdata(gcf, 'designscores');
   conditions = getappdata(gcf, 'conditions');
   num_cond_lst = getappdata(gcf, 'num_cond_lst');
   num_subj_lst = getappdata(gcf, 'num_subj_lst');
   grp_idx = get(getappdata(gcf, 'grp_hdl'), 'value');
   lv_idx = get(getappdata(gcf, 'lv_hdl'), 'value');

   if (getappdata(gcf,'PlotDesignState') == 1),
      ax_hdl = getappdata(gcf,'bottom_axes');
   else
      ax_hdl = getappdata(gcf,'main_axes');
   end;

   set(ax_hdl, ...
	'buttondown','pet_plot_scores_ui(''fig_bt_dn'');', ...
	'userdata', 'PlotBrainDesignScores');

   num_conds = num_cond_lst(grp_idx);
   num_subjs = num_subj_lst(grp_idx);
   num_in_grp = [0 num_cond_lst.*num_subj_lst];

   color_code =[ 'bo';'rx';'g+';'m*';'bs';'rd';'g^';'m<';'bp';'r>'; ...
                  'gh';'mv';'ro';'gx';'m+';'b*';'rs';'gd';'m^';'b<'];

   % need more color
   %
   if num_conds > size(color_code,1)

      tmp = [];

      for i=1:ceil(num_conds/size(color_code,1))
         tmp = [tmp; color_code];
      end

      color_code = tmp;

   end

   min_x = min(designscores(:));	max_x = max(designscores(:));
   min_y = min(brainscores(:));		max_y = max(brainscores(:));
   margin_x = abs((max_x - min_x) / 20);
   margin_y = abs((max_y - min_y) / 20);

   axes(ax_hdl);
   cla; grid off; hold on;

   for n=1:num_subjs
      for k=1:num_conds
         j = sum(num_in_grp(1:grp_idx)) + (k-1) * num_subjs + n;
         score_hdl(n,k) = plot(designscores(j,lv_idx), ...
		brainscores(j,lv_idx), ...
		color_code(k,:), ...
		'buttondown','pet_plot_scores_ui(''select_subj'');', ...
		'userdata', n);

         if ~subj_select_lst{grp_idx}(n)
            set(score_hdl(n,k), 'visible', 'off');
         end
      end
   end

   setappdata(gcf, 'score_hdl', score_hdl);

   set(ax_hdl, 'xtickmode','auto',  'xticklabelmode','auto');
   axis([min_x-margin_x,max_x+margin_x,min_y-margin_y,max_y+margin_y]);
   hold off;

   l_hdl = [];

   if ~isempty(conditions),

      % remove the old legend to avoid the bug in the MATLAB5
      old_legend = getappdata(gcf,'LegendHdl');
      if ~isempty(old_legend),
        try
          delete(old_legend{1});
        catch
        end;
      end;

      % create a new legend, and save the handles
      [l_hdl, o_hdl] = legend(conditions, 0);
      set(l_hdl,'color',[0.9 1 0.9]);
      setappdata(gcf,'LegendHdl',[{l_hdl} {o_hdl}]);

      legend_state = get(findobj(gcf,'Tag','LegendMenu'),'Userdata');
      if (legend_state == 1),
	 DisplayLegend('on');
      else
	 DisplayLegend('off');
      end;

   else

      setappdata(gcf,'LegendHdl',[]);

   end;

   if(getappdata(gcf, 'is_design_plot'))
      xlabel('Design Scores');
   else
      xlabel('Behavior Scores');
   end

   ylabel('Brain Scores');
   title('');

   try
      txtbox_hdl = getappdata(gcf,'txtbox_hdl');
      delete(txtbox_hdl);                           % clear rri_txtbox
   catch
   end

   if (getappdata(gcf,'PlotDesignState') == 1) | isempty(perm_result)
      return;
   else
      title(sprintf('LV %d:  %.2f%% crossblock,  p < %.3f', lv_idx, 100*cb(lv_idx), perm_result.sprob(lv_idx)));
   end

   return;					% PlotBrainDesignScores


%---------------------------------------------------------------------------

function PlotDesignScores

   if (getappdata(gcf,'PlotDesignState') == 0),
      return;
   end;

   s = getappdata(gcf,'s');
   cb = erp_per(s);
   perm_result = getappdata(gcf,'perm_result');
   designscores = getappdata(gcf,'designscores');
   conditions = getappdata(gcf,'conditions');
   num_cond_lst = getappdata(gcf, 'num_cond_lst');
   num_subj_lst = getappdata(gcf, 'num_subj_lst');
   grp_idx = get(getappdata(gcf, 'grp_hdl'), 'value');
   lv_idx = get(getappdata(gcf, 'lv_hdl'), 'value');

   if (getappdata(gcf,'PlotBrainDesignState') == 1),
      ax_hdl = getappdata(gcf,'top_axes');
   else
      ax_hdl = getappdata(gcf,'main_axes');
   end;

   axes(ax_hdl);
   cla;hold on;

   num_conds = num_cond_lst(grp_idx);
   num_subjs = num_subj_lst(grp_idx);
   num_in_grp = [0 num_cond_lst.*num_subj_lst];

   min_x = 0.5;				max_x = num_conds+0.5;
   min_y = min(designscores(:));	max_y = max(designscores(:));
   margin_x = abs((max_x - min_x) / 20);
   margin_y = abs((max_y - min_y) / 20);

%   grp_range = sum(num_in_grp(1:grp_idx))+1:sum(num_in_grp(1:(grp_idx+1)));
%   bar(designscores(grp_range,lv_idx));

   mask = [];

   for k = 1:num_conds
      mask = [mask,num_subjs*(k-1)+1];
   end

   mask = mask + sum(num_in_grp(1:grp_idx));

   designscores_disp = designscores(mask,:);

   load('rri_color_code');

   for k = 1:num_conds
      bar_hdl = bar(k, designscores_disp(k,lv_idx));
      set(bar_hdl,'facecolor',color_code(k,:));
   end

   hold off;

   axis([min_x,max_x,min_y-margin_y,max_y+margin_y]);

   set(ax_hdl, 'userdata', 'PlotDesignScores');

   set(ax_hdl,'tickdir','out','ticklength', [0.005 0.005], ...
	'box','on');

%   set(ax_hdl, 'xtick',[0.5:num_subjs:(length(grp_range)+0.5)], ...
%	'xticklabel',{});

   set(ax_hdl,'xtick',1:num_conds);
   set(ax_hdl,'xticklabel',1:num_conds);

   conditions = getappdata(gcf, 'conditions');

   if ~isempty(conditions),

      % remove the old legend to avoid the bug in the MATLAB5
      old_legend = getappdata(gcf,'LegendHdl2');
      if ~isempty(old_legend),
        try
          delete(old_legend{1});
        catch
        end;
      end;

      % create a new legend, and save the handles
      [l_hdl, o_hdl] = legend(conditions, 0);
      set(l_hdl,'color',[0.9 1 0.9]);
      setappdata(gcf,'LegendHdl2',[{l_hdl} {o_hdl}]);

      legend_state = get(findobj(gcf,'Tag','LegendMenu'),'Userdata');
      if (legend_state == 1),
	 DisplayLegend('on');
      else
	 DisplayLegend('off');
      end;

   else

      setappdata(gcf,'LegendHdl2',[]);

   end;

   xlabel('Conditions');

   if(getappdata(gcf, 'is_design_plot'))
      ylabel('Design Scores');
   else
      ylabel('Behavior Scores');
   end

   title('');
   grid on;

   try
      txtbox_hdl = getappdata(gcf,'txtbox_hdl');
      delete(txtbox_hdl);                           % clear rri_txtbox
   catch
   end

   if isempty(perm_result)
      return;
   else
      title(sprintf('LV %d:  %.2f%% crossblock,  p < %.3f', lv_idx, 100*cb(lv_idx), perm_result.sprob(lv_idx)));
   end

   return;                                              % PlotDesignScores


%---------------------------------------------------------------------------

function PlotDesignLV

   if (getappdata(gcf,'PlotDesignLVState') == 0)
      return;
   end;

   s = getappdata(gcf,'s');
   cb = erp_per(s);
   perm_result = getappdata(gcf,'perm_result');
   designlv = getappdata(gcf,'designlv');

   num_cond_lst = getappdata(gcf, 'num_cond_lst');
   num_subj_lst = getappdata(gcf, 'num_subj_lst');
   grp_idx = get(getappdata(gcf, 'grp_hdl'), 'value');
   lv_idx = get(getappdata(gcf, 'lv_hdl'), 'value');

   num_conds = num_cond_lst(grp_idx);
%   num_subjs = num_subj_lst(grp_idx);
%   num_in_grp = [0 num_cond_lst.*num_subj_lst];

   min_x = 0.5;				max_x = num_conds+0.5;
   min_y = min(designlv(:));	max_y = max(designlv(:));
   margin_x = abs((max_x - min_x) / 20);
   margin_y = abs((max_y - min_y) / 20);

%   grp_range = sum(num_in_grp(1:grp_idx))+1:sum(num_in_grp(1:(grp_idx+1)));

   mask = zeros(1, size(designlv,1));
   mask( [num_conds * (grp_idx - 1) + 1 : num_conds * grp_idx] ) = 1;
   designlv = designlv(find(mask), :);

if(1)
   ax_hdl = getappdata(gcf,'bottom_axes');
   axes(ax_hdl);
   set(ax_hdl,'visible','off');
end

   %  plot of the designlv
   %
   ax_hdl = getappdata(gcf,'top_axes');
   axes(ax_hdl);
   cla;hold on;

   %  the rows are stacked by groups. each group has several conditions.
   %  each condition could have several contrasts.
   %
%   num_rows = size(designlv,1);
%   num_rows = num_conds;

%   tick_step = round(num_rows / 20);

   load('rri_color_code');

   for k = 1:num_conds
      bar_hdl = bar(k, designlv(k,lv_idx));
      set(bar_hdl,'facecolor',color_code(k,:));
   end

   hold off;

   axis([min_x,max_x,min_y-margin_y,max_y+margin_y]);

   set(ax_hdl, 'userdata', 'topPlotDesignLV');
   % set(ax_hdl,'xtick',[1:tick_step:num_rows]);
%   set(ax_hdl,'tickdir','out','ticklength', [0.005 0.005], ...
%	'box','on','xtick',[]);
   set(ax_hdl,'tickdir','out','ticklength', [0.005 0.005], ...
	'box','on');

%   min_value = min(designlv(:,lv_idx));
%   max_value = max(designlv(:,lv_idx));
%   offset = (max_value - min_value) / 20;
%   axis([0 size(designlv,1)+1 min_value-offset max_value+offset]);

   ylabel('Weights');

   if(getappdata(gcf, 'is_design_plot'))
      title('Weights of the contrasts for the Design LV');
   else
      title('Weights of the contrasts for the Behavior LV');
   end

   grid on;

   set(ax_hdl,'xtick',1:num_conds);
   set(ax_hdl,'xticklabel',1:num_conds);

   conditions = getappdata(gcf, 'conditions');

   if ~isempty(conditions),

      % remove the old legend to avoid the bug in the MATLAB5
      old_legend = getappdata(gcf,'LegendHdl3');
      if ~isempty(old_legend),
        try
          delete(old_legend{1});
        catch
        end;
      end;

      % create a new legend, and save the handles
      [l_hdl, o_hdl] = legend(conditions, 0);
      set(l_hdl,'color',[0.9 1 0.9]);
      setappdata(gcf,'LegendHdl3',[{l_hdl} {o_hdl}]);

      legend_state = get(findobj(gcf,'Tag','LegendMenu'),'Userdata');
      if (legend_state == 1),
	 DisplayLegend('on');
      else
	 DisplayLegend('off');
      end;

   else

      setappdata(gcf,'LegendHdl3',[]);

   end;

   xlabel('Conditions');


if(0)

   %  plot of the designlv permuation result if any
   %
   ax_hdl = getappdata(gcf,'bottom_axes');
   axes(ax_hdl);
   cla; grid off;


%cla;
%xlabel('');
%ylabel('');
%title('');
set(ax_hdl,'visible','off');
return;


   if isempty(perm_result)
      title('--- No permutation test has been performed --- ');
      return;
   end;

   bar(perm_result.dprob(:,lv_idx)*100,'r');
   set(ax_hdl, 'userdata', 'bottomPlotDesignLV');
   % set(ax_hdl,'XTick',[1:tick_step:num_contrasts]);
   set(ax_hdl,'xtick',[]);
   axis([0 size(designlv,1)+1 0 105]);

   xlabel('Contrasts');
   ylabel('Probability (%)');

   if(getappdata(gcf, 'is_design_plot'))
      title(sprintf('Permuted design LV greater than observed, %d permutation tests, %d%% crossblock', perm_result.num_perm, cb(lv_idx)));
   else
      title(sprintf('Permuted behav LV greater than observed, %d permutation tests, %d%% crossblock', perm_result.num_perm, cb(lv_idx)));
   end
end

   try
      txtbox_hdl = getappdata(gcf,'txtbox_hdl');
      delete(txtbox_hdl);                           % clear rri_txtbox
   catch
   end

   return;                                              % PlotDesignLV


%---------------------------------------------------------------------------

function ToggleLegend

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

   legend_state = get(h,'Userdata');
   switch (legend_state)
     case {0},
	set(h,'Userdata',1,'Label','&Hide Legend');
        DisplayLegend('on');
     case {1},
	set(h,'Userdata',0,'Label','&Show Legend');
        DisplayLegend('off');
   end;

   return;                                              % ToggleLegend


%---------------------------------------------------------------------------

function DisplayLegend(on_off)

   l_hdls = getappdata(gcf,'LegendHdl');
   l_hdls2 = getappdata(gcf,'LegendHdl2');
   l_hdls3 = getappdata(gcf,'LegendHdl3');

   if ~isempty(l_hdls) & ishandle(l_hdls{1}),
      set(l_hdls{1},'Visible',on_off);
      num_obj = length(l_hdls{2});
      for i=1:num_obj,
         set(l_hdls{2}(i),'Visible',on_off);
      end;
   end

   if  ~isempty(l_hdls2) & ishandle(l_hdls2{1})
      set(l_hdls2{1},'Visible',on_off);
      num_obj = length(l_hdls2{2});
      for i=1:num_obj,
         set(l_hdls2{2}(i),'Visible',on_off);
      end;
   end

   if  ~isempty(l_hdls3) & ishandle(l_hdls3{1})
      set(l_hdls3{1},'Visible',on_off);
      num_obj = length(l_hdls3{2});
      for i=1:num_obj,
         set(l_hdls3{2}(i),'Visible',on_off);
      end;
   end

   return;                                              % DisplayLegend


%---------------------------------------------------------------------------

function ToggleBrainDesignScores

   brain_design_state = getappdata(gcf,'PlotBrainDesignState');
   is_design_plot = getappdata(gcf, 'is_design_plot');
   switch (brain_design_state)
     case {0},
        if is_design_plot
           m_hdl = findobj(gcf,'Tag','BrainDesignMenu');
   	   set(m_hdl,'Label','Hide &Brain vs Design Scores');
	else
           m_hdl = findobj(gcf,'Tag','BrainBehavMenu');
   	   set(m_hdl,'Label','Hide &Brain vs Behavior Scores');
	end

        setappdata(gcf,'PlotBrainDesignState',1);
	DisplayBrainDesignScores('on');
%   	set(findobj(gcf,'Tag','LegendMenu'),'Enable','on');
        setappdata(gcf,'PlotDesignLVState',0);

        if is_design_plot
           m_hdl = findobj(gcf,'Tag','DesignLVMenu');
           set(m_hdl,'Label','Show Design &Latent Variables');
        else
           m_hdl = findobj(gcf,'Tag','BehavLVMenu');
           set(m_hdl,'Label','Show Behavior &Latent Variables');
	end

     case {1},
        if is_design_plot
           m_hdl = findobj(gcf,'Tag','BrainDesignMenu');
    	   set(m_hdl,'Label','Show &Brain vs Design Scores');
        else
           m_hdl = findobj(gcf,'Tag','BrainDesignMenu');
    	   set(m_hdl,'Label','Show &Brain vs Behavior Scores');
	end

        setappdata(gcf,'PlotBrainDesignState',0);
	DisplayBrainDesignScores('off');
%   	set(findobj(gcf,'Tag','LegendMenu'),'Enable','off');

   end;

   return;					% ToggleBrainDesignScores


%---------------------------------------------------------------------------

function DisplayBrainDesignScores(on_off)

   design_state = getappdata(gcf,'PlotDesignState');

   switch (on_off)
     case {'on'},
        if (design_state == 1),		% need to display design scores
           h = getappdata(gcf,'main_axes');
           axes(h); cla; set(h,'Visible','off');

           set(getappdata(gcf,'top_axes'),'Visible','on');
           PlotDesignScores;

           set(getappdata(gcf,'bottom_axes'),'Visible','on');
           PlotBrainDesignScores;
        else
           h = getappdata(gcf,'top_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'bottom_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'main_axes'); 
           axes(h); cla; set(h,'Visible','on');
           PlotBrainDesignScores;
	end;

     case {'off'},
         old_legend = getappdata(gcf,'LegendHdl');
         if ~isempty(old_legend),
            try
               delete(old_legend{1});
            catch
            end;
         end;
%        DisplayLegend('off');
        if (design_state == 1) 
           h = getappdata(gcf,'top_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'bottom_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'main_axes');
           axes(h); cla; set(h,'Visible','on');
           PlotDesignScores;
        else
           h = getappdata(gcf,'main_axes'); 
           axes(h); cla; set(h,'Visible','off');
	end;

   end;  % switch

   return;					% DisplayBrainDesignScores


%---------------------------------------------------------------------------

function ToggleDesignScores

   design_state = getappdata(gcf,'PlotDesignState');
   is_design_plot = getappdata(gcf, 'is_design_plot');
   switch (design_state)
     case {0},
        if is_design_plot
           m_hdl = findobj(gcf,'Tag','DesignMenu');
           set(m_hdl,'Label','Hide &Design Scores');
           setappdata(gcf,'PlotDesignState',1);
	   DisplayDesignScores('on');

           setappdata(gcf,'PlotDesignLVState',0);
           m_hdl = findobj(gcf,'Tag','DesignLVMenu');
           set(m_hdl,'Label','Show Design &Latent Variables');
	else
           m_hdl = findobj(gcf,'Tag','BehavMenu');
           set(m_hdl,'Label','Hide &Behavior Scores');
           setappdata(gcf,'PlotDesignState',1);
	   DisplayDesignScores('on');

           setappdata(gcf,'PlotDesignLVState',0);
           m_hdl = findobj(gcf,'Tag','BehavLVMenu');
           set(m_hdl,'Label','Show Behavior &Latent Variables');
	end
     case {1},
        new_state = 0;
        if is_design_plot
           m_hdl = findobj(gcf,'Tag','DesignMenu');
           set(m_hdl,'Label','Show &Design Scores');
	else
           m_hdl = findobj(gcf,'Tag','BehavMenu');
           set(m_hdl,'Label','Show &Behavior Scores');
	end
        setappdata(gcf,'PlotDesignState',0);
	DisplayDesignScores('off');
   end;

   return;                                              % ToggleDesignScores


%---------------------------------------------------------------------------

function DisplayDesignScores(on_off)

   brain_design_state = getappdata(gcf,'PlotBrainDesignState');

   switch (on_off)
     case {'on'},
        if (brain_design_state == 1),	% need to display brain/design scores
           h = getappdata(gcf,'main_axes'); 
           axes(h); cla; set(h,'Visible','off');

           set(getappdata(gcf,'top_axes'),'Visible','on');
           PlotDesignScores;

           set(getappdata(gcf,'bottom_axes'),'Visible','on');
           PlotBrainDesignScores;
        else
           h = getappdata(gcf,'top_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'bottom_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'main_axes'); 
           axes(h); cla; set(h,'Visible','on');
           PlotDesignScores;
	end;
     case {'off'},
         old_legend = getappdata(gcf,'LegendHdl2');
         if ~isempty(old_legend),
            try
               delete(old_legend{1});
            catch
            end;
         end;
        if (brain_design_state == 1),	% need to display brain/design scores
           h = getappdata(gcf,'top_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'bottom_axes');
           axes(h); cla; set(h,'Visible','off');

           set(getappdata(gcf,'main_axes'),'Visible','on');
           PlotBrainDesignScores;
        else
           h = getappdata(gcf,'main_axes'); 
           axes(h); cla; set(h,'Visible','off');
	end;
   end;  % switch

   return;                                              % DisplayDesignScores


%---------------------------------------------------------------------------

function ToggleDesignLV

   designlv_state = getappdata(gcf,'PlotDesignLVState');
   is_design_plot = getappdata(gcf, 'is_design_plot');
   switch (designlv_state)
     case {0},
        if is_design_plot
           setappdata(gcf,'PlotBrainDesignState',0);
           m_hdl = findobj(gcf,'Tag','BrainDesignMenu');
           set(m_hdl,'Label','Show &Brain vs Design Scores');
           DisplayBrainDesignScores('off');

           setappdata(gcf,'PlotDesignState',0);
           m_hdl = findobj(gcf,'Tag','DesignMenu');
           set(m_hdl,'Label','Show &Design Scores');
           DisplayDesignScores('off');

           m_hdl = findobj(gcf,'Tag','DesignLVMenu');
           set(m_hdl,'Label','Hide Design &Latent Variables');
           setappdata(gcf,'PlotDesignLVState',1);
	   DisplayDesignLV('on');
 	else
           setappdata(gcf,'PlotBrainDesignState',0);
           m_hdl = findobj(gcf,'Tag','BrainBehavMenu');
           set(m_hdl,'Label','Show &Brain vs Behavior Scores');
           DisplayBrainDesignScores('off');

           setappdata(gcf,'PlotDesignState',0);
           m_hdl = findobj(gcf,'Tag','BehavMenu');
           set(m_hdl,'Label','Show &Behavior Scores');
           DisplayDesignScores('off');

           m_hdl = findobj(gcf,'Tag','BehavLVMenu');
           set(m_hdl,'Label','Hide Behavior &Latent Variables');
           setappdata(gcf,'PlotDesignLVState',1);
	   DisplayDesignLV('on');
	end

%	set(findobj(gcf,'Tag','LegendMenu'),'Enable','off');

     case {1},
        new_state = 0;
        if is_design_plot
           m_hdl = findobj(gcf,'Tag','DesignLVMenu');
           set(m_hdl,'Label','Show Design &Latent Variables');
           setappdata(gcf,'PlotDesignLVState',0);
	   DisplayDesignLV('off');

           setappdata(gcf,'PlotDesignState',1);
           m_hdl = findobj(gcf,'Tag','DesignMenu');
           set(m_hdl,'Label','Hide &Design Scores');
           DisplayDesignScores('on');

           setappdata(gcf,'PlotBrainDesignState',1);
           m_hdl = findobj(gcf,'Tag','BrainDesignMenu');
           set(m_hdl,'Label','Hide &Brain vs Design Scores');
           DisplayBrainDesignScores('on');
	else
           m_hdl = findobj(gcf,'Tag','BehavLVMenu');
           set(m_hdl,'Label','Show Behavior &Latent Variables');
           setappdata(gcf,'PlotDesignLVState',0);
	   DisplayDesignLV('off');

           setappdata(gcf,'PlotDesignState',1);
           m_hdl = findobj(gcf,'Tag','BehavMenu');
           set(m_hdl,'Label','Hide &Behavior Scores');
           DisplayDesignScores('on');

           setappdata(gcf,'PlotBrainDesignState',1);
           m_hdl = findobj(gcf,'Tag','BrainBehavMenu');
           set(m_hdl,'Label','Hide &Brain vs Behavior Scores');
           DisplayBrainDesignScores('on');
	end

   end;

   return;                                              % ToggleDesignLV


%---------------------------------------------------------------------------

function DisplayDesignLV(on_off)

   design_state = getappdata(gcf,'PlotDesignState');
   brain_design_state = getappdata(gcf,'PlotBrainDesignState');

   switch (on_off)
     case {'on'},
	   if (design_state == 1)
		ToggleDesignScores;
           end;

	   if (brain_design_state == 1)
		ToggleBrainDesignScores;
           end;

           h = getappdata(gcf,'main_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'top_axes');
           axes(h); cla; set(h,'Visible','on');

           h = getappdata(gcf,'bottom_axes');
           axes(h); cla; set(h,'Visible','on');

           PlotDesignLV;

     case {'off'},
         old_legend = getappdata(gcf,'LegendHdl3');
         if ~isempty(old_legend),
            try
               delete(old_legend{1});
            catch
            end;
         end;
           h = getappdata(gcf,'main_axes');
           axes(h); cla; set(h,'Visible','off');

           h = getappdata(gcf,'top_axes');
           axes(h); cla; set(h,'Visible','off');
%           PlotDesignScores;

           h = getappdata(gcf,'bottom_axes');
           axes(h); cla; set(h,'Visible','off');
	   PlotBrainDesignScores;

   end;  % switch

   return;                                         % DesignLV


%---------------------------------------------------------------------------

function [brainscores, designscores, designlv, ...
	cond_name, subj_name_lst, ...
	num_cond_lst, num_subj_lst, s, perm_result, datamat_files] = ...
		load_pls_scores(result_file, is_design_plot)

   brainscores = [];
   designscores = [];
   designlv = [];

   cond_name = [];
   subj_name_lst = [];
   num_cond_lst = [];
   num_subj_lst = [];
   s = [];
   perm_result = [];
   datamat_files = [];

   if ~exist('result_file','var') | isempty(result_file),
     pattern = '*PETresult.mat';
     [result_file, path] = uigetfile(pattern,'Load PLS scores');

     if isequal(result_file, 0),
        return;
     end;

     result_file = [path, result_file];
   end;

   try
      if(is_design_plot)
         load(result_file,'brainscores','designscores','designlv', ...
			'subj_name_lst', ...
			'num_cond_lst','num_subj_lst', 's', ...
			'perm_result','datamat_files' );
      else
         load(result_file,'brainscores','behavscores','behavlv', ...
			'subj_name_lst', ...
			'num_cond_lst','num_subj_lst', 's', ...
			'perm_result','datamat_files' );
         designscores = behavscores;
         designlv = behavlv;
      end
   catch
      msg = sprintf('Cannot load the PLS result from file: %s',PLSresultFile);
      msgbox(['ERROR: ' msg],'modal');
      return;
   end;

   rri_changepath('petresult');

   load(datamat_files{1}, 'session_info');    % load the condition from datamat file

   cond_selection = [];
   warning off;
   try
      load(result_file, 'cond_selection');
   catch
   end
   warning on;

   if isempty(cond_selection)
      cond_selection = ones(1,session_info.num_conditions);
   end

   cond_name = session_info.condition(find(cond_selection));

   return;					% load_pls_scores


%---------------------------------------------------------------------------

function delete_fig(),

   link_info = getappdata(gcbf,'LinkFigureInfo');

   try
      rmappdata(link_info.hdl,link_info.name);
   end;

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

     pet_plot_scores_pos = get(gcbf,'position');

     save(pls_profile, '-append', 'pet_plot_scores_pos');
   catch
   end

   h0 = gcbf;
   axis_fig = getappdata(h0,'axis_fig');
   dlv_fig = getappdata(h0,'dlv_fig');

   try
      if ishandle(axis_fig)
         delete(axis_fig);
      end
      if ishandle(dlv_fig)
         delete(dlv_fig);
      end
   catch
   end

   return;					% delete_fig


%------------------------------------------------

function toggle_axis

   hm_axis = getappdata(gcf,'hm_axis');
   axis_status = get(hm_axis,'userdata');

   if ~axis_status				% was not checked
      set(hm_axis, 'userdata',1, 'check','on');

      view_axis;

   else
      set(hm_axis, 'userdata',0, 'check','off');

      try
         axis_fig_name = get(getappdata(gcf,'axis_fig'),'name');
         if ~isempty(axis_fig_name) & strcmp(axis_fig_name,'Current Axis')
            close(getappdata(gcf,'axis_fig'));
         end
      catch
      end

   end

   return;				% toggle_axis


%--------------------------------------------------

function view_axis

   h0 = gcf;
   axis_old = gca;

   if ~ischar(get(axis_old,'userdata')) | (...
	~strcmp(get(axis_old,'userdata'),'PlotBrainDesignScores') ...
	& ~strcmp(get(axis_old,'userdata'),'PlotDesignScores') ...
	& ~strcmp(get(axis_old,'userdata'),'topPlotDesignLV') ...
	& ~strcmp(get(axis_old,'userdata'),'bottomPlotDesignLV'))
      msgbox('Please click a plot in PLS Scores Plot.', 'modal');
      hm_axis = getappdata(h0,'hm_axis');
      set(hm_axis, 'userdata',0, 'check','off');
      return;
   end

   axis_fig_name = [];

   try
      axis_fig_name = get(getappdata(h0,'axis_fig'),'name');
   catch
   end

   if ~isempty(axis_fig_name) & strcmp(axis_fig_name,'Current Axis')
      msg = 'ERROR: Current Axis window has already been opened.';
      msgbox(msg,'ERROR','modal');
   else

      % It seems that Matlab has a lot of bugs in Legend function,
      % Slow, not working after copyobj, etc. ... 
      %
      if strcmp(get(axis_old,'userdata'),'PlotBrainDesignScores')
         old_legend = getappdata(gcf,'LegendHdl');
         if ~isempty(old_legend),
            try
               delete(old_legend{1});
            catch
            end;
         end;
      end;

      if strcmp(get(axis_old,'userdata'),'PlotDesignScores')
         old_legend = getappdata(gcf,'LegendHdl2');
         if ~isempty(old_legend),
            try
               delete(old_legend{1});
            catch
            end;
         end;
      end;

      if strcmp(get(axis_old,'userdata'),'PlotDesignLV')
         old_legend = getappdata(gcf,'LegendHdl3');
         if ~isempty(old_legend),
            try
               delete(old_legend{1});
            catch
            end;
         end;
      end;

      h01 = erp_new_axis_ui;
      set(h01,'name','Current Axis');
      axis_new = gca;

      conditions = getappdata(h0, 'conditions');

      %  redraw legend
      %
      if strcmp(get(axis_old,'userdata'),'PlotBrainDesignScores') ...
		& ~isempty(conditions)

         legend_state = get(findobj(h0,'Tag','LegendMenu'),'Userdata');

         axes(axis_old);
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(h0, 'LegendHdl',[{l_hdl} {o_hdl}]);
         if (legend_state == 1),
            DisplayLegend('on');
         else
            DisplayLegend('off');
         end;

         figure(h01)
         axes(axis_new);
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(h01, 'LegendHdl',[{l_hdl} {o_hdl}]);
         if (legend_state == 1),
	    DisplayLegend('on');
         else
            DisplayLegend('off');
         end;

      end

      if strcmp(get(axis_old,'userdata'),'PlotDesignScores') ...
		& ~isempty(conditions)

         legend_state = get(findobj(h0,'Tag','LegendMenu'),'Userdata');

         axes(axis_old);
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(h0, 'LegendHdl2',[{l_hdl} {o_hdl}]);
         if (legend_state == 1),
            DisplayLegend('on');
         else
            DisplayLegend('off');
         end;

         figure(h01)
         axes(axis_new);
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(h01, 'LegendHdl2',[{l_hdl} {o_hdl}]);
         if (legend_state == 1),
	    DisplayLegend('on');
         else
            DisplayLegend('off');
         end;

      end

      if strcmp(get(axis_old,'userdata'),'topPlotDesignLV') ...
		& ~isempty(conditions)

         legend_state = get(findobj(h0,'Tag','LegendMenu'),'Userdata');

         axes(axis_old);
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(h0, 'LegendHdl3',[{l_hdl} {o_hdl}]);
         if (legend_state == 1),
            DisplayLegend('on');
         else
            DisplayLegend('off');
         end;

         figure(h01)
         axes(axis_new);
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(h01, 'LegendHdl3',[{l_hdl} {o_hdl}]);
         if (legend_state == 1),
	    DisplayLegend('on');
         else
            DisplayLegend('off');
         end;

      end

      if ~isempty(h01)
         setappdata(h0,'axis_fig',h01);
         setappdata(h01,'main_fig',h0);
      end
   end

   return;				% view_axis


%-----------------------------------------------------------

function fig_bt_dn()

   score_hdl = getappdata(gcf,'score_hdl');

   for i=1:length(score_hdl(:))
      set(score_hdl(i), 'selected', 'off');		% remove selection
   end

   try
      txtbox_hdl = getappdata(gcf,'txtbox_hdl');
      delete(txtbox_hdl);				% clear rri_txtbox
   catch
   end

   return;						% fig_bt_dn


%-----------------------------------------------------------

function select_subj()

   % don't do anything if we're supposed to be zooming
   tmp = zoom(gcf,'getmode');
   if (isequal(tmp,'in') | isequal(tmp,'on')), return; end

   score_hdl = getappdata(gcf,'score_hdl');
   subj_name_lst = getappdata(gcf, 'subj_name_lst');
   num_cond_lst = getappdata(gcf, 'num_cond_lst');
   num_subj_lst = getappdata(gcf, 'num_subj_lst');
   grp_idx = get(getappdata(gcf, 'grp_hdl'), 'value');
   num_conds = num_cond_lst(grp_idx);
   num_subjs = num_subj_lst(grp_idx);
   subj_name = subj_name_lst{grp_idx};

   for n=1:num_subjs				% deselect other subj
      for k=1:num_conds
         set(score_hdl(n,k),'selected','off');
      end
   end

   n = get(gco, 'userdata');

   for k=1:num_conds
      set(score_hdl(n,k),'selected','on');	% select only this subj
   end

   txtbox_hdl = rri_txtbox(gca, 'Subject Name', subj_name{n});
   setappdata(gcf, 'txtbox_hdl', txtbox_hdl);

   return;					% select_subj


%------------------------------------------------

function toggle_dlv

   hm_dlv = getappdata(gcf,'hm_dlv');
   dlv_status = get(hm_dlv,'userdata');

   if ~dlv_status				% was not checked
      set(hm_dlv, 'userdata',1, 'check','on');

      view_dlv;

   else
      set(hm_dlv, 'userdata',0, 'check','off');

      try
         dlv_fig_user = get(getappdata(gcf,'dlv_fig'),'user');
         if ~isempty(dlv_fig_user) & strcmp(dlv_fig_user,'LV Plot')
            close(getappdata(gcf,'dlv_fig'));
         end
      catch
      end

   end

   return;				% toggle_dlv


%--------------------------------------------------

function view_dlv

   h0 = gcf;

   dlv_fig_user = [];

   try
      dlv_fig_user = get(getappdata(h0,'dlv_fig'),'user');
   catch
   end

   if ~isempty(dlv_fig_user) & strcmp(dlv_fig_user,'LV Plot')		% update lv_idx

      h01 = getappdata(h0,'dlv_fig');
      figure(h01);

%      msg = 'ERROR: Design LV Plot window has already been opened.';
%      msgbox(msg,'ERROR','modal');
   else

      h01 = erp_plot_dlv_ui;

   end

      tit_fn = getappdata(gcbf,'tit_fn');
      tit = ['Design LV Plot  [', tit_fn, ']'];
      set(h01,'name',tit);

      s = getappdata(gcbf,'s');
      cb = erp_per(s);
      perm_result = getappdata(gcbf,'perm_result');
      designlv = getappdata(gcbf,'designlv');

      num_cond_lst = getappdata(gcbf, 'num_cond_lst');
      num_subj_lst = getappdata(gcbf, 'num_subj_lst');
      num_grp = length(num_subj_lst);
      lv_idx = get(getappdata(gcbf, 'lv_hdl'), 'value');
      num_conds = num_cond_lst(1);

      min_x = 0.5;				max_x = size(designlv,1)+0.5;
      min_y = min(designlv(:));			max_y = max(designlv(:));
      margin_x = abs((max_x - min_x) / 20);
      margin_y = abs((max_y - min_y) / 20);

      %  plot of the designlv
      %
      cla;hold on;

      %  the rows are stacked by groups. each group has several conditions.
      %  each condition could have several contrasts.
      %

      load('rri_color_code');

      for g=1:num_grp
         for k=1:num_conds
            bar_hdl = bar((g-1)*num_conds+k, designlv((g-1)*num_conds+k,lv_idx));
            set(bar_hdl,'facecolor',color_code(k,:));
         end
      end

      hold off;

      axis([min_x,max_x,min_y-margin_y,max_y+margin_y]);

      set(gca,'tickdir','out','ticklength', [0.005 0.005], ...
		'box','on');
      ylabel('Design LV');

       if isempty(perm_result)
          title(sprintf('LV %d:  %.2f%% crossblock', lv_idx, 100*cb(lv_idx)));
       else
          title(sprintf('LV %d:  %.2f%% crossblock,  p < %.3f', lv_idx, 100*cb(lv_idx), perm_result.sprob(lv_idx)));
       end

%      if(getappdata(gcbf, 'is_design_plot'))
%         title('Weights of the contrasts for the Design LV');
%      else
%         title('Weights of the contrasts for the Behavior LV');
%      end

      grid on;

      set(gca,'xtick',[1:num_grp]*num_conds - num_conds + 0.5);
      set(gca,'xticklabel',1:num_grp);

      conditions = getappdata(gcbf, 'conditions');

      if ~isempty(conditions),

         % remove the old legend to avoid the bug in the MATLAB5
         old_legend = getappdata(gcbf,'LegendHdl3');
         if ~isempty(old_legend),
           try
             delete(old_legend{1});
           catch
           end;
         end;

         % create a new legend, and save the handles
         [l_hdl, o_hdl] = legend(conditions, 0);
         set(l_hdl,'color',[0.9 1 0.9]);
         setappdata(gcbf,'LegendHdl3',[{l_hdl} {o_hdl}]);

         legend_state = get(findobj(gcbf,'Tag','LegendMenu'),'Userdata');
         if (legend_state == 1),
	    DisplayLegend('on');
         else
  	    DisplayLegend('off');
         end;

      else

         setappdata(gcbf,'LegendHdl3',[]);

      end;

      xlabel('Groups');

      if ~isempty(h01)
         setappdata(h0,'dlv_fig',h01);
         setappdata(h01,'main_fig',h0);
      end
%   end

   return;				% view_dlv

