function make_template_auto_manager(V,modality,graphicmode,estimate,modulation,optimal,NRMsourceweight, NRMtemplateweight,SEGsourceweight, SEGtemplateweight,ApplyMask,write_seg,results_dir,stime,Xserver,ddd,nnn,ggg,www,ccc,sss,l1)
%(V,VGO,graphicmode,estimate,modulation,optimal,NRMsourceweight, NRMtemplateweight,SEGsourceweight, SEGtemplateweight, ApplyMask,write_seg)
%CG_CREATE_TEMPLATE
%s8template=  make_template_auto(V,VGO,1,1,0,1,0,1,0,1,0,0);
%
% creation of customized template and prior images for vbm analysis
%
% Run this script by selecting all anatomical images of your sample
% to be analyzed. This function creates a new template and prior images
% which are smoothed with fwhm of 8 mm.
%
% You can run the whole procedure in one step or only calculate the new
% template and the priors from already segmented data. The second option
% is useful if you calculated segmented images using the first option and
% you don't want to include all subjects to caluclat the template and priors.
% inputs
% V                 : volumes to normalize       (spm volume structure)
% VGO               : template for normalisation (spm volume structure)
% graphicmode       : 0|1 (no graphics | graphics)
% estimate          : 0|1 (average previous estimates | make new estimates & average)
% modulation        : 0|1 (no|yes) 
% optimal           : 0|1 (standard VBM | optimized VBM)
% NRMsourceweight   : 0|1 (no|yes)
% NRMtemplateweight : 0|1 (no|yes)
% SEGsourceweight   : 0|1 (no|yes)
% SEGtemplateweight : 0|1 (no|yes)
% ApplyMask         : 0|1 (no|yes)
% write_seg         : 0|1 (no|yes) write_seg=1 saves segmented GM, WM, and CSF images to disk
%
%  
% output images:
%---------------
%	s8template.img:	smoothed template
%	s8gray.img:	    smoothed gray matter prior image
%	s8white.img:	smoothed white matter prior image
%	s8csf.img:	    smoothed CSF prior image
%
% Additionally all temporary images (warped and segmented images) are saved
% and can be removed after calculation of template and prior images:
%
%	w*.img		warped raw image
%	w*_seg1.img	gray matter image
%	w*_seg2.img	white matter image
%	w*_seg3.img	CSF image
%_______________________________________________________________________
% @(#)cg_create_template.m	1.13 Christian Gaser 03/09/02  
% adapted from: @(#)cg_create_template.m	1.13 Christian Gaser 03/09/02
% modified script of John Ashburner
%spm_pathdef;
%  if nargin>0
%    V= varargin{1};
%  end
%  if nargin>1
%    VG0= varargin{2};
%  end
cd(results_dir)
disp(['results_dir = ',results_dir])
disp('creating custom template (make_template_auto_manager.m)')
spm_defaults
global defaults
dseg			= defaults.segment;
dseg.write.wrt_cor	= 0;
dseg.estimate.affreg.weight	= fullfile(spm('Dir'),'apriori','brainmask.mnc');	% always use brainmask
% (can be switched off by setting SEGtemplateweight=0)
dseg.write.cleanup   		= 1;		% clean up partitions

dseg.estimate.affreg.sourceweight = '';
VWF='';
VWG='';
dnrm			= defaults.normalise;
dnrm.write.vox		= [1 1 1];
%dnrm.write.bb		= reshape([-90 90 -126 90 -72 108],2,3);
%dnrm.estimate.graphics	= 0;   % Crashes otherwise
% dnrm.write.bb		= [-90 -111 -90;90 111 108];
% bby1=input('bby1 [e.g. -111] ?');
% bby2=input('bby2 [e.g.  111] ?');
% if bby1==Inf | bby2==Inf
    dnrm.write.bb = [Inf Inf Inf;Inf Inf Inf];
% else
%     dnrm.write.bb(1,1) = -abs(bby1);
%     dnrm.write.bb(1,2) = abs(bby2);
% end
%disp('bb = ')
%disp(num2str(dnrm.write.bb))
dnrm.estimate.graphics	= 1;  % display normalisation graphics
% -78  -112   -70
%    78    76    85
if ~exist('email','var')
    email = spm_input('Email address to notify?','+1','s','Senjem.Matthew1@mayo.edu');
end
if ~exist('estimate','var')
    estimate = spm_input('What to do?',1,'m',...
        'segment images and create template and prior images|use previously segmented images to create template and priors',[1 0], 1);
end
if ~exist('modulation','var')
    modulation = spm_input('additional modulation?',1,'m','modulation|no modulation',[1 0], 1);
end
if ~exist('remove_inputs','var')
    remove_inputs = 0;%spm_input('Delete intermediate files?',1,'m','Yes|No',[1 0], 1);
end
% estimate segmentation
if estimate
    
    if ~exist('optimal','var')
        optimal = spm_input('Normalize to Whole Head/GM/WM ?',1,'m','Normalize to Whole Head|Normalize to GM prior|Normalize to WM prior',[0 1 2], 1);
        %optimal = spm_input('Standard or Optimized VBM?',1,'m','Standard|Optimized (GM)|optimized (WM)',[0 1 2], 2);
    end
    if ~exist('NRMsourceweight','var')
        NRMsourceweight   = get_weight(0,'NRM source'); 
    end
    if ~exist('NRMtemplateweight','var')
        NRMtemplateweight = get_weight(0,'NRM template'); 
    end
    if ~exist('SEGsourceweight','var')
        SEGsourceweight   = get_weight(0,'SEG source');
    end
    if ~exist('SEGtemplateweight','var')
        SEGtemplateweight = get_weight(0,'SEG template'); 
    end
    if ~exist('ApplyMask','var')
        ApplyMask = get_ApplyMask(0);
    end
    if (~exist('V','var') | isempty(V))
        V   = spm_vol(spm_get(Inf,'*.IMAGE','Select images'));
    end
    if iscell(V)
        for vi = 1:length(V)
            Vv(vi) = spm_vol(V{vi});
        end
        clear V
        V=Vv;
    end
else
    % average images to new template and prior images
    if (~exist('V','var')| isempty(V))
        % first select normalized anatomical images
        V   = spm_vol(spm_get(Inf,'w*.IMAGE','Select normalized anatomical images'));
    end
    n = length(V);
    % ... and select same # of segmented images
    if ~exist('V1','var')
        V1   = spm_vol(spm_get(n,'*.IMAGE','Select gray matter images'));
    end
    if ~exist('V2','var')
        V2   = spm_vol(spm_get(n,'*.IMAGE','Select white matter images'));
    end
    if ~exist('V3','var')
        V3   = spm_vol(spm_get(n,'*.IMAGE','Select CSF images'));
    end
end
if ~exist('stime','var')
    stime=[date,'_',num2str(now)];%    stime = date;
end
sname = ['template_params_',stime,'.mat'];
save(sname)
disp(['saving parameters in ',sname])
if ~exist('l1','var')
    l1=0;
end
l=length(V);
l2=l1+l;
options=' -hold_jid ';
for i=1:l
    nn=0;
	filename=['MTAW_input',num2str(i+l1),'_',stime,'_',num2str(nn),'.mat'];
     while exist(filename,'file')
         nn=nn+1;
         filename=['MTAW_input',num2str(i+l1),'_',stime,'_',num2str(nn),'.mat'];
      end
    save(filename)
    [jobname1,savefile1]=sge_spawn_matlab('make_template_auto_worker',{filename},{num2str(i)},results_dir,'','',Xserver); % distribute this job to a worker
    jobnames{i}  = jobname1{1};
    savefiles{i} = savefile1{1};
    options=[options,jobnames{i},','];
end
options(end)=[]; % delete trailing comma.
options(end+1)=' '; % add a space for good measure
if exist('email','var') && ~isempty(email)
	options = [options '-m e -M ',email];
end
	
	nn=0;
filename=['MTAM_output_',stime,'_',num2str(nn),'.mat'];
while exist(filename,'file')
    nn=nn+1;
    filename=['MTAM_output_',stime,'_',num2str(nn),'.mat'];
end
save(filename)
np=0;
njnam=['template_',stime,'_',num2str(np)];
while exist(njnam,'dir')
    np=np+1;
njnam=['template_',stime,'_',num2str(np)];
end

remove_inputs = 0; % for testing purposes
[jobname1,savefile1]=sge_spawn_matlab2('sge_template_results',{filename},results_dir,'output',options,njnam,remove_inputs,Xserver);

return
