function run_xbeta
% ------------------------
% Utility function to carry out the running of roi_stats on
% the basic beta files and carving up results into appropriate
% files.
%
% Assumptions currently made in this labwide version include:
%   - no more than 999 beta images for any design matrix
%      
%


expdir = spm_get(-1, '*', 'Select experiment home directory');


names = spm_get(-Inf, '*', 'Select subject home directories');
names = cellstr(names);
names = deblank(names);
for i = 1:length(names)
    curr = names{i};
    [dummy_dir, names{i}] = fileparts(curr);
end



full_resdir = spm_get(-1, '*', 'Select results directory from one subject');
[dummy_dir, resdir] = fileparts(full_resdir);
resdir = deblank(resdir);
if (exist(fullfile(expdir, names{1}, resdir, 'beta_0001.img')))==0
    % results directory is not at first level of subject dir
    [test_dummy_dir, test_dir] = fileparts(dummy_dir);
    while(~(strcmp(test_dir, names{1})))
        [dummy_dir, newpart] = fileparts(dummy_dir);
        resdir = fullfile(newpart, resdir);
        [test_dummy_dir, test_dir] = fileparts(dummy_dir);
    end
end
resdir = deblank(resdir);  %I'm being compulsive; I apologize.

if (exist(fullfile(expdir, names{1}, resdir, 'SPMcfg.mat'), 'file'))==0;
    full_cfg_path = spm_get(1, 'SPMcfg.mat', 'Please locate SPMcfg.mat file for a subject.');
else
    full_cfg_path = fullfile(expdir, names{1}, resdir, 'SPMcfg.mat');
end  
sample_cond = kc_get_design('Load', full_cfg_path);
cond_list = vertcat(sample_cond.name);


ntypes = spm_input_ui('How many trial types to extract from?',1,'i','',1);
for t = 1:ntypes
    condidx = spm_input_ui(['Trial type ' num2str(t) ': choose type'],'+1','m',char(cond_list))
    types{t} = deblank(cond_list{condidx});
end

sess_flag = spm_input_ui('Save session-by-session data?', '+1', 'y/n', [1 0], 2);


rois = spm_get(Inf,'*.img','Select ROI .img files');
rois = char(rois);

destpath = spm_get(-1, '*', 'Select destination directory for text files');


for i = 1:length(names)
    curr_name = spm_str_manip(names{i},'u');  % remove illegal chars; '-' mainly
    curr_beta_path = fullfile(expdir, curr_name, resdir);
    if (exist(fullfile(curr_beta_path, 'SPMcfg.mat'), 'file'))==0;
        full_cfg_path = spm_get(1, 'SPMcfg.mat', 'Please locate SPMcfg.mat file for this subject.');
    else
        full_cfg_path = fullfile(curr_beta_path, 'SPMcfg.mat');
    end
    Cond = kc_get_design('Load', full_cfg_path);
    cond_name_list = vertcat(Cond.name);
    if ~isletter(curr_name(1))
        % starts with a non-letter, so prepend flag for
        % Matlab variable names
        curr_name = ['nonletter' curr_name];
    end
    for j = 1:ntypes
        curr_betas = [];
        curr_cond = Cond(find(strcmp(cond_name_list, types{j})));
        if length(curr_cond)>1
            error('More than one condition with selected name for this subject.');
        end
        curr_idx = curr_cond.iC;
        for k = 1:length(curr_idx)
            curr_sing_idx = curr_idx(k);
            if curr_sing_idx < 10
                curr_sing_idx = ['00' num2str(curr_sing_idx)];
            elseif curr_sing_idx < 100
                curr_sing_idx = ['0' num2str(curr_sing_idx)];
            else
                curr_sing_idx = num2str(curr_sing_idx);
            end
            eval(['curr_betas = vertcat(curr_betas, spm_get(''files'',curr_beta_path,''beta_0' curr_sing_idx '.img''));']);
        end
        eval([curr_name '_roi = xbeta_roi_stats(rois, curr_betas);']);
        if ~sess_flag
            xbeta_divvy_up_params(curr_name, eval([curr_name '_roi']), spm_str_manip(types{j}, 'u'), destpath);
        else
            xbeta_divvy_up_params_session(curr_name, eval([curr_name '_roi']), spm_str_manip(types{j}, 'u'), destpath);
        end
    end
end

xbeta_break_params_to_rois(rois, destpath);

if ~sess_flag
    xbeta_mat_to_txt(names, types, destpath);
else
    xbeta_mat_to_txt_session(names, types, destpath);
end

delete(fullfile(destpath, '*_xbeta.mat'));
