function roi_deconvolve_viewer(varargin)
% ------------------------------------
% Lightweight viewer to explore output of roi_deconvolve.
% 
% Usage:
% roi_deconvolve_viewer('init', infile)
% roi_deconvolve_viewer(actionstring)


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% User-specified defaults go here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ALPHA = 0.05;



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin==0
    op = 'init';
else
    op = varargin{1};
end


if strcmp(op, 'init')
    

if nargin > 1
    infile = varargin{2};
else
    infile = [];
end

%%%%%%%%%%%%%%%%%%%
% First, set up GUI
%%%%%%%%%%%%%%%%%%%

% Set up figure first
% ----------------------
h1 = figure(...
'Units','characters',...
'Color',[0.93 0.92 0.85],...
'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
'MenuBar','none',...
'PaperPosition',get(0,'defaultfigurePaperPosition'),...
'Position',[103.8 19.4 219 42.0],...
'Resize','off',...
'Tag','Viewer');

% Next, set up frames
% ------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[49.8 12.3 162.6 6.6],...
'Style','frame',...
'Tag','cond_frame');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[-0.2 -0.0 40.2 42.0],...
'Style','frame',...
'Tag','roi_group_frame');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[49.8 0.3 78 11.6],...
'Style','frame',...
'Tag','display_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[132.2 0.2 80.2 11.8],...
'Style','frame',...
'Tag','save_frame');


% Set up Current ROI controls
% -----------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[1.2 39.7 22 1.5],...
'String','Current ROI:',...
'Style','text',...
'Tag','curr_roi_txt');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Enable','inactive',...
'FontSize',9,...
'Position',[1.8 37.4 35.2 1.5],...
'String','',...
'Style','edit',...
'Tag','curr_roi_edit');


% Set up Current Group controls
% ------------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[1 34.5 30 1.5],...
'String','Current Group:',...
'Style','text',...
'Tag','curr_group_txt');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[1.8 15.5 33 18.3],...
'String',[],...
'Style','listbox',...
'Max', 0,...
'Min', 0,...
'Tag','curr_group_list');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''curr_group_add'')',...
'FontSize',9,...
'Position',[3.8 13.3 13.2 1.7],...
'String','Add',...
'Enable','off',...
'Tag','curr_group_add');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''curr_group_remove'')',...
'FontSize',9,...
'Position',[18.4 13.3 15 1.7],...
'String','Remove',...
'Enable','off',...
'Tag','curr_group_remove');


% Set up Load New button
% ---------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''load'')',...
'FontSize',10,...
'Position',[6.1 2.0 24.8 3],...
'String','Load New File',...
'Tag','load_new_button');


% Next, set up condition controls - a color bar, a popup,
% and a checkbox for each of five available controls
% -------------------------------------------------------

% first color legends
uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 0 0],...
'Position',[51 17 30 0.6],...
'Style','frame',...
'Tag','cond_color_1');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0 0.5 1],...
'Position',[84 17.0 30 0.6],...
'Style','frame',...
'Tag','cond_color_2');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0 1 0],...
'Position',[116.8 17 30 0.6],...
'Style','frame',...
'Tag','cond_color_3');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.5 0 0.2],...
'Position',[149 17 30 0.6],...
'Style','frame',...
'Tag','cond_color_4');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 0],...
'Position',[181 17 30 0.6],...
'Style','frame',...
'Tag','cond_color_5');

% Next popup controls
uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_popup'', 1)',...
'Position',[51 15 30 1.6],...
'String','<None>',...
'Style','popupmenu',...
'Tag','cond_popup_1');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_popup'', 2)',...
'Position',[84 15 30 1.6],...
'String','<None>',...
'Style','popupmenu',...
'Tag','cond_popup_2');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_popup'', 3)',...
'Position',[116.8 15 30 1.6],...
'String','<None>',...
'Style','popupmenu',...
'Tag','cond_popup_3');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_popup'', 4)',...
'Position',[149 15 30 1.6],...
'String','<None>',...
'Style','popupmenu',...
'Tag','cond_popup_4');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_popup'', 5)',...
'Position',[181 15 30 1.6],...
'String','<None>',...
'Style','popupmenu',...
'Tag','cond_popup_5');

% Last checkboxes
uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_compare'', 1)',...
'FontSize',9,...
'Position',[51.2 13.2 20.2 1.5],...
'String','Compare',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Enable', 'off',...
'Tag','cond_compare_1');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_compare'', 2)',...
'FontSize',9,...
'Position',[84 13.2 20.2 1.5],...
'String','Compare',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Enable', 'off',...
'Tag','cond_compare_2');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_compare'', 3)',...
'FontSize',9,...
'Position',[116.8 13.2 20.2 1.5],...
'String','Compare',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Enable', 'off',...
'Tag','cond_compare_3');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_compare'', 4)',...
'FontSize',9,...
'Position',[149 13.2 20.2 1.5],...
'String','Compare',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Enable', 'off',...
'Tag','cond_compare_4');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''cond_compare'', 5)',...
'FontSize',9,...
'Position',[181.2 13.2 20.2 1.5],...
'String','Compare',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Enable', 'off',...
'Tag','cond_compare_5');


% Set up display option controls
% -----------------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[81.8 9.7 11.4 1.5],...
'String','Display',...
'Style','text',...
'Tag','display_text');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''display_conint'')',...
'FontSize',9,...
'Position',[52.6 7.3 32.2 1.7],...
'String','Show confidence intervals',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Tag','display_conint');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''display_sigdiff'')',...
'FontSize',9,...
'Position',[52.6 5.2 38.2 1.2],...
'String','Show significant differences',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Tag','display_sigdiff');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''display_sess'')',...
'FontSize',9,...
'Position',[52.6 2.5 40.4 1.8],...
'String','Allow session-by-session display',...
'Style','checkbox',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Tag','display_sess');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[98.2 7.6 25.8 1.2],...
'String','Comparison is against:',...
'Style','text',...
'Enable', 'off',...
'Tag','display_comp_txt');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''display_comp_zero'')',...
'FontSize',9,...
'Position',[103.2 6.3 10.2 1.4],...
'String','Zero',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1,...
'Enable', 'off',...
'Tag','display_comp_zero');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''display_comp_other'')',...
'FontSize',9,...
'Position',[103.2 4.9 21.6 1.4],...
'String','Other conditions',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 0,...
'Enable', 'off',...
'Tag','display_comp_other');


% Set up saving controls
% ---------------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[164.8 9.8 7.6 1.5],...
'String','Save',...
'Style','text',...
'Tag','save_text');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[134 7.6 15 1.2],...
'String','Output label:',...
'Style','text',...
'HorizontalAlignment', 'left',...
'Tag','save_name_txt');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',9,...
'Position',[150 7.3 19 1.6],...
'String','',...
'Style','edit',...
'HorizontalAlignment', 'left',...
'Tag','save_name_edit');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[168.6 7.6 22.2 1.3],...
'String','Output file format:',...
'Style','text',...
'Tag','save_file_txt');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[190.6 7.6 18.2 1.5],...
'String',{ 'JPEG'; 'TIFF'; 'EPS'; 'PNG' },...
'Style','popupmenu',...
'Value',1,...
'Tag','save_file_popup');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[134 5.3 18 1.2],...
'String','Output directory:',...
'Style','text',...
'HorizontalAlignment', 'left',...
'Tag','save_dir_txt');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Enable','inactive',...
'FontSize',9,...
'Position',[150 5.1 38.4 1.6],...
'String','',...
'Style','edit',...
'Tag','save_dir_edit');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''save_dir_change'')',...
'FontSize',9,...
'Position',[195.4 5.0 13.4 1.7],...
'String','Change',...
'Tag','save_dir_change');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback', 'roi_deconvolve_viewer(''save'')',...
'FontSize',9,...
'Position',[136.6 1.1 25.6 2.1],...
'String','Save Figure',...
'Tag','save_button');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',9,...
'Position',[166.6 1.3 40 1.5],...
'String','Figure saved!:',...
'Style','text',...
'HorizontalAlignment', 'left',...
'Visible', 'off',...
'Tag','save_feedback_txt');


% Finally, set up axes and plots
% -----------------------------


h_ax = axes(...
'Parent',h1,...
'Units','characters',...
'Position',[49.8 20.7 162.6 18],...
'Tag','main_axis');

def_data = zeros(17, 1);
hold on;
plot(0:16, def_data, 'Color', 'r', 'Tag', 'cond_plot_1', 'Visible', 'off');
plot(0:16, def_data, 'Color', [0 0.5 1], 'Tag', 'cond_plot_2', 'Visible', 'off');
plot(0:16, def_data, 'Color', 'g', 'Tag', 'cond_plot_3', 'Visible', 'off');
plot(0:16, def_data, 'Color', [0.5 0 0.2], 'Tag', 'cond_plot_4', 'Visible', 'off');
plot(0:16, def_data, 'Color', 'y', 'Tag', 'cond_plot_5', 'Visible', 'off');

%% set up error bars
%for i = 1:5
%    curr = findobj('Tag', ['cond_plot_' int2str(i)]);
%    for j = 0:(length(get(curr, 'YData')) - 1)
%        % error bars only have two points, both at same x
%        % value, but different Ys
%        bars(i) = plot([j j], [0 0], 'Visible', 'off', 'Color', get(curr, 'Color'));
%    end
%    set(curr, 'Children', bars);
%    clear bars;
%end

% axis for significant difference stars to appear in.
h_star = axes(...
'Parent',h1,...
'Units','characters',...
'Position',[49.8 36.7 162.6 2],...
'HitTest','off',...
'YLimMode','manual',...
'YLim',[-1 1],...
'XTickMode','manual',...
'YTickMode','manual',...
'XTick',[],...
'YTick',[],...
'XColor',[1 1 1],...
'YColor',[1 1 1],...
'Visible','off',...
'Tag','star_axis');

hold on;
plot(0:16, def_data, 'UserData', 0, 'Color', 'k', 'Tag', 'star_plot_basic', 'Visible', 'off', 'Marker', '*', 'MarkerSize', 10);
plot(0:16, (def_data + 0.8), 'UserData', 0.8, 'Color', 'r', 'Tag', 'star_plot_1', 'LineStyle', 'none', 'Visible', 'off', 'Marker', '*', 'MarkerSize', 10);
plot(0:16, (def_data + 0.4), 'UserData', 0.4, 'Color', [0 0.5 1], 'Tag', 'star_plot_2', 'LineStyle', 'none', 'Visible', 'off', 'Marker', '*', 'MarkerSize', 10);
plot(0:16, def_data, 'UserData', 0, 'Color', 'g', 'Tag', 'star_plot_3', 'LineStyle', 'none', 'Visible', 'off', 'Marker', '*', 'MarkerSize', 10);
plot(0:16, (def_data - 0.4), 'UserData', -0.4, 'Color', [0.5 0 0.2], 'Tag', 'star_plot_4', 'LineStyle', 'none', 'Visible', 'off', 'Marker', '*', 'MarkerSize', 10);
plot(0:16, (def_data - 0.8), 'UserData', -0.8, 'Color', 'y', 'Tag', 'star_plot_5', 'LineStyle', 'none', 'Visible', 'off', 'Marker', '*', 'MarkerSize', 10);

set(h_star, 'XLim', [0 length(def_data)]);
set(h_star, 'XAxisLocation', 'top');
set(h_ax, 'XAxisLocation', 'top');
set(h_ax, 'XLim', [0 length(def_data)]);
set(h_ax, 'YGrid', 'on');
set(h_ax, 'XGrid', 'on');
set(get(h_ax, 'XLabel'), 'String', 'post-stimulus time (scans)');
set(get(h_ax, 'YLabel'), 'String', '% Signal Change');


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Next, initialize for supplied file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
if ~isempty(infile)
    roi_deconvolve_viewer('load', infile)
end

return;

end  % if op = 'init'


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% And Now...
% Callback Central!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% These next two currently on hold...
%if strcmp(op, 'curr_group_add')
%    
%    return;
%end

%if strcmp(op, 'curr_group_remove')
%    
%    return;
%end
% end on hold


if strcmp(op, 'cond_popup')
    idx = varargin{2};
    
    axes(findobj('Tag', 'main_axis'));
    cond_array = get(findobj('Tag', 'main_axis'), 'UserData');
    % Our condition list in the popups always starts with
    % the average cond, and if session-by-session if on, is
    % always followed by the session-by-session list. So our
    % popup lists are co-indexed with this array so long as 
    % we go through the avg_Conds first, then the Conds.
    
    h_plot = findobj('Tag', ['cond_plot_' int2str(idx)]);
    val = get(findobj('Tag', ['cond_popup_' int2str(idx)]), 'Value');
    if val == 1
        % i.e., the user has chosen '<None>' for this color
        
        % set plot and error bars invisible - don't need to
        % do anything else.
        set(h_plot, 'Visible', 'off');
        bars = get(h_plot, 'UserData');
        for i = 1:length(bars)
            set(bars(i), 'Visible', 'off');
        end
        set(findobj('Tag', ['cond_popup_' int2str(idx)]), 'UserData', []);
    else
        % i.e., the user has chosen an actual condition for
        % this color
        
        % offset val for <None>
        val = val - 1;
        if val <= length(cond_array{1})
            cond = cond_array{1}(val);
        else
            cond = cond_array{2}(val - length(cond_array{1}));
        end
        
        % set plot's values appropriately and cache cond
        set(h_plot, 'XData', 0:(length(cond.irf) - 1));
        set(h_plot, 'YData', cond.irf);
        set(h_plot, 'Visible', 'on');
        set(findobj('Tag', ['cond_popup_' int2str(idx)]), 'UserData', cond);
        
        % create error bars - even if not currently
        % displayed, we'll want them around later

        if get(findobj('Tag', 'display_conint'), 'Value')
            bars_visible = 'on';
        else
            bars_visible = 'off';
        end
        % destroy old bars            
        old_bars = get(h_plot, 'UserData');
        for i = 1:length(old_bars)
            delete(old_bars(i));
        end
        % make new bars at each timepoint
        curr_x = get(h_plot, 'XData');
        curr_y = get(h_plot, 'YData');
        for i = 1:length(curr_x)
            bar_x = [curr_x(i) curr_x(i)];
            bar_y = [(curr_y(i) - cond.conint(i)) (curr_y(i) + cond.conint(i))];
            bars(i) = plot(bar_x, bar_y, 'Color', get(h_plot, 'Color'), 'Visible', bars_visible);
        end
        % save bars for later use
        set(h_plot, 'UserData', bars);

    end
    roi_deconvolve_viewer('star_plot') % in case we've just turned off a plot that's displaying a star
    return;
end

if strcmp(op, 'cond_compare')
    roi_deconvolve_viewer('star_plot');
    
    return;
end


if strcmp(op, 'display_conint')
    for i = 1:5
        % check each plot to see if its error bars should be
        % on or off.
        curr = findobj('Tag', ['cond_plot_' int2str(i)]);
        bars = get(curr, 'UserData');
        if get(findobj('Tag', 'display_conint'), 'Value') & ...
            (get(findobj('Tag', ['cond_popup_' int2str(i)]), 'Value') ~=1)
            % i.e., conint is displayed and condition is
            % displayed
            for j = 1:length(bars)
                set(bars(j), 'Visible', 'on');
            end        
        else
            for j = 1:length(bars)
                set(bars(j),'Visible', 'off');
            end
        end

    end
    
    return;
end


if strcmp(op, 'display_sigdiff')
    if get(findobj('Tag', 'display_sigdiff'), 'Value')
        toggle_val = 'on';
    else
        toggle_val = 'off';
    end
    
    for i = 1:5
        set(findobj('Tag', ['cond_compare_' int2str(i)]), 'Enable', toggle_val);
    end
    set(findobj('Tag', 'display_comp_txt'), 'Enable', toggle_val);
    set(findobj('Tag', 'display_comp_zero'), 'Enable', toggle_val);
    %set(findobj('Tag', 'display_comp_other'), 'Enable', toggle_val);
    
    roi_deconvolve_viewer('star_plot');
    return;
end    


if strcmp(op, 'display_sess')
    cond_array = get(findobj('Tag', 'main_axis'), 'UserData');
    
    if isempty(cond_array)
        % no file loaded, so no conditions available
        return;
    end
    
    if get(findobj('Tag', 'display_sess'), 'Value')
        % i.e., we want to display sess-by-sess
        iS = vertcat(cond_array{2}.sess);
        for i = 1:length(cond_array{2})
            sess_names{i} = [cond_array{2}(i).name ' (session ' int2str(iS(i)) ')'];
        end
        cond_names = vertcat({'<None>'}, {cond_array{1}.name}', sess_names');
    else
        % i.e., we don't want to display sess-by-sess
        cond_names = vertcat({'<None>'}, {cond_array{1}.name}');
    end
    
    for i = 1:5
        % set to <None> - do this before re-setting list to
        % avoid keeping value at something too high for new
        % list
        set(findobj('Tag', ['cond_popup_' int2str(i)]), 'Value', 1);
        % set new name list
        set(findobj('Tag', ['cond_popup_' int2str(i)]), 'String', cond_names);
        % hit popup to zero out plots
        roi_deconvolve_viewer('cond_popup', i);
    end
    
    % zero out star plot
    roi_deconvolve_viewer('star_plot');
    
    return;
end


if strcmp(op, 'display_comp_zero')
    set(findobj('Tag', 'display_comp_other'), 'Value', 0);
    set(findobj('Tag', 'display_comp_zero'), 'Value', 1);
    roi_deconvolve_viewer('star_plot');
    return;
end
    
if strcmp(op, 'display_comp_other')
    set(findobj('Tag', 'display_comp_zero'), 'Value', 0);
    set(findobj('Tag', 'display_comp_other'), 'Value', 1);   
    roi_deconvolve_viewer('star_plot');    
    return;
end


if strcmp(op, 'save_dir_change')
    newdir = spm_get(-1, '*', 'Please select a new output directory');      
    set(findobj('Tag', 'save_dir_edit'), 'String', spm_str_manip(newdir, 'a25'));
    set(findobj('Tag', 'save_dir_edit'), 'UserData', newdir);
    return;
end


if strcmp(op, 'save')

    outdir = get(findobj('Tag', 'save_dir_edit'), 'UserData');
    [dummy, fname] = fileparts(spm_str_manip(get(findobj('Tag', 'save_name_edit'), 'String'), 'ud'));
    if isempty(fname)
        fname = 'percent_signal_figure';
    else
        fname = [fname '_figure'];
    end
    fname = fullfile(outdir, fname);
    type_list = get(findobj('Tag', 'save_file_popup'), 'String');
    type_val = get(findobj('Tag', 'save_file_popup'), 'Value');
    type = type_list{type_val};
    
    if strcmp(type, 'JPEG')
        fname = [fname '.jpg'];
        print(fname, '-djpeg', '-painters', '-loose');
    elseif strcmp(type, 'TIFF')
        fname = [fname '.tif'];
        print(fname, '-dtiff', '-painters', '-loose');
    elseif strcmp(type, 'EPS')
        fname = [fname '.eps'];
        print(fname, '-depsc2', '-painters', '-loose');
    elseif strcmp(type, 'PNG')    
        fname = [fname '.png'];
        print(fname, '-dpng', '-painters', '-loose');
    end

    set(findobj('Tag', 'save_feedback_txt'), 'String', ['Figure saved!: ' spm_str_manip(fname, 'a25')]);
    set(findobj('Tag', 'save_feedback_txt'), 'Visible', 'on');
    pause(3);
    %keyboard;
    set(findobj('Tag', 'save_feedback_txt'), 'Visible', 'off');

    return;
end


if strcmp(op, 'star_plot')
    
    % here it gets tricky.
    
    % Begin by turning off all existing plots.  We only want
    % to look at ones that are currently checked and
    % significant and everything.
    for i = 1:5
        set(findobj('Tag', ['star_plot_' int2str(i)]), 'Visible', 'off');
    end
    set(findobj('Tag', 'star_plot_basic'), 'Visible', 'off');    
    
    % Check to find out which conditions are checked and/or
    % displayed
    vis_idx = [];
    checked_idx = [];
    for i = 1:5
        if get(findobj('Tag', ['cond_compare_' int2str(i)]), 'Value')
            checked_idx(end + 1) = i;
        end
        if (get(findobj('Tag', ['cond_popup_' int2str(i)]), 'Value')) ~= 1
            % i.e., some condition is displayed here
            vis_idx(end + 1) = i;
        end
    end
    
    % if we don't have at least one checked, displayed,
    % condition (or at least two in the case of against
    % each-other comparisons), we turn all our stars off and
    % bail out; we do the same if we're turning off
    % comparisons here.
    
    idx = intersect(vis_idx, checked_idx);    
    if isempty(idx) | ((get(findobj('Tag', 'display_comp_other'), 'Value')) & (length(idx) < 2)) | ...
             (get(findobj('Tag', 'display_sigdiff'), 'Value') == 0)
        return;
    end
    
    % If we make it here, we've got something, so let's
    % bring our star_axis forward
    chil = get(findobj('Tag', 'Viewer'), 'Children');
    h_star = findobj('Tag', 'star_axis');
    star_idx = find(chil==h_star);
    if star_idx~=1
        chil(star_idx) = chil(1);
        chil(1) = h_star;
    end
    set(findobj('Tag', 'Viewer'), 'Children', chil);
    
    % Now, we have two forks - one if comparisons are
    % against each other, one if they're against zero
    
    if get(findobj('Tag', 'display_comp_zero'), 'Value')
        % i.e., comparisons are against zero
        for i = idx
            curr = findobj('Tag', ['star_plot_' int2str(i)]);
            cond = get(findobj('Tag', ['cond_popup_' int2str(i)]), 'UserData');
            
            % now loop over timepoints, and anywhere we find
            % a significant diff from zero, we put a point
            % into the new X and Y data for this star_plot.
            %
            % See important note in docs about T-stats in
            % individuals vs. in groups.
            newX = [];
            newY = [];
            offset = get(curr, 'UserData');
            for j = 1:length(cond.tstat)
                p = tcdf(-(abs(cond.tstat(j))), cond.df);
                if p < (ALPHA / 2)
                    % we have a timepoint significantly
                    % different from the baseline / zero
                    newX(end + 1) = j;
                    newY(end + 1) = offset;
                end
            end
            % now set star_plot to put points appropriately
            % and make visible.
            % Offset newX because tstat starts at one and plot starts at zero
            newX = newX - 1;
            set(curr, 'XData', newX);  
            set(curr, 'YData', newY);
            set(curr, 'Visible', 'on');
        end
    else
        % i.e., comparisons are against each other
        % only take first two to compare
        idx = idx(1:2);
        a_cond = get(findobj('Tag', ['cond_popup_' int2str(idx(1))]), 'UserData');
        b_cond = get(findobj('Tag', ['cond_popup_' int2str(idx(2))]), 'UserData');
        h_plot = findobj('Tag', 'star_plot_basic');
        
        newX = [];
        for j = 1:length(a_cond.irf)
            % kind of arbitrary how this is done - might
            % check with Sue...
            t = (a_cond.irf(j) - b_cond.irf(j)) / mean(a_cond.stderr(j), b_cond.stderr(j));
            p = tcdf(-(abs(t)), mean(a_cond.df, b_cond.df));
            if p < (ALPHA / 2)
                % we have a timepoint where these two
                % conditions significantly differ
                newX(end + 1) = j;
            end
        end
        set(h_plot, 'XData', newX);
        set(h_plot, 'YData', zeros(length(newX),1));
        set(curr, 'Visible', 'on');
    end

    return;
end


% Loading file, either on initialization or with the Load
% New button
% ---------------------------------------------------------

if strcmp(op, 'load')
    
    if nargin > 1
        infile = varargin{2};
    else 
        infile = spm_get(1, '*percent_signal*.mat', 'Please select a % signal output file');
    end
    
    load(infile);
    
    % Things to do:
    %   * clean out ROI_edit and group list
    %   * put current ROI names and group names into those
    %   uicontrols
    %   * set all cond_popups = <none> (maybe just with
    %   cond_popup button?)
    %   * re-set cond popup lists with new conditions (check
    %   allow_session flag to see which list)
    %   * attach vector of all average conds and
    %   sess-by-sess conds (in same order as popup lists) to
    %   userdata of peristim axes
    %   * set all conditions compare_checks to 0
    %   * disable sess-by-sess controls if only one session
    

    
    if exist('ROI')
        % i.e., this is a single-subject % signal change file
        
        set(findobj('Tag', 'curr_roi_edit'), 'String', spm_str_manip(ROI.roi_name, 'a25'));
        set(findobj('Tag', 'curr_roi_edit'), 'UserData', ROI);
        
        set(findobj('Tag', 'curr_group_list'), 'String', spm_str_manip(ROI.subj_name, 'a25'));
        
        % Conds will be saved as UserData for the main axis
        % as two cells - avg_conds in cell 1, sess-by-sess
        % conds in cell 2.
        cond_array{1} = ROI.avg_Cond;
        cond_array{2} = ROI.Cond;
        set(findobj('Tag', 'main_axis'), 'UserData', cond_array);
        
        % disable sess-by-sess controls if only one session
        sessions = vertcat(cond_array{2}.sess);  % woo!  I'm drunk on that move.
        if max(sessions)==1
            set(findobj('Tag', 'display_sess'), 'Value', 0);
            set(findobj('Tag', 'display_sess')', 'Enable', 'off');
        end
        
        cond_names = vertcat({'<None>'}, {ROI.avg_Cond.name}'); % this is still probably the best trick I know in MATLAB
        if get(findobj('Tag', 'display_sess'), 'Value')
            cond_names = vertcat(cond_names, {ROI.Cond.name}');  % I could do that all day.
        end
        
    elseif exist('Group')
        % i.e., this is a group % signal change file
        
        set(findobj('Tag', 'curr_roi_edit'), 'String', spm_str_manip(Group.roi_name, 'a25'));
        set(findobj('Tag', 'curr_roi_edit'), 'UserData', Group);
        
        % in Group, subj_name is a cell array, but this
        % should still work
        set(findobj('Tag', 'curr_group_list'), 'String', char(spm_str_manip(Group.subj_name, 'a25')));
        
        % Conds will be saved as UserData for the main axis
        % as two cells - avg_conds in cell 1, sess-by-sess
        % conds in cell 2.
        cond_array{1} = Group.avg_Cond;
        cond_array{2} = Group.Cond;
        set(findobj('Tag', 'main_axis'), 'UserData', cond_array);
        
        % disable sess-by-sess controls if only one session
        sessions = vertcat(cond_array{2}.sess);  % woo!  I'm drunk on that move.
        if max(sessions)==1
            set(findobj('Tag', 'display_sess'), 'Value', 0);
            set(findobj('Tag', 'display_sess')', 'Enable', 'off');
        end
        
        cond_names = vertcat({'<None>'}, {Group.avg_Cond.name}'); % this is still probably the best trick I know in MATLAB
        if get(findobj('Tag', 'display_sess'), 'Value')
            cond_names = vertcat(cond_names, {Group.Cond.name}');  % I could do that all day.
        end
    else
        error('Error loading supplied file - no readable structure present!  Check files...');
    end
    
    
    % now turn off all plots and checkboxes, and seed each
    % cond_popup with the appropriate list of conditions
    for i = 1:5
        % set each compare checkbox to off
        set(findobj('Tag', ['cond_compare_' int2str(i)]), 'Value', 0);
        % set each condition list with correct list of names
        set(findobj('Tag', ['cond_popup_' int2str(i)]), 'String', char(cond_names));
        % set each popup to <None>
        set(findobj('Tag', ['cond_popup_' int2str(i)]), 'Value', 1);
        % now activate callbacks to turn off plots
        roi_deconvolve_viewer('cond_popup', i);
    end
    
    % now that all cond_compares are off, this will zero
    % out sig. diff. plot
    roi_deconvolve_viewer('star_plot') 
    
    return;
end
        


