function roi_deconvolve_interface(varargin)
%-------------------------------
% Handles all the design choices for roi_deconvolve in a
% graphical fashion; returns a vector of Design structs,
% where each Design represents a subject x ROI combination.
%
% Usage
%
% roi_deconvolve_interface(actionstring)
% roi_deconvolve_interface('init', def_IRF_LENGTH, def_CON_INT)
%
%

op = varargin{1};
if nargin > 1
    def_IRF_LENGTH = varargin{2};
    def_CON_INT = varargin{3};
end

% Design is a vector of structs, one for each running of the
% roi_deconvolve code, i.e., one element for each subject X ROI
% combination.
% Each element has the following fields:
%   - roi_fname: full-path filename for ROI file
%   - roi_name: extensionless ROI name, cleaned up and ready
%   for saving/labeling purposes
%   - XYZvox: the coordinates, in voxels, of this ROI (3 x
%   n)
%   - XYZmm: the coordinates, in mm, of this ROI (3 x n)
%   - subj_name: subject name, cleaned and suitable for
%   labeling/saving
%   - resdir: full-path results directory for this subject
%   - prepend: string to be prepended to front of output
%   filenames; can be empty.
%   - outdir: full-path directory in which all output files
%   are placed
%   - des_fname: full-path filename for the appropriate
%   design file - SPMcfg.mat for SPM99, SPM.mat for SPM2
%   - SPMver: version of SPM used for this subject.  Either
%   2 or 99 - integer.
%   - nsess: number of sessions for the experiment
%   - TR: TR for the experiment
%   - n_lags: round(IRF_LENGTH / TR) + 1 = the number of
%   timepoints in each condition-specific impulse function 
%   that will be estimated.
%   - omitted: cell array (nsess x 1 long) of session-specific
%   scan indexes to be omitted from analysis.
%   - V: vector of image files structures, each with
%   following fields:
%       - iS: session index for this V
%       - G: global mean for this V
%       - vol: memory-mapped vol struct (see spm_vol for
%       details)
%   - Cond: vector of condition structures, each with
%   following fields:
%       - name: name of condition
%       - basemodel_flag: 1 if condition is to be included
%       in baseline model and hence have its effects removed
%       from availability for independent testing; 0 otherwise.
%       Currently disabled - always 0.
%       - ons: vector of onsets (in TRs)
%       - dur: vector of durations (in TRs)
%       - stim: n(images) x 1 vector containing 1 at every
%       timepoint this stimulus is on and 0 everywhere else.
%   - base_flags: a structure itself, which contains a variety of
%   logical flags (and a couple integer values), signaling 
%   different aspects of the chosen baseline design:
%       - base_timeflag: 0 = steady baseline; 1 =
%       time-varying
%       - base_condflag: 0 = baseline is mean of timecourse;
%       1 = baseline is mean of condition
%       - base_cond_idx: 0 if baseline is mean of condition;
%       otherwise integer specifying condition number
%       - base_region: 1 = same ROI is baseline region;
%       2 = grand mean of volume is baseline; 3 = mean of
%       user-specified mask is baseline; 4 = mean of
%       user-specified inverse mask is baseline
%       - base_mask: empty unless base_region_idx = 3; then
%       full-path filename of specified mask
%       - base_neg: empty unless base_region_idx = 4; then
%       full-path filename of negative mask (voxels to
%       exclude)
%       - base_template: empty unless base_region_idx = 4;
%       then full-path filename of mask template (voxels
%       from which inverse mask are excluded)
%   - preproc_flags: a structure itself, which contains a
%   variety of logical flags and a couple other things,
%   signaling different aspects of the chosen temporal model of the
%   data:
%       - trim: 0 = no trim; 1 = trim
%       - trim_amt: threshold of standard deviations beyond
%       mean of session above or below which values will be
%       trimmed.
%       - detr: 0 = no detrending; 1 = linear detrending
%       - lowpass: 0 = no low-pass filtering; 1 = low-pass
%       filtering
%       - low_choice: 'Gaussian' or 'hrf'; empty if lowpass
%       = 0
%       - low_param: 0 unless low_choice is 'Gaussian';
%       then integer specifying FWHM in secs of low-pass
%       filter kernel
%       - highpass: 0 = no high-pass filtering; 1 =
%       high-pass filtering
%       - high_choice: 'none' if highpass is 0, otherwise
%       'specify'
%       - high_param: 0 if highpass is 0; otherwise, integer
%       specifying period of interest in secs; filter
%       attenuates effects with periods longer than this
%       number.
%   - Contrasts: vector of structures specifying what linear
%   contrasts, if any, are to be performed.  May be empty.
%   Has the following fields if not:
%       - name: label for contrast
%       - c: value of contrast, set up as array of n x p
%       size, where p is the number of parameters and n is
%       the number of linear constraints used.  Each row is
%       one linear constraint.

if strcmp(op, 'init')

% 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',[10 28.1 220.2 33.3],...
'Resize','off',...
'Tag','Interface');

% Set up frames in order
% ---------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[-0.2 -0.08 50.2 33],...
'Style','frame',...
'Tag','left_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[52.4 -0.08 55.6 33],...
'Style','frame',...
'Tag','left_cent_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[109.8 -0.08 60.2 33],...
'Style','frame',...
'Tag','right_cent_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[0.4 20.8 49.2 11.5],...
'Style','frame',...
'Tag','rois_frame');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[0.4 9 49.2 11.5],...
'Style','frame',...
'Tag','subj_frame');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[0.4 0.2 49.6 8.2],...
'Style','frame',...
'Tag','results_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[53 13.9 54.2 18.6],...
'Style','frame',...
'Tag','baseline_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[53.2 0.3 53.2 12.9],...
'Style','frame',...
'Tag','preproc_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[54.4 28.3 51.6 2.1],...
'Style','frame',...
'Tag','base_timeflag_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[54.4 22.2 51.6 6],...
'Style','frame',...
'Tag','base_condflag_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[54.8 14.6 51.4 7],...
'Style','frame',...
'Tag','base_regionflag_frame');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[111.8 .3 56 20.0],...
'Style','frame',...
'Tag','contrasts_frame');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[172.2 7.6 47.8 22],...
'Style','frame',...
'Tag','output_frame');


% Set up ROI and subject controls
% --------------------------------

% ROI first
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[1.6 30.1 9 1.5],...
'String','ROIs:',...
'Style','text',...
'Tag','rois_text');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',10,...
'Position',[1.4 23.9 46.4 6.0],...
'String','',...
'Style','listbox',...
'Max',0,...
'Min',0,...
'Tag','rois_list');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''rois_add'');',...
'FontSize',11,...
'Position',[5 21.5 16.8 1.7],...
'String','Add',...
'Tag','rois_add_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''rois_remove'');',...
'FontSize',11,...
'Position',[28 21.5 16.8 1.7],...
'String','Remove',...
'Enable', 'off',...
'Tag','rois_remove_button');


% next Subject

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[1 18.3 16.6 1.5],...
'String','Subjects:',...
'Style','text',...
'Tag','subj_text');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',10,...
'Position',[1.4 12.0 46.4 6.0],...
'String','',...
'Style','listbox',...
'Max',0,...
'Min',0,...
'Tag','subj_list');



uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''subj_add'');',...
'FontSize',11,...
'Position',[5 9.6 16.8 1.7],...
'String','Add',...
'Tag','subj_add_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''subj_remove'');',...
'FontSize',11,...
'Position',[28 9.6 16.8 1.7],...
'String','Remove',...
'Enable', 'off',...
'Tag','subj_remove_button');


% Set up results path controls
% -----------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',10,...
'Position',[1.6 3.3 46.2 2.2],...
'String','',...
'Enable', 'inactive',...
'Style','edit',...
'Tag','resdir_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[2.2 6.1 20.6 1.5],...
'String','Results Path:',...
'Style','text',...
'Tag','resdir_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''resdir_choose'');',...
'FontSize',11,...
'Position',[5.2 1 16.8 1.7],...
'String','Choose',...
'Enable', 'off',...
'Tag','resdir_choose_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''resdir_load'');',...
'FontSize',11,...
'Position',[28.4 1 16.8 1.7],...
'String','Load',...
'Enable', 'off',...
'Tag','resdir_load_button');



% Set up baseline controls
% -------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[73.4 30.7 16.6 1.5],...
'String','Baseline',...
'Style','text',...
'Enable', 'off',...
'Tag','base_text');

% time flag first
uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_steady'');',...
'FontSize',11,...
'Position',[61.2 28.6 14.4 1.3],...
'String','Steady',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','base_timeflag_steady_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_timevary'');',...
'FontSize',11,...
'Position',[78.8 28.5 22 1.6],...
'String','Time-varying',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','base_timeflag_vary_button');

% Cond flag next
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[65.6 26.5 28.6 1.3],...
'String','Baseline is mean of:',...
'Style','text',...
'Enable', 'off',...
'Tag','base_condflag_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_cond_time'');',...
'FontSize',11,...
'Position',[55.4 24.9 22.6 1.6],...
'String','Timecourse',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','base_condflag_time_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_cond_cond'');',...
'FontSize',11,...
'Position',[55.2 23.0 17 1.6],...
'String','Condition:',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','base_condflag_cond_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[73 22.5 31.8 2.1],...
'String', 'None',...
'Style','popupmenu',...
'Value',1,...
'Enable', 'off',...
'Tag','base_condflag_popup');


% Region flag next
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[55 20 12 1.3],...
'String','Region:',...
'Style','text',...
'Enable', 'off',...
'Tag','base_regflag_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_reg'');',...
'FontSize',11,...
'Position',[66.8 19.7 38.6 1.7],...
'String',{ 'Same ROI'; 'Grand Mean'; 'Mask'; 'Neg. Mask' },...
'Style','popupmenu',...
'Value',1,...
'Enable', 'off',...
'Tag','base_regflag_popup');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[55.6 17.7 10.2 1.3],...
'String','Mask:',...
'Style','text',...
'Enable', 'off',...
'Tag','base_regflag_mask_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[56 15.3 14.4 1.3],...
'String','Template:',...
'Style','text',...
'Enable', 'off',...
'Tag','base_regflag_temp_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_reg_mask_choose'');',...
'FontSize',11,...
'Position',[93.6 17.3 11.8 2],...
'String','Choose',...
'Enable', 'off',...
'Tag','base_regflag_mask_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''base_reg_temp_choose'');',...
'FontSize',11,...
'Position',[93.6 15.0 11.8 2],...
'String','Choose',...
'Enable', 'off',...
'Tag','base_regflag_temp_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[65 17.7 28 1.3],...
'String','',...
'Style','text',...
'Enable', 'off',...
'Tag','base_regflag_mask_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[69.8 15.4 23.4 1.3],...
'String','',...
'Style','text',...
'Enable', 'off',...
'Tag','base_regflag_temp_edit');


% Set up preprocessing controls
% --------------------------------



uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[70 11 22.8 1.7],...
'String','Preprocessing',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_text');

% Set up trim first
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[54.6 9.1 10.8 1.3],...
'String','Trim?:',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_trim_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_trim'');',...
'FontSize',11,...
'Position',[65 9 10.6 2],...
'String','Yes',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','preproc_trim_yes');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_notrim'');',...
'FontSize',11,...
'Position',[75.4 9 10.6 2],...
'String','No',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','preproc_trim_no');

% Next detrending
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[54.8 7.5 12.8 1.3],...
'String','Detrend?:',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_detr_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_detr'');',...
'FontSize',11,...
'Position',[69.2 7.3 10.6 2],...
'String','Yes',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','preproc_detr_yes');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_nodetr'');',...
'FontSize',11,...
'Position',[79.6 7.3 10.6 2],...
'String','No',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','preproc_detr_no');

% Next high-pass filter
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[54.8 5.8 16.8 1.3],...
'String','High-pass?:',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_high_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_high'');',...
'FontSize',11,...
'Position',[73.6 5.6 10.6 2],...
'String','Yes',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','preproc_high_yes');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_nohigh'');',...
'FontSize',11,...
'Position',[84 5.6 10.6 2],...
'String','No',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','preproc_high_no');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[65.8 4.2 12 1.3],...
'String','Kernel:',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_high_kern_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',11,...
'Position',[77.2 4.1 10.2 1.6],...
'String','',...
'Style','edit',...
'Enable', 'off',...
'Tag','preproc_high_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[88 4.2 10.2 1.3],...
'String','(secs)',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_high_secs_text');

% Finally low-pass controls
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[55.6 2.3 17.2 1.4],...
'String','Low-pass?:',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_low_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_low'');',...
'FontSize',11,...
'Position',[75.2 2.3 10.2 1.3],...
'String','Yes',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','preproc_low_yes');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''preproc_nolow'');',...
'FontSize',11,...
'Position',[86.6 2.3 10.2 1.3],...
'String','No',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','preproc_low_no');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[65.8 0.8 12 1.3],...
'String','Kernel:',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_low_kern_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',11,...
'Position',[77.4 0.7 10.2 1.6],...
'String','',...
'Style','edit',...
'Enable', 'off',...
'Tag','preproc_low_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[88.2 0.9 10.2 1.3],...
'String','(secs)',...
'Style','text',...
'Enable', 'off',...
'Tag','preproc_low_secs_text');


% Set up IRF length and Con Int controls
% --------------------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[112.2 30.5 18.2 1.7],...
'String','IRF Length:',...
'Style','text',...
'Enable', 'off',...
'Tag','irf_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Callback','roi_deconvolve_interface(''irf_check'')',...
'FontSize',11,...
'Position',[131 30.7 8.4 1.7],...
'String', num2str(def_IRF_LENGTH),...
'Style','edit',...
'Enable', 'off',...
'Tag','irf_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[139.8 30.9 10.2 1.3],...
'String','(secs)',...
'Style','text',...
'Enable', 'off',...
'Tag','irf_secs_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[112 28.5 30.8 1.5],...
'String','Confidence Interval:',...
'Style','text',...
'Enable', 'off',...
'Tag','conint_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Callback','roi_deconvolve_interface(''conint_check'');',...
'FontSize',11,...
'Position',[143.8 28.5 8 1.7],...
'String',num2str(def_CON_INT),...
'Style','edit',...
'Enable', 'off',...
'Tag','conint_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[152.4 28.7 2.6 1.3],...
'String','%',...
'Style','text',...
'Enable', 'off',...
'Tag','conint_pct_text');


% Set up contrast controls
% ---------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[132.2 18.1 17 1.5],...
'String','Contrasts',...
'Style','text',...
'Enable', 'off',...
'Tag','con_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',11,...
'Position',[113 5.3 52.8 11.0],...
'String',[],...
'Style','listbox',...
'Max',0,...
'Min',0,...
'Enable', 'off',...
'Tag','con_list');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''con_add'');',...
'FontSize',11,...
'Position',[123 2.3 8 2],...
'String','Add',...
'Enable', 'off',...
'Tag','con_add_button');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''con_edit'');',...
'FontSize',11,...
'Position',[135.2 2.3 8 2],...
'String','Edit',...
'Enable', 'off',...
'Tag','con_edit_button');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''con_remove'');',...
'FontSize',11,...
'Position',[148 2.3 12 2],...
'String','Remove',...
'Enable', 'off',...
'Tag','con_remove_button');


% Set up output controls
% ----------------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[189.8 27.3 12.4 1.5],...
'String','Output',...
'Style','text',...
'Enable', 'off',...
'Tag','out_text');

% omitted scans first
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[176.5 25.6 13 1.3],...
'String','Omit scans?:',...
'Style','text',...
'Enable', 'off',...
'Tag','out_omit_text');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Callback','roi_deconvolve_interface(''out_omit_check'');',...
'FontSize',11,...
'Position',[189 25.6 25.2 1.6],...
'String','',...
'Style','edit',...
'Enable', 'off',...
'Tag','out_omit_edit');

% previously omitted scans 
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[176.5 23 20 1.3],...
'String','Prev. omitted scans?:',...
'Style','text',...
'Enable', 'off',...
'Tag','out_prev_omit_text');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Callback','roi_deconvolve_interface(''out_prev_omit_check'');',...
'FontSize',11,...
'Position',[196.5 23 18 1.6],...
'String','',...
'Style','edit',...
'Enable', 'off',...
'Tag','out_prev_omit_edit');

% session-specific flag
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[174.4 20.6 32.8 1.3],...
'String','Session-specific output?:',...
'Style','text',...
'Enable', 'off',...
'Tag','out_sess_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''out_sess'');',...
'FontSize',11,...
'Position',[190.2 19 8.6 1.3],...
'String','Yes',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Enable', 'off',...
'Tag','out_sess_yes');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''out_nosess'');',...
'FontSize',11,...
'Position',[200.8 19 8.6 1.3],...
'String','No',...
'Style','radiobutton',...
'Max', 1,...
'Min', 0,...
'Value', 1, ...
'Enable', 'off',...
'Tag','out_sess_no');

% prepend string next
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[174.8 16.6 20.2 1.5],...
'String','Prepend string:',...
'Style','text',...
'Enable', 'off',...
'Tag','out_prepend_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',11,...
'Position',[177.6 15.1 37 1.6],...
'String','',...
'Style','edit',...
'Enable', 'off',...
'Tag','out_prepend_edit');

% output directory last
uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',11,...
'Position',[175 13 21.6 1.3],...
'String','Output directory:',...
'Style','text',...
'Enable', 'off',...
'Tag','out_outdir_text');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',11,...
'Position',[178 10.5 36.6 2],...
'String','',...
'Style','edit',...
'Enable', 'off',...
'Tag','out_outdir_edit');


uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''out_outdir_choose'');',...
'FontSize',11,...
'Position',[188 8.1 13.2 1.7],...
'String','Choose',...
'Enable', 'off',...
'Tag','out_outdir_choose_button');


% Finally the process and help buttons
% ------------------------------

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''process'');',...
'FontSize',12,...
'FontWeight','bold',...
'Position',[178 2 35 3],...
'String','Process',...
'Enable', 'off',...
'Tag','process_button');

uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','roi_deconvolve_interface(''help'');',...
'FontSize',12,...
'Position',[200 30.5 19 2.5],...
'String','Help',...
'Enable', 'off',...
'Tag','help_button');

end  % initialization statement


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


% Add ROIs pushbutton
% --------------------
if strcmp(op, 'rois_add')
    img = spm_get(Inf, '.img', 'Select ROI .img file(s) to add');

    rois = get(findobj('Tag', 'rois_list'), 'UserData');    
    for i = 1:length(rois)
        for j = 1:size(img,1)
            if strcmp(deblank(rois{i}), deblank(img(j,:)))
                beep;
                fprintf('\nROI %s has already been added!\n', spm_str_manip(img(j,:), 'a25'));
                return;
            end
        end
    end

    for i=1:size(img, 1)
        rois = vertcat(rois, {img(i,:)});
    end
    set(findobj('Tag', 'rois_list'), 'UserData', rois);
    liststring = get(findobj('Tag', 'rois_list'), 'String');
    liststring = vertcat(liststring, {spm_str_manip(img, 'a25')});
    set(findobj('Tag', 'rois_list'), 'String', liststring);
    set(findobj('Tag', 'rois_list'), 'Value', length(rois));
        
    set(findobj('Tag', 'rois_remove_button'), 'Enable', 'on');
    set(findobj('Tag', 'process_button'), 'Enable', 'on');
    return;
end

% Remove ROIs pushbutton
% -----------------------
if strcmp(op, 'rois_remove')
    remove_idx = get(findobj('Tag', 'rois_list'), 'Value');
    liststring = get(findobj('Tag', 'rois_list'), 'String');
    rois = get(findobj('Tag', 'rois_list'), 'UserData');
    if length(rois) > 1
        rois(remove_idx) = [];
        liststring(remove_idx) = [];
    else
        rois = [];
        liststring = [];
    end
    set(findobj('Tag', 'rois_list'), 'String', liststring);
    set(findobj('Tag', 'rois_list'), 'UserData', rois);
    if remove_idx > 1
        set(findobj('Tag', 'rois_list'), 'Value', remove_idx - 1);
    else
        set(findobj('Tag', 'rois_list'), 'Value', 1);
    end
    
    if isempty(liststring)
        % i.e., that was the last ROI in the list
        set(findobj('Tag', 'rois_remove_button'), 'Enable', 'off');
        set(findobj('Tag', 'process_button'), 'Enable', 'off');
    end
    return;
end

% Add subjects pushbutton
% -------------------------
if strcmp(op, 'subj_add')
    dirs = spm_get(-Inf, '.img', 'Select subject directories to add');
    dirs = cellstr(dirs);
    dirs = deblank(dirs);
    for i = 1:length(dirs)
        [dummy_dir, dummy_file, dummy_ext] = fileparts(dirs{i});
        if (strcmp(dummy_ext,'.') | strcmp(dummy_ext,'')) & isempty(dummy_file)
            % we've selected a directory from within it, and
            % hence subj_name ends in /.  So let's strip it
            dirs{i} = dummy_dir;
        end
    end

    subj = get(findobj('Tag', 'subj_list'), 'UserData');    
    for i = 1:length(subj)
        for j = 1:length(dirs)
            if strcmp(deblank(subj{i}), dirs{j})
                beep;
                fprintf('\nSubject %s has already been added!\n', spm_str_manip(dirs{j}, 'a25'));
                return;
            end
        end
    end

    for i=1:length(dirs)
        subj = vertcat(subj, dirs(i));
    end
    set(findobj('Tag', 'subj_list'), 'UserData', subj);
    liststring = get(findobj('Tag', 'subj_list'), 'String');
    liststring = vertcat(liststring, spm_str_manip(dirs, 'a25'));
    set(findobj('Tag', 'subj_list'), 'String', liststring);
    set(findobj('Tag', 'subj_list'), 'Value', length(subj));
        
    set(findobj('Tag', 'subj_remove_button'), 'Enable', 'on');
    set(findobj('Tag', 'resdir_choose_button'), 'Enable', 'on');
    set(findobj('Tag', 'process_button'), 'Enable', 'on');
    return;   
end

% Remove subjects pushbutton
% ----------------------------

if strcmp(op, 'subj_remove')
    remove_idx = get(findobj('Tag', 'subj_list'), 'Value');
    liststring = get(findobj('Tag', 'subj_list'), 'String');
    subj = get(findobj('Tag', 'subj_list'), 'UserData');
    if length(subj) > 1
        subj(remove_idx) = [];
        liststring(remove_idx) = [];
    else
        subj = [];
        liststring = [];
    end
    set(findobj('Tag', 'subj_list'), 'String', liststring);
    set(findobj('Tag', 'subj_list'), 'UserData', subj);
    if remove_idx > 1
        set(findobj('Tag', 'subj_list'), 'Value', remove_idx - 1);
    else
        set(findobj('Tag', 'subj_list'), 'Value', 1);
    end
    
    if isempty(liststring)
        % i.e., that was the last subject in the list
        set(findobj('Tag', 'subj_remove_button'), 'Enable', 'off');
        % remove results directory until new subjects added
        set(findobj('Tag', 'resdir_edit'), 'String', '');
        set(findobj('Tag', 'resdir_choose_button'), 'Enable', 'off');
        set(findobj('Tag', 'resdir_load_button'), 'Enable', 'off');
        set(findobj('Tag', 'process_button'), 'Enable', 'off');
    end
    return;
end

% Choose results directory pushbutton
% --------------------------------------

if strcmp(op, 'resdir_choose')
    dir = spm_get(-1, '.img', 'Select results directory from one subject');
    dir = deblank(dir);

    [dummy_dir, display_dir, dummy_ext] = fileparts(dir);
    if strcmp(dummy_ext, '.') & isempty(display_dir)
        % dir ends in /., so strip those
        dir = dummy_dir;     
        display_dir = dummy_dir;
        [dummy_dir, display_dir] = fileparts(display_dir);
    end
    set(findobj('Tag', 'resdir_edit'), 'String', spm_str_manip(display_dir, 'a25'));
    
    % abstract results path away from individual person
    subj = get(findobj('Tag', 'subj_list'), 'UserData');
    exp_dir = fileparts(deblank(subj{1}));
    
    % initial guess at resdir
    [dummy_dir, resdir] = fileparts(dir);
    
    while(~(strcmp(dummy_dir, exp_dir)))
        [dummy_dir, newpart] = fileparts(dummy_dir);
        prev_resdir = resdir;
        resdir = fullfile(newpart, resdir);
    end    
    
    % now we've hit the exp_dir, we have a leading subject
    % directory on our resdir path - so let's trim it.
    resdir = prev_resdir;
    
    set(findobj('Tag', 'resdir_edit'), 'UserData', resdir);
 
    set(findobj('Tag', 'resdir_load_button'), 'Enable', 'on');

    % disable eeeeeeverything
    set(findobj('Tag', 'base_text'), 'Enable', 'off');
    set(findobj('Tag', 'base_timeflag_steady_button'), 'Enable', 'off');
    set(findobj('Tag', 'base_timeflag_vary_button'), 'Enable', 'off');
    set(findobj('Tag', 'base_condflag_text'), 'Enable', 'off');
    set(findobj('Tag', 'base_condflag_time_button'), 'Enable', 'off');
    set(findobj('Tag', 'base_condflag_cond_button'), 'Enable', 'off');
    set(findobj('Tag', 'base_condflag_popup'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_text'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_popup'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_mask_text'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_temp_text'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_mask_button'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_temp_button'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_mask_edit'), 'Enable', 'off');
    set(findobj('Tag', 'base_regflag_temp_edit'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_trim_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_trim_yes'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_trim_no'), 'Enable', 'off');    
    set(findobj('Tag', 'preproc_detr_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_detr_yes'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_detr_no'), 'Enable', 'off');    
    set(findobj('Tag', 'preproc_high_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_yes'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_no'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_kern_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_edit'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_secs_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_yes'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_no'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_kern_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_edit'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_secs_text'), 'Enable', 'off');
    set(findobj('Tag', 'irf_text'), 'Enable', 'off');
    set(findobj('Tag', 'irf_edit'), 'Enable', 'off');
    set(findobj('Tag', 'irf_secs_text'), 'Enable', 'off');
    set(findobj('Tag', 'conint_text'), 'Enable', 'off');
    set(findobj('Tag', 'conint_edit'), 'Enable', 'off');
    set(findobj('Tag', 'conint_pct_text'), 'Enable', 'off');
    set(findobj('Tag', 'con_text'), 'Enable', 'off');
    set(findobj('Tag', 'con_list'), 'Enable', 'off');
    set(findobj('Tag', 'con_add_button'), 'Enable', 'off');
    set(findobj('Tag', 'con_edit_button'), 'Enable', 'off');
    set(findobj('Tag', 'con_remove_button'), 'Enable', 'off');
    set(findobj('Tag', 'out_text'), 'Enable', 'off');
    set(findobj('Tag', 'out_omit_text'), 'Enable', 'off');
    set(findobj('Tag', 'out_omit_edit'), 'Enable', 'off'); 
    set(findobj('Tag', 'out_prev_omit_text'), 'Enable', 'off');
    set(findobj('Tag', 'out_prev_omit_edit'), 'Enable', 'off');
    set(findobj('Tag', 'out_sess_text'), 'Enable', 'off');    
    set(findobj('Tag', 'out_sess_yes'), 'Enable', 'off');    
    set(findobj('Tag', 'out_sess_no'), 'Enable', 'off');  
    set(findobj('Tag', 'out_prepend_text'), 'Enable', 'off');
    set(findobj('Tag', 'out_prepend_edit'), 'Enable', 'off');    
    set(findobj('Tag', 'out_outdir_text'), 'Enable', 'off');
    set(findobj('Tag', 'out_outdir_edit'), 'Enable', 'off');  
    set(findobj('Tag', 'out_outdir_choose_button'), 'Enable', 'off');
    set(findobj('Tag', 'process_button'), 'Enable', 'off');
    set(findobj('Tag', 'help_button'), 'Enable', 'off');
    return;   
end


if strcmp(op, 'resdir_load')
    % Here we need to:
    %   - set preprocessing and baseline values to their
    %   proper defaults
    %   - enable eeeeeverything
    
    subj = get(findobj('Tag', 'subj_list'), 'UserData');
    resdir = get(findobj('Tag', 'resdir_edit'), 'UserData');
    full_resdir = fullfile(deblank(subj{1}), resdir);
    
    if ~exist(fullfile(full_resdir, 'SPM.mat'))
        error('Can''t locate results in given directory - check files!');
    end
    
    % need the following:
    %   - list of conditions
    %   - default high- and low-pass filter kernels
    
    % determine if results are SPM99 or SPM2    
    % crude but effective test for SPM99-style results
    if exist(fullfile(full_resdir, 'SPMcfg.mat'))
        %results are SPM99
        version = 99;
        load(fullfile(full_resdir,'SPMcfg.mat'));
        % assume all sessions have same conditions and
        % filters
        con_list = Sess{1}.name';
        filter = xX.K{1};
        % clean up stuff from SPMcfg - K is all we need
        clear F_iX0 SPMid Sess VY xGX xM xsDes xX;
    else
        % results are SPM2
        version = 2;
        load(fullfile(full_resdir,'SPM.mat'));
        % assume all sessions have same conditions and
        % filters
        for c = 1:length(SPM.Sess(1).U)
            con_list{c,1} = SPM.Sess(1).U(c).name{1};
        end
        filter = SPM.xX.K(1);
        if isinf(filter.HParam)
            filter.HChoice = 'none';
        else
            filter.HChoice = 'specify';
        end
        filter.LChoice = 'none';
        filter.LParam = [];
        % clean stuff up
        clear SPM;
    end
    
    % enable eeeeeverything
    
    set(findobj('Tag', 'base_text'), 'Enable', 'on');
    set(findobj('Tag', 'base_timeflag_steady_button'), 'Enable', 'on');
    set(findobj('Tag', 'base_timeflag_vary_button'), 'Enable', 'on');
    set(findobj('Tag', 'base_condflag_text'), 'Enable', 'on');
    set(findobj('Tag', 'base_condflag_time_button'), 'Enable', 'on');
    set(findobj('Tag', 'base_condflag_cond_button'), 'Enable', 'on');
    % allow code below to determine what should be on
    roi_deconvolve_interface('base_cond_time');
    set(findobj('Tag', 'base_regflag_text'), 'Enable', 'on');
    set(findobj('Tag', 'base_regflag_popup'), 'Enable', 'on');
    % allow code below to determine what should be on
    roi_deconvolve_interface('base_reg');
    set(findobj('Tag', 'preproc_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_trim_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_trim_yes'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_trim_no'), 'Enable', 'on');    
    set(findobj('Tag', 'preproc_detr_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_detr_yes'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_detr_no'), 'Enable', 'on');    
    set(findobj('Tag', 'preproc_high_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_yes'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_no'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_kern_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_edit'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_secs_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_yes'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_no'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_kern_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_edit'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_secs_text'), 'Enable', 'on');
    set(findobj('Tag', 'irf_text'), 'Enable', 'on');
    set(findobj('Tag', 'irf_edit'), 'Enable', 'on');
    set(findobj('Tag', 'irf_secs_text'), 'Enable', 'on');
    set(findobj('Tag', 'conint_text'), 'Enable', 'on');
    set(findobj('Tag', 'conint_edit'), 'Enable', 'on');
    set(findobj('Tag', 'conint_pct_text'), 'Enable', 'on');
    set(findobj('Tag', 'con_text'), 'Enable', 'on');
    set(findobj('Tag', 'con_list'), 'Enable', 'on');
    set(findobj('Tag', 'con_add_button'), 'Enable', 'on');
    set(findobj('Tag', 'con_edit_button'), 'Enable', 'on');
    set(findobj('Tag', 'con_remove_button'), 'Enable', 'on');
    set(findobj('Tag', 'out_text'), 'Enable', 'on');
    set(findobj('Tag', 'out_omit_text'), 'Enable', 'on');
    set(findobj('Tag', 'out_omit_edit'), 'Enable', 'on');
    set(findobj('Tag', 'out_prev_omit_text'), 'Enable', 'on');
    set(findobj('Tag', 'out_prev_omit_edit'), 'Enable', 'on'); 
    set(findobj('Tag', 'out_sess_text'), 'Enable', 'on');    
    set(findobj('Tag', 'out_sess_yes'), 'Enable', 'on');    
    set(findobj('Tag', 'out_sess_no'), 'Enable', 'on');  
    set(findobj('Tag', 'out_prepend_text'), 'Enable', 'on');
    set(findobj('Tag', 'out_prepend_edit'), 'Enable', 'on');    
    set(findobj('Tag', 'out_outdir_text'), 'Enable', 'on');
    set(findobj('Tag', 'out_outdir_edit'), 'Enable', 'inactive');  
    set(findobj('Tag', 'out_outdir_choose_button'), 'Enable', 'on');
    set(findobj('Tag', 'process_button'), 'Enable', 'on');    
    set(findobj('Tag', 'help_button'), 'Enable', 'on');
    
        
    % now set object values appropriately
    set(findobj('Tag', 'base_condflag_popup'), 'String', con_list);
    set(findobj('Tag', 'base_condflag_popup'), 'Value', 1);
    if strcmp(filter.HChoice, 'none')
        roi_deconvolve_interface('preproc_nohigh');
    else
        roi_deconvolve_interface('preproc_high');
        set(findobj('Tag', 'preproc_high_edit'), 'String', num2str(filter.HParam));
    end
    if version==99
        if strcmp(filter.LChoice, 'none')
            roi_deconvolve_interface('preproc_nolow');
        else
            roi_deconvolve_interface('preproc_low');
            if strcmp(filter.LChoice, 'Gaussian')
                set(findobj('Tag', 'preproc_low_edit'), 'String', num2str(filter.LParam));
            else
                set(findobj('Tag', 'preproc_low_edit'), 'String', 'hrf');
            end
        end
    else
        % low-pass filtering isn't allowed in SPM2, so we
        % disable low-pass controls for this case.
        roi_deconvolve_interface('preproc_nolow');
        set(findobj('Tag', 'preproc_low_text'), 'Enable', 'off');
        set(findobj('Tag', 'preproc_low_yes'), 'Enable', 'off');
        set(findobj('Tag', 'preproc_low_no'), 'Enable', 'off');
        set(findobj('Tag', 'preproc_low_kern_text'), 'Enable', 'off');
        set(findobj('Tag', 'preproc_low_edit'), 'Enable', 'off');
        set(findobj('Tag', 'preproc_low_secs_text'), 'Enable', 'off');
    end
        
    return;
end


% ---------------------------------
% A note on radio button coding
% ---------------------------------
% In theory, you only need to have one line in most of these
% radio buttons - to turn its opposite off, since presumably
% it's being called by a click on it.  But I like to use
% these callbacks sometimes from other points in the
% program, so I explicitly encode the turning on.


if strcmp(op, 'base_steady')
    set(findobj('Tag', 'base_timeflag_vary_button'), 'Value', 0);
    set(findobj('Tag', 'base_timeflag_steady_button'), 'Value', 1);    
    return;
end


if strcmp(op, 'base_timevary')
    set(findobj('Tag', 'base_timeflag_steady_button'), 'Value', 0);
    set(findobj('Tag', 'base_timeflag_vary_button'), 'Value', 1);    
    return;
end


if strcmp(op, 'base_cond_time')
    set(findobj('Tag', 'base_condflag_cond_button'), 'Value', 0);
    set(findobj('Tag', 'base_condflag_time_button'), 'Value', 1);
    set(findobj('Tag', 'base_condflag_popup'), 'Enable', 'off');
    return;
end


if strcmp(op, 'base_cond_cond')
    set(findobj('Tag', 'base_condflag_time_button'), 'Value', 0);
    set(findobj('Tag', 'base_condflag_cond_button'), 'Value', 1);    
    set(findobj('Tag', 'base_condflag_popup'), 'Enable', 'on');
    return;
end


if strcmp(op, 'base_reg')
    val = get(findobj('Tag', 'base_regflag_popup'), 'Value');
    switch val
        case {1, 2}
            % Baseline = Same ROI or Grand Mean
            % turn off both mask and template controls
            set(findobj('Tag', 'base_regflag_mask_text'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_temp_text'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_mask_button'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_temp_button'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_mask_edit'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_temp_edit'), 'Enable', 'off');
        case 3
            % Baseline = user-specified mask
            % turn on mask, turn off template
            set(findobj('Tag', 'base_regflag_mask_text'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_mask_button'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_mask_edit'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_temp_text'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_temp_button'), 'Enable', 'off');
            set(findobj('Tag', 'base_regflag_temp_edit'), 'Enable', 'off');            
        case 4
            % Baseline = user-spec'ed negative mask
            % turn on both mask and template
            set(findobj('Tag', 'base_regflag_mask_text'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_temp_text'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_mask_button'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_temp_button'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_mask_edit'), 'Enable', 'on');
            set(findobj('Tag', 'base_regflag_temp_edit'), 'Enable', 'on');
    end
    return;
end


if strcmp(op, 'base_reg_mask_choose')
    mask = spm_get(1, '*.img', 'Please select mask image for baseline region');
    
    set(findobj('Tag', 'base_regflag_mask_edit'), 'UserData', mask);
    set(findobj('Tag', 'base_regflag_mask_edit'), 'String', spm_str_manip(mask, 'a20'));
    return;
end


if strcmp(op, 'base_reg_temp_choose')
    template = spm_get(1, '*.img', 'Please select template to include in baseline ');
    
    set(findobj('Tag', 'base_regflag_mask_edit'), 'UserData', mask);
    set(findobj('Tag', 'base_regflag_mask_edit'), 'String', spm_str_manip(mask, 'a20'));
    return;
end


if strcmp(op, 'preproc_trim')
    set(findobj('Tag', 'preproc_trim_no'), 'Value', 0);
    set(findobj('Tag', 'preproc_trim_yes'), 'Value', 1);
    return;
end


if strcmp(op, 'preproc_notrim')
    set(findobj('Tag', 'preproc_trim_yes'), 'Value', 0);
    set(findobj('Tag', 'preproc_trim_no'), 'Value', 1);    
    return;    
end


if strcmp(op, 'preproc_detr')
    set(findobj('Tag', 'preproc_detr_no'), 'Value', 0);
    set(findobj('Tag', 'preproc_detr_yes'), 'Value', 1);    
    return;
end


if strcmp(op, 'preproc_nodetr')
    set(findobj('Tag', 'preproc_detr_yes'), 'Value', 0);
    set(findobj('Tag', 'preproc_detr_no'), 'Value', 1);
    return;
end


if strcmp(op, 'preproc_high')
    set(findobj('Tag', 'preproc_high_no'), 'Value', 0);
    set(findobj('Tag', 'preproc_high_yes'), 'Value', 1);    
    set(findobj('Tag', 'preproc_high_kern_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_edit'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_high_secs_text'), 'Enable', 'on');
    return;
end


if strcmp(op, 'preproc_nohigh')
    set(findobj('Tag', 'preproc_high_yes'), 'Value', 0);
    set(findobj('Tag', 'preproc_high_no'), 'Value', 1);    
    set(findobj('Tag', 'preproc_high_kern_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_edit'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_high_secs_text'), 'Enable', 'off');    
    return;
end


if strcmp(op, 'preproc_low')
    set(findobj('Tag', 'preproc_low_no'), 'Value', 0);
    set(findobj('Tag', 'preproc_low_yes'), 'Value', 1);    
    set(findobj('Tag', 'preproc_low_kern_text'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_edit'), 'Enable', 'on');
    set(findobj('Tag', 'preproc_low_secs_text'), 'Enable', 'on');    
    return;
end


if strcmp(op, 'preproc_nolow')
    set(findobj('Tag', 'preproc_low_yes'), 'Value', 0);
    set(findobj('Tag', 'preproc_low_no'), 'Value', 1);    
    set(findobj('Tag', 'preproc_low_kern_text'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_edit'), 'Enable', 'off');
    set(findobj('Tag', 'preproc_low_secs_text'), 'Enable', 'off');      
    return;
end


if strcmp(op, 'irf_check')
    string = get(findobj('Tag', 'irf_edit'), 'String');
    [num, ok] = str2num(string);
    if ~isempty(num)
        if (num < 1) | (num > 50)
            ok = 0;
        end
        if length(num) > 1
            ok = 0;
        end
    end
    if ~ok
        set(findobj('Tag', 'irf_edit'), 'String', '');
        set(findobj('Tag', 'process_button'), 'Enable', 'off');        
        fprintf('\n\nSorry; %s is invalid for IRF value. ', string);
        fprintf('IRF must be a positive integer between 1 and 50.  ');
        fprintf('Canonical HRF length is about 32 secs.\n\n');
    else
        num = round(num);
        set(findobj('Tag', 'irf_edit'), 'String', int2str(num));
        set(findobj('Tag', 'process_button'), 'Enable', 'on');        
    end
    return;
end


if strcmp(op, 'conint_check')
    string = get(findobj('Tag', 'conint_edit'), 'String');
    [num, ok] = str2num(string);
    if ~isempty(num)
        if (num < 1) | (num > 99)
            ok = 0;
        end
        if length(num) > 1
            ok = 0;
        end
    end
    if ~ok
        set(findobj('Tag', 'conint_edit'), 'String', '');
        set(findobj('Tag', 'process_button'), 'Enable', 'off');
        fprintf('\n\nSorry; %s is invalid for confidence interval value.  ', string);
        fprintf('Con. int. must be a positive integer between 1 and 99.  ');
        fprintf('Typical values are 95 or 90.\n\n');
    else
        num = round(num);
        set(findobj('Tag', 'conint_edit'), 'String', int2str(num));
        set(findobj('Tag', 'process_button'), 'Enable', 'on');        
    end
    return;

end


if strcmp(op, 'con_edit')

end


if strcmp(op, 'con_remove')

end


if strcmp(op, 'con_add')

end


if strcmp(op, 'out_omit_check')
    resdir = get(findobj('Tag', 'resdir_edit'), 'UserData');    
    load(fullfile(resdir, 'SPM.mat'));
    if exist('Sess')
        % these are SPM99 results
        nsess = length(Sess);
        n = length(Sess{1}.row);
    else
        % these are SPM2 results
        nsess = length(SPM.Sess);
        n = length(SPM.Sess(1).row);
        % see, that's the kind of thing that drives a sane
        % programmer crazy.
    end

    string = get(findobj('Tag', 'out_omit_edit'), 'String');
    if (isempty(string)) | (all(isspace(string)))
        ok = 1;
        set(findobj('Tag', 'out_omit_edit'), 'String', '');
        set(findobj('Tag', 'out_omit_edit'), 'UserData', []);
        return;
    end        
    [omit, ok] = str2num(string);        
    if ~isempty(omit)
        if length(omit) ~= nsess
            ok = 0;
        end
        if min(omit) < 1
            ok = 0;
        end
        if max(omit) > n
            ok = 0;
        end
    end
    if ~ok
        set(findobj('tag', 'out_omit_edit'), 'String', '');
        set(findobj('Tag', 'out_omit_edit'), 'UserData', []);
        fprintf('\n\nSorry, %s is not a valid input for omitted.\n', string);
        fprintf('This space has to be a series of positive integers separated by spaces,\n');
        fprintf('one and only one number for each session.\n');
        fprintf('No number may be larger than the number of images in a session.\n');
    else
        omit = round(omit);
        set(findobj('tag', 'out_omit_edit'), 'String', int2str(omit));
        for i=1:length(omit)
            data{i} = omit(i);
        end
        set(findobj('tag', 'out_omit_edit'), 'UserData', data);
    end
    return;
end


if strcmp(op, 'out_prev_omit_check')
    resdir = get(findobj('Tag', 'resdir_edit'), 'UserData');    
    load(fullfile(resdir, 'SPM.mat'));
    if exist('Sess')
        % these are SPM99 results
        nsess = length(Sess);
        n = length(Sess{1}.row);
    else
        % these are SPM2 results
        nsess = length(SPM.Sess);
        n = length(SPM.Sess(1).row);
        % see, that's the kind of thing that drives a sane
        % programmer crazy.
    end

    string = get(findobj('Tag', 'out_prev_omit_edit'), 'String');
    ok = 1;
    if (isempty(string)) | (all(isspace(string)))
        ok = 1;
        set(findobj('Tag', 'out_prev_omit_edit'), 'String', '');
        set(findobj('Tag', 'out_prev_omit_edit'), 'UserData', []);
        return;
    end
    [prev_omit, convert_ok] = str2num(string);
    if ~convert_ok
        % string is not just string of numbers
        prev_omit = eval(string);        
    end
    if ~isempty(prev_omit)
        if iscell(prev_omit)
            if length(prev_omit) ~= nsess
                ok = 0;
            else
                for i = 1:length(prev_omit)
                    min_array(i) = min(prev_omit{i});
                    max_array(i) = max(prev_omit{i});
                end
                if (any(min_array < 1)) | (any(max_array) > n)
                    ok = 0;
                end
            end
        elseif ~isnumeric(prev_omit)
            ok = 0;
        else
            % not a cell array, just a string of numbers
            if (max(prev_omit) > n) | (min(prev_omit) < 1)
                ok = 0;
            end
        end
    end
    if ~ok
        set(findobj('tag', 'out_prev_omit_edit'), 'String', '');
        set(findobj('Tag', 'out_prev_omit_edit'), 'UserData', []);
        fprintf('\n\nSorry, %s is not a valid input for previously omitted.\n', string);
        fprintf('This space has to be a single number or vector (to specify the same\n');
        fprintf('dropped scans for each session), or a string specifying a cell array\n');
        fprintf('with one element for each session (e.g. {1:8; 2; 5:8}.)\n');
        fprintf('No number may be larger than the number of images in a session\n');
        fprintf('or negative.\n');
        fprintf('If you have questions about what this button does, contact Jeff\n');
        fprintf('at jcooper@stanford.edu.\n');
        beep;
    else
        if iscell(prev_omit)
            data = prev_omit;
        else
            for i = 1:nsess
                data{i} = prev_omit;
            end
        end
        set(findobj('tag', 'out_prev_omit_edit'), 'UserData', data);
    end
    return;
    
end


if strcmp(op, 'out_sess')
    set(findobj('Tag', 'out_sess_no'), 'Value', 0);
    set(findobj('Tag', 'out_sess_yes'), 'Value', 1);    
    return;  
end


if strcmp(op, 'out_nosess')
    set(findobj('Tag', 'out_sess_yes'), 'Value', 0);
    set(findobj('Tag', 'out_sess_no'), 'Value', 1);    
    return; 
end


if strcmp(op, 'out_outdir_choose')
    outdir = spm_get(-1, '*.img', 'Please select output directory');
    
    set(findobj('Tag', 'out_outdir_edit'), 'UserData', outdir);
    set(findobj('Tag', 'out_outdir_edit'), 'String', spm_str_manip(outdir, 'a25'));
    return;
end

if strcmp(op, 'help')

end


if strcmp(op, 'process')
    
    % temp for lab meeting
    %math_test_roi_deconvolve_interface(5, 95);  
    
    %return;
    
    
    % Create Design struct
    % ---------------------
    Design = struct(...
                'roi_fname', [], ...
                'roi_name', [], ...
                'XYZvox', [], ...
                'XYZmm', [], ...
                'subj_name', [], ...
                'exp_dir', [], ...
                'resdir', [], ...
                'prepend', [], ...
                'outdir', [], ...
                'sess_out', [], ...
                'des_fname', [], ...
                'SPMver', [], ...
                'nsess', [], ...
                'TR', [], ...
                'n_lags', [], ...
                'omitted', [], ...
                'V', [], ...
                'Cond', [], ...
                'base_flags', [], ...
                'preproc_flags', [], ...
                'Contrasts', []);  
            
    % Get bits we can from interface
    % -------------------------------
    prepend = get(findobj('Tag', 'out_prepend_edit'), 'String');
    if ~isempty(prepend)
        prepend = [prepend '_'];
    end
    outdir = get(findobj('Tag', 'out_outdir_edit'), 'UserData');
    sess_out = get(findobj('Tag', 'out_sess_yes'), 'Value');
    omitted = get(findobj('Tag', 'out_omit_edit'), 'UserData');
    prev_omitted = get(findobj('Tag', 'out_prev_omit_edit'), 'UserData');
    % Note - must make sure c matrix for contrasts is sparse
    Contrasts = get(findobj('Tag', 'con_list'), 'UserData');
    IRF_LENGTH = str2num(get(findobj('Tag', 'irf_edit'), 'String'));
    CON_INT = str2num(get(findobj('Tag', 'conint_edit'), 'String'));
    
    base_flags = struct(...
        'base_timeflag', get(findobj('Tag', 'base_timeflag_vary_button'), 'Value'),...
        'base_condflag', get(findobj('Tag', 'base_condflag_cond_button'), 'Value'),...
        'base_cond_idx', 0, ...
        'base_region', get(findobj('Tag', 'base_regflag_popup'), 'Value'),...
        'base_mask', [],...
        'base_neg', [],...
        'base_template', []);
    if base_flags.base_condflag
        base_flags.base_cond_idx = get(findobj('Tag', 'base_condflag_popup'), 'Value');
    end
    if base_flags.base_region == 3
        base_flags.base_mask = get(findobj('Tag', 'base_regflag_mask_edit'), 'UserData');
    elseif base_flags.base_region == 4
        base_flags.base_neg = get(findobj('Tag', 'base_regflag_mask_edit'), 'UserData');
        base_flags.base_template = get(findobj('Tag', 'base_regflag_temp_edit'), 'UserData');
    end
        
    preproc_flags = struct(...
        'trim', get(findobj('Tag', 'preproc_trim_yes'), 'Value'),...
        'trim_amt', 2,...
        'detr', get(findobj('Tag', 'preproc_detr_yes'), 'Value'),...
        'lowpass', get(findobj('Tag', 'preproc_low_yes'), 'Value'),...
        'low_choice', 'none',...
        'low_param', 0,...
        'highpass', get(findobj('Tag', 'preproc_high_yes'), 'Value'),...
        'high_choice', [],...
        'high_param', 0);
    if preproc_flags.lowpass
        preproc_flags.low_param = get(findobj('Tag', 'preproc_low_edit'), 'String');
        [new_param, ok] = str2num(preproc_flags.low_param);
        if ok
            preproc_flags.low_param = new_param;
            preproc_flag.low_choice = 'Gaussian';
        else
            if strcmp(preproc_flags.low_param, 'hrf')
                preproc_flags.low_param = 0;
                preproc_flags.low_choice = 'hrf';
            else
                error('Unrecognizable string in low-pass filter kernel box!');
            end
        end
    end
    if preproc_flags.highpass
        preproc_flags.high_choice = 'specify';
        preproc_flags.high_param = str2num(get(findobj('Tag', 'preproc_high_edit'), 'String'));
    end

    % Subject loop
    % ---------------------
    
    subj = get(findobj('Tag', 'subj_list'), 'UserData');
    rois = get(findobj('Tag', 'rois_list'), 'UserData');
    resdir = get(findobj('Tag', 'resdir_edit'), 'UserData');
    %keyboard;        
    k = 1;
    for i = 1:length(subj)
        curr_sub = deblank(subj{i});
        [exp_dir, subj_name] = fileparts(curr_sub);    
        curr_resdir = fullfile(exp_dir, subj_name, resdir);
       
        % determine if SPM99 or SPM2
        if exist(fullfile(curr_resdir, 'SPMcfg.mat'))
            % SPM99
            curr_respath = fullfile(curr_resdir, 'SPMcfg.mat');
            SPMver = 99;
            
            % extract necessary parameters from design file
            load(curr_respath);
            TR = xX.RT;
            V.vol = VY;
            V.G = xGX.rg;
            V.iS = (xX.X(:,xX.iB))*(1:length(xX.iB))';  % nice line here from Kalina
            nsess = length(Sess);
            
            %% Correct for first-scan-omitted
            %% designs with old bch_tsampl3 - attempt to identify them by
            %% a misconnect between pst and VY
            %% ----------------------------------
            %first_scan_omit_flag = 0;
            %pst_sum = 0;
            %for s = 1:length(Sess)
            %    pst_idx = 1;
            %    while isempty(Sess{s}.pst{pst_idx})
            %        pst_idx = pst_idx + 1;
            %    end
            %     pst_sum = pst_sum + length(Sess{s}.pst{pst_idx});
            %end
            %if pst_sum~=length(VY)
            %    first_scan_omit_flag = 1;
            %    fprintf('PST/VY mismatch in subject %s - apparently scans deleted.  ', subj_name);
            %    fprintf('Attempting to compensate...\n');
            %end
                
            clear F_iX0 VY SPMid xM xX xGX xsDes;           
            
            Cond = struct('name', [],...
                'sess', [], ...
                'basemodel_flag', [],...
                'ons', [],...
                'dur', [],...
                'stim', []);
            r = 1;
            for s = 1:nsess;
                for c = 1:length(Sess{s}.name)
                    Cond(r).name = Sess{s}.name{c};
                    Cond(r).sess = s;
                    % conditions in baseline model currently
                    % disabled...
                    Cond(r).basemodel_flag = 0;
                    Cond(r).ons = Sess{s}.ons{c};
                    % onsets in SPM99 always stored in
                    % seconds
                    Cond(r).ons = Cond(r).ons / TR;
                    % ons always starts from 0, but we
                    % start counting at scan 1 in stim
                    % function
                    Cond(r).ons = (round(Cond(r).ons)) + 1;
                    
                    % handle previously omitted scans
                    if ~isempty(prev_omitted)
                        for p = 1:length(prev_omitted{s})
                            curr = prev_omitted{s}(p);
                            % subtract one from all onsets
                            % that happened AFTER this
                            % skipped onset - effectively
                            % shift time
                            to_shift = find(Cond(r).ons >= curr);
                            if ~isempty(to_shift)
                                Cond(r).ons(to_shift) = Cond(r).ons(to_shift) - 1;
                                % now we shifted time, so we
                                % need to shift the omitted
                                % scans as well
                                prev_omitted{s} = prev_omitted{s} - 1;
                            end
                        end
                    end
                    
                    % assemble dur
                    Cond(r).dur = 2 * ones(length(Cond(r).ons), 1);
                    % this next line is real code, but
                    % disabled until roi_deconvolve_find_dur
                    % is ready
                    %Cond(r).dur = [];
                    r = r + 1;
                end
            end
            clear Sess;
        else
            % SPM2
           curr_respath = fullfile(curr_resdir, 'SPM.mat');
           SPMver = 2;
            
            % extract necessary parameters from design file
            load(curr_respath);
            TR = SPM.xY.RT;
            V.vol = SPM.xY.VY;
            V.G = SPM.xGX.rg;
            V.iS = (SPM.xX.X(:,SPM.xX.iB))*(1:length(SPM.xX.iB))';
            nsess = length(SPM.Sess);
            
            Cond = struct('name', [],...
                'sess', [], ...                
                'basemodel_flag', [],...
                'ons', [],...
                'dur', [],...
                'stim', []);
            r = 1;
            for s = 1:nsess;
                for c = 1:length(SPM.Sess(s).U)
                    Cond(r).name = SPM.Sess(s).U(c).name{1};
                    Cond(r).sess = s;
                    % conditions in baseline model currently
                    % disabled...
                    Cond(r).basemodel_flag = 0;
                    Cond(r).ons = SPM.Sess(s).U(c).ons;
                    Cond(r).dur = SPM.Sess(s).U(c).dur;
                    if strcmp(SPM.xBF.UNITS, 'seconds')
                        Cond(r).ons = Cond(r).ons / TR;
                        Cond(r).dur = Cond(r).dur / TR;                        
                    end
                    Cond(r).ons = (round(Cond(r).ons)) + 1;
                    Cond(r).dur = round(Cond(r).dur);
                    r = r+1;
                end
            end
            clear SPM;
        end
        
        if isempty(Cond(1).dur)
            %Cond = roi_deconvolve_find_dur(curr_respath,Cond);
        end
        
        
        
        if ~sess_out
            % one stim function for each condition across
            % all sessions
            new_Cond = struct('name', [],...
                'sess', [], ...                
                'basemodel_flag', 0,...
                'stim', []);
            idx = zeros(length(Cond),1);
            for c = 1:length(Cond)
                names = vertcat({new_Cond.name}');
                element = find(strcmp(names, Cond(c).name));
                if isempty(element)
                    % no new_Cond by this name exists yet
                    new_Cond(end + 1).name = Cond(c).name;
                    idx(c) = length(new_Cond);
                else
                    idx(c) = element;
                end
            end
            % strip dummy new_Cond
            new_Cond = new_Cond(2:end);
            idx = idx - 1;
            
            for c = 1:length(new_Cond)
                new_Cond(c).sess = 1;
                new_Cond(c).stim = zeros(length(V.vol),1);
                % conditions in baseline model currently
                % disabled
                new_Cond(c).basemodel_flag = 0;
            end
            
        end
            
        % Set up stim functions
        for c = 1:length(Cond)
            Cond(c).stim = zeros(length(V.vol), 1);
            sess_length = length(find(V.iS==Cond(c).sess));
            % assume all sessions are same length            
            sess_offset = (Cond(c).sess - 1) * sess_length;
            deleted_onsets = [];
            for d = 1:length(Cond(c).ons)

                on_idx(d) = Cond(c).ons(d);

                if length(Cond(c).dur) > 1
                    % we have specified durations for each
                    % onset, so go to the specific one.
                    off_idx(d) = on_idx(d) + (Cond(c).dur(d) - 1);
                else
                    % we have a scalar for dur, which either
                    % means only one onset or identical
                    % durations for all of several onsets,
                    % so:
                    off_idx(d) = on_idx(d) + (Cond(c).dur(1) - 1);
                end
                % threshold on and off_idx
                if (on_idx(d) < 1)
                    % you could make a case we could just
                    % shift this up to onset 1 here, but as
                    % this generally occurs when we've
                    % omitted scans, we'll just strip this
                    % onset.
                    deleted_onsets(end + 1) = d;
                    continue;
                elseif (on_idx(d) > sess_length)
                    on_idx(d) = sess_length;
                end
                if (off_idx(d) < 1)
                    off_idx(d) = 1;
                elseif (off_idx(d) > sess_length)
                    off_idx(d) = sess_length;
                end 
                
                % add session offset
                on_idx(d) = on_idx(d) + sess_offset;
                off_idx(d) = off_idx(d) + sess_offset;
                
                                
                %%%%%%%%%%%%%%%%%%%%%%%%%%%
                % These next lines disabled for testing on
                % collinearity problem...
                %%%%%%%%%%%%%%%%%%%%%%%%%%%
                
                
                %% stim is set to one from onset of condition
                %% until its end, for each onset          
                % if sess_out
                %   Cond(c).stim(on_idx(d) : off_idx(d)) = 1;
                % else
                %    new_Cond(idx(c)).stim(on_idx(d) : off_idx(d)) = 1;
                % end
                
                
                %%%%%%%%%%%%%%%%%%%%%%%%%%
                % Temporary fix...
                %   - thresholding isn't correct for this
                %   style - if on_idx less than 1, continue,
                %   I think, no off_idx necessary                
                %%%%%%%%%%%%%%%%%%%%%%%%%%
                
                if sess_out
                    Cond(c).stim(on_idx(d)) = 1;
                else
                    new_Cond(idx(c)).stim(on_idx(d)) = 1;
                end
            end
            Cond(c).ons(deleted_onsets) = [];
            Cond(c).dur(deleted_onsets) = [];
        end % stim function loop
        
        if ~sess_out
            Cond = new_Cond;
        end
        
        % Now censor stim functions and other needed
        % structures.
        if ~isempty(omitted)
            for s = 1:nsess
                sess_idx = find(V.iS==s);
                first_sess_idx = sess_idx(1);
                sess_offset = first_sess_idx - 1;
                censor = omitted{s} + sess_offset;
                    
                % first censor images - this will
                % effectively censor Y in
                % roi_deconvolve_process.
                V.vol(censor) = [];
                V.iS(censor) = [];
                V.G(censor) = [];
                    
                % next censor stim functions
                for c = 1:length(Cond)
                    % and now here's the kind of ugly hack.
                    % You can make the case we should adjust
                    % the onset here, but seeing as how
                    % censoring may be used intentionally to
                    % remove trials, we'll just do the
                    % obvious thing here.  The commented
                    % code here could be used to adjust
                    % onsets instead of removing them...
                    %if Cond(c).stim(censor)==1
                    %    Cond(c).stim(censor + 1) = 1;
                    %end
                    Cond(c).stim(censor) = [];
                end
            end
        end

        % ROI loop
        % ----------------------------
        for j = 1:length(rois)
            curr_roi = deblank(rois{j});

            % names first
            [dummy_dir, roi_name, roi_ext] = fileparts(curr_roi);
            roi_name = spm_str_manip(roi_name, 'ud');

            % ROI data/coords
            V_roi = spm_vol(curr_roi);
            [Y_roi, XYZmm] = spm_read_vols(V_roi);
            XYZmm = XYZmm(:, find(Y_roi==max(max(max(Y_roi)))));
            clear Y_roi;
            
                     
            % Create Design struct, increment Design vector
            % counter k.
            Design(k).roi_fname = curr_roi;
            Design(k).roi_name = roi_name;
            Design(k).XYZmm = XYZmm;
            Design(k).subj_name = spm_str_manip(subj_name, 'd');
            Design(k).exp_dir = exp_dir;
            Design(k).resdir = curr_resdir;
            Design(k).prepend = prepend;
            Design(k).outdir = outdir; 
            Design(k).sess_out = sess_out;
            Design(k).des_fname = curr_respath;
            Design(k).SPMver = SPMver;
            Design(k).nsess = nsess;
            Design(k).TR = TR;
            Design(k).n_lags = (floor(IRF_LENGTH / TR)) + 1;
            Design(k).omitted = omitted;
            Design(k).V = V;
            Design(k).Cond = Cond;
            Design(k).base_flags = base_flags;
            Design(k).preproc_flags = preproc_flags;
            Design(k).Contrasts = Contrasts;
            k = k+1;
        end
    end

    cdir = pwd;
    cd(outdir);
    save('test_design.mat', 'Design');
    fid = fopen('test_stim_matrix.1D', 'w');
    for t = 1:length(Design(k -1).Cond(1).stim)
        for c = 1:length(Design(k-1).Cond)
            fprintf(fid, '%g\t', Design(k-1).Cond(c).stim(t));
        end
       fprintf(fid,'\n');
    end
    fprintf(fid, '\n\n');
    fclose(fid);
    cd(cdir);
    %keyboard;
    % Run main processing loop over Designs
    % ---------------------------------------
    roi_deconvolve_process(Design, IRF_LENGTH, CON_INT);
    
end % if op=process statement