function [template,priors] = update_template(parr,modality,V2,sname)
% update_template.m: template creation for T1 or T2 images with SPM2.
% 
% Please note, with some setup work,
% this can be configured to run over Sun Grid Engine.  (SGE)
% By default SGE mode is disabled, but you can
% un-comment line 12 in vbm.m and line 19 in make_template.m 
% to allow SGE mode to be used. you will need to make some other changes in
% the code also.  Email me with any questions about SGE mode.
%
% SEE ALSO: vbm_ui.m, make_template.m
% Jan. 10, 2006
% Matthew L. Senjem
% Mayo Clinic 
% Senjem.Matthew1@mayo.edu
%
% When using this code, please reference the following paper:
%
% Senjem ML, Gunter JL, Shiung MM, Petersen RC, Jack CR Jr., "Comparison of different methodological implementations of voxel-based
% morphometry in neurodegenerative disease." Neuroimage. 2005 Jun;26(2):600-8. 

spm_defaults;
global defaults;
% if ~exist('template_cell','var')
%     template_cell{1} = spm_get(1,'template*.IMAGE','Select unsmoothed template to update'); 
%     template_cell{2} = spm_get(1,'gray*.IMAGE','Select unsmoothed GM prior to update'); 
%     template_cell{3} = spm_get(1,'white*.IMAGE','Select unsmoothed WM prior to update'); 
%     template_cell{4} = spm_get(1,'csf*.IMAGE','Select unsmoothed CSF prior to update'); 
% end
if ~exist('sname','var')
    sname   = spm_get(1,'*update-template-params*.mat','Select template params to update');
end
disp(['loading parameters from ',sname])
load(sname)
sge=1;
if exist('parr','var') && ~exist('sge','var')
    if strcmpi(parr,'sge')
        sge = 1;
    else
        sge=0;
    end
elseif ~exist('parr','var') && ~exist('sge','var')
    sge = spm_input('Run over SGE?','+1','m','YES|NO',[1 0], 1)
    
elseif exist('parr','var')
    if strcmpi(parr,'sge')
        sge = 1;
    else
        sge=0;
    end
end
%save
if ~exist('modality','var')
    moda = spm_input('Modality?','+1','m','T1|T2',[1 2], 1);
    switch moda
        case 1
            modality='t1';
        case 2
            modality='t2';
    end
end
stime=[date,'_',num2str(now)];%stime2=date;
if ~exist('results_dir','var')
    results_dir = spm_input('Directory to save results in?','+1','s',[pwd,filesep,'update_template-',stime2]);
end
cd('/')
if ~exist(results_dir,'dir')
    mkdir(results_dir)
end
cd(results_dir)
V2 = spm_vol(spm_get(Inf,'*.IMAGE','Select Additional Images'));
V3 = check4repeats(V,V2);
clear V2
V2=V3;
clear V3;
%sge_update_template(modality,ImgVols,results_dir,stime2,sname,template_cell,V2)
graphicmode=1;
estimate=1;
modulation=0;
optimal=1;
NRMsourceweight=0;
NRMtemplateweight=1;
SEGsourceweight=0;
SEGtemplateweight=1;
ApplyMask=0;
write_seg=0;
results_dir=results_dir;
stime2=stime2;
sname=sname;
Xserver='mr-bill:1.0';

sname2='update_template_inputs.mat';
disp(['saving parameters to ',sname2])
try l1=l2; catch l1=l; end
save(sname2)


if sge
    if ~exist('ddd','var')
        ddd=d;clear d
        nnn=n;clear n
        ggg=g;clear g
        www=w;clear w
        ccc=c;clear c
        sss=s;clear s

    end
    make_template_auto_manager(V2,modality,graphicmode,estimate,modulation,...
        optimal,NRMsourceweight, NRMtemplateweight,SEGsourceweight,...
        SEGtemplateweight,ApplyMask,write_seg,results_dir,stime2,...
        Xserver,ddd,nnn,ggg,www,ccc,sss,l1);
else
    if ~exist('d','var')
        d=ddd;clear ddd
        n=nnn;clear nnn
        g=ggg;clear ggg
        w=www;clear www
        c=ccc;clear ccc
        s=sss;clear sss
    end
    make_template_auto(V2,VG0,graphicmode,estimate,modulation,optimal,...
        NRMsourceweight, NRMtemplateweight,SEGsourceweight,...
        SEGtemplateweight,ApplyMask,write_seg,d,n,g,w,c,s,l1);
end


%_______________________________________________________________________
function weight = get_weight(weight,type)
% Get cutoff frequency of DCT bases
% FORMAT cutoff = get_cutoof(cutoff)
if (strcmp(type,'NRM template') | strcmp(type,'SEG template'))
    tmp2 = [0 1];
    choices = 'no mask|generic mask';
elseif (strcmp(type,'SEG source') | strcmp(type,'NRM source'))
    tmp2 = [0 1];
    choices = 'no mask|subject mask';
    
else
    error('incorrect type')
end
tmp = find(tmp2 == weight);
if isempty(tmp) tmp = length(tmp2); end;
weight = spm_input([type ' Weighting Mask'],'+1','m',...
    choices, tmp2, tmp);

return;
%_______________________________________________________________________
%function sge_update_template(modality,ImgVols,results_dir,stime2,sname,template_cell,V2)
%sge_update_template_auto_manager(ImgVols,modality,1,1,0,1,0,1,0,1,0,0,resu
%lts_dir,stime2,sname,template_cell,V2);

function V3 = check4repeats(V,V2)
%V3 = struct([]);
for i=1:length(V2)
%    disp(i)
    [p2,n2] = fileparts(V2(i).fname);
    for j=1:length(V)
        [p1,n1] = fileparts(V(j).fname);
        if all(n1==n2)
            %        warndlg([n2,'.img is already in the template!!'])
            qstring = char({n2;'.img is already in the template!!';'Do you want to add it again?'});
            button = questdlg(qstring,'WARNING!!','No');
            break
        else
            button='next';%
            continue
        end
    end
    switch button
        case 'Yes'
            disp(['ADDING repeat image ',n2,'.img to the list...'])
            try V3(end+1)=V2(i); catch V3(1)=V2(i); end
        case 'No'
            disp(['REMOVING repeat image ',n2,'.img from the list...'])
        case 'next' 
            try V3(end+1)=V2(i); catch V3(1)=V2(i); end
        otherwise
            error('You pressed Cancel!!')
    end
end
disp('__________________INPUT IMAGES___________________')
disp(char(V3.fname))
disp('_________________________________________________')
disp(' ')

return;