% Command-line based SPM results display for AA results.
% showAAResults(aadir,subjectn,contrast,correction,threshold)
% Where
% aadir - directory where aap_parameters.mat may be found
% subjectn - I for subject in aap
% contrast - I for contrast in subject's SPM.mat
% correction - 'none','FWE','FDR'
% threshold - p/t value
% All arguments are optional. Try leaving one out (or make it [])
% and see what happens. In particular, leaving out subjectn or
% contrastn brings up reference lists of indices for these.
% 16/1/2011 J Carlin
% 18/2/2011 Updated for SPM8 compatibility

function showAAResults(aadir,subjectn,contrastn,correction,threshold)

% If you tell us no dir, assume we're already there
if ~exist('aadir','var') || isempty(aadir)
    fprintf('No aadir defined - assume it''s pwd\n')
    aadir = pwd;
end

load(fullfile(aadir,'aap_parameters.mat'))


% --- PARAMETER TO CHANGE --- %
%addpath /Users/johan/code/UtilityScripts/BatchPrintSPMs %Change to where this is saved

subjroot = aadir;
ana_dir = aap.directory_conventions.stats_singlesubj;

def = '';
if ~exist('correction','var') || isempty(correction)
    correction = 'none';
    def = 'default ';
end
fprintf('Using %scorrection: %s', def,correction);

def = '';
if ~exist('threshold','var') || isempty(threshold)
    threshold = 0.001;
    def = 'default ';
end
fprintf(', %sp<%.03f\n', def, threshold)

% TODO - second level analysis

% Get subject paths
for s = 1:length(aap.acq_details.subjects)
    subjpaths{s} = aas_getsubjpath(aap,s);
end

% Test if we need to return a list.
simpletest = @(x) ~exist(x) || isempty(eval(x)) || strcmp(eval(x),'list');

% Return a list of subjects, with indices
if simpletest('subjectn')
    subjlist = [num2str((1:length(subjpaths))','%03d') repmat(' ',length(subjpaths),1) char(subjpaths)];
    fprintf('Must define a subject (by its index):\n')
    display(subjlist)
    return
end

% Get contrasts for this subject
spmpath = fullfile(subjpaths{subjectn},ana_dir,'SPM.mat');

if simpletest('contrastn')
	load(spmpath);
	contrastnames = {SPM.xCon.name};
    contrastlist = [num2str((1:length(contrastnames))','%03d') repmat(' ',length(contrastnames),1) char(contrastnames)];
    fprintf('Must define a contrast (by its index):\n')
    display(contrastlist)
    return
end

% Now using SPM8 batch functionality
matlabbatch{1}.spm.stats.results.spmmat = cellstr(spmpath);
matlabbatch{1}.spm.stats.results.conspec.titlestr = '';
matlabbatch{1}.spm.stats.results.conspec.contrasts = contrastn;
matlabbatch{1}.spm.stats.results.conspec.threshdesc = correction;
matlabbatch{1}.spm.stats.results.conspec.thresh = threshold;
matlabbatch{1}.spm.stats.results.conspec.extent = 0;
matlabbatch{1}.spm.stats.results.conspec.mask = struct('contrasts', {}, ...
	'thresh', {}, 'mtype', {});
matlabbatch{1}.spm.stats.results.units = 1;
matlabbatch{1}.spm.stats.results.print = false;

spm('defaults','FMRI');
spm_jobman('serial',matlabbatch);
return
