function out = fy_normalise(files,runnormalise)
%fy_normalise: Normalise images at a time
%This function is a tool to normalise images. When one does Normalise est &
%write, one has to identify the image to be normalised twice. When one has
%many image files, identifying images twice by hand can be tough and
%cause human errors. With this script all you need to select images once
%and the script handles rest of the normalisation.
%Usage:
%fy_normalise  without any arguments, the script just makes a mat file
%which can be used in the batch later and doesn't run normalisation.
%
%fy_normalise('',1) If you specify 1, it brings up a dialogue of file
%selection and normalise the selected files.
% 
% Written by Fumio Yamashita, 13 Jan 2014

%% initialize batch
spm('defaults','pet');
spm_jobman('initcfg');

%% check argument
if nargin == 0 || isempty(files)
    files = spm_select(Inf,'image','Select image files to be normalised');
end
if nargin <= 1
    runnormalise = 0;% 1 for run normalise (not only batch saving)
end

%% set output directory
outputdir = spm_select(1,'dir','Select an output directory for batch file');

%% set target files
for i=1:size(files,1)
    file = deblank(files(i,:));
    matlabbatch{1}.spm.spatial.normalise.estwrite.subj(i).source{1} = file;
    matlabbatch{1}.spm.spatial.normalise.estwrite.subj(i).wtsrc = '';
    matlabbatch{1}.spm.spatial.normalise.estwrite.subj(i).resample{1} = file;
end

%% parameter for normalisation
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.template{1} = fullfile(spm('dir'),'templates','SPECT.nii');
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.weight = '';
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.smosrc = 8;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.smoref = 0;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.regtype = 'mni';
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.cutoff = 25;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.nits = 16; % default:16, 0 for affine only
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.reg = 1;
matlabbatch{1}.spm.spatial.normalise.estwrite.roptions.preserve = 0;
matlabbatch{1}.spm.spatial.normalise.estwrite.roptions.bb = [-78 -112 -50;78 76 85];% default:[-78 -112 -50;78 76 85], [nan nan nan;nan nan nan] to fit template's bounding box
matlabbatch{1}.spm.spatial.normalise.estwrite.roptions.vox = [2 2 2];% default:[2 2 2], [nan nan nan] to use template's voxel size
matlabbatch{1}.spm.spatial.normalise.estwrite.roptions.interp = 1;
matlabbatch{1}.spm.spatial.normalise.estwrite.roptions.wrap = [0 0 0];
matlabbatch{1}.spm.spatial.normalise.estwrite.roptions.prefix = 'w';

%% save batch file
save([outputdir 'spm_normalise_' datestr(now,'yyyymmdd_HHMMSS') '.mat'],'matlabbatch');

%% run normalise
if runnormalise == 1
    spm_jobman('run',matlabbatch);
end