function norm_fluid_auto_manager(varargin)
%%%%
[V,matfiles,W,VG0,priors,graphicmode,modulation,optimal,NRMsourceweight,...
    NRMtemplateweight,SEGsourceweight, SEGtemplateweight, ApplyMask, ...
    max_seg, writeseg,writeanat,writeepi,bmask,voxsize,smoothing,fwhm,results_dir,stime,email,priority] = deal(varargin{1:nargin});

Xserver = 'mr-bill:1.0';
own_prior=1;
if ~exist('email','var')
    email = spm_input('Email address to notify?','+1','s','Senjem.Matthew1@mayo.edu');
end
if ~exist('priority','var')
    priority = spm_input('Job priority?','+1','i',1);
end
priority = min(1024,max(-1024,priority));
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
disp('normalizing ... (norm_fluid_auto_manager.m)')
spm_defaults;
global defaults
dseg				= defaults.segment;
dseg.write.wrt_cor		= 0;		% don't write bias corrected image
%dseg.estimate.affreg.weight	= fullfile(spm('Dir'),'apriori','brainmask.mnc');	% always use brainmask
dseg.write.cleanup   		= 1;		% clean up partitions
dseg.estimate.affreg.sourceweight = '';
VWF='';
VWG='';

dnrm				= defaults.normalise;
if length(voxsize)==1
    dnrm.write.vox			= [voxsize voxsize voxsize];%[.859 .859 .859];%[1 1 1];
elseif length(voxsize)==3
    dnrm.write.vox			= [voxsize];
end
dnrm.write.vox			= [1 1 1];
dnrm.write.bb = [Inf Inf Inf;Inf Inf Inf];%  (1,3)		= -70;		% enlarge z-axis to include more cerebellum
dnrm.estimate.graphics		= 1;		% display normalisation results in spm2.ps file
if ~exist('V','var')
    V   = spm_vol(spm_get(Inf,'*.IMAGE','Select raw (not normalized) images'));
end
if ~exist('matfiles','var')
    matfiles   = {};%spm_get([0 length(V)],'*_sn.mat',{'Select *_sn.mat files'});
end
if ~exist('W','var')
    for i=1:length(V)
        [pth,nam,ext] = fileparts(V(i).fname);
        str=['Select EPI images for ',nam];
        fltr=['*',nam(1:4),'*.IMAGE'];
        WW  = spm_get(Inf,{fltr},{str});
        if ~isempty(WW)
            W(i,:)   = spm_vol(WW);
        end
    end
end
if ~exist('VG0','var')
    VG0 = spm_vol(spm_get(1,'*T1*.IMAGE','Select T1 template for first normalization'));
end
if ~exist('max_seg','var')

    max_seg    = spm_input('Calculate',1,'m','gray matter|gray+white matter|all',[1 2 3],1);
end
if ~exist('modulation','var')

    modulation = spm_input('Additional modulation?','+1','yes|no',[1 0],2);
end
if ~exist('own_prior','var')
    own_prior  = spm_input('Use own prior images?','+1','yes|no',[1 0],2);
end
if ~exist('priors','var')

    if own_prior
        dseg.estimate.priors = spm_get(3,'*.IMAGE','Select gray/white and CSF prior images');
    end
else
    dseg.estimate.priors = priors;
end

% change default parameters for (non)linear normalization
%dnrm.estimate.cutoff = get_cutoff(dnrm.estimate.cutoff);
%if dnrm.estimate.cutoff ~= Inf
%    dnrm.estimate.reg    = get_reg(dnrm.estimate.reg);
%    dnrm.estimate.nits   = get_nits(dnrm.estimate.nits);
%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 NRMtemplateweight
    VWG = fullfile(spm('Dir'),'apriori','brainmask.mnc');%
else
    VWG = '';
end
if SEGtemplateweight
    dseg.estimate.affreg.weight= fullfile(spm('Dir'),'apriori','brainmask.mnc');%
else
    dseg.estimate.affreg.weight= '';
end
%if ~exist('VG1','var')
%    VG1 = spm_vol(spm_get(1,'*gray*.IMAGE','Select own prior (gray) image for normalization'));
%end
if optimal==1
    VG1 = spm_vol(dseg.estimate.priors(1,:));
elseif optimal==2
    VG1 = spm_vol(dseg.estimate.priors(2,:))
end
% create graphics window
fg=spm_figure('FindWin','Graphics');
if isempty(fg), fg=spm_figure('Create','Graphics'); end
%if exist('reuse_anat','var')&reuse_anat
%else
% save gray/white matter and csf volumes in log-file
logname = 'vbm_volumes.txt';
if exist(logname,'file');
    fid = fopen(logname,'a');
else
    fid = fopen(logname,'w');
    fprintf(fid,'Volume [ml]\tgray\twhite\tcsf');
end
save(['NFAparams_',stime,'.mat'])
disp(['saved parameters in NFAparams_',stime,'.mat']);

if exist('priority','var') && ~isempty(priority)
    opt = [' -p ',num2str(priority),' '];
else opt='';
end


l=length(V);
options=' -hold_jid ';
for i=1:l
    options1 = '';
    [pth,nam,ext] = fileparts(V(i).fname);
    matname0 = fullfile(pth,[nam '_sn.mat']);
    if ~exist(matname0,'file')
        disp(['creating ',matname0])
        nn=0;
        filename = ['MTAW_',num2str(i),'_',stime,'_',num2str(nn),'.mat'];
        while exist(filename,'file')
            nn=nn+1;
            filename=['MTAW_',num2str(i),'_',stime,'_',num2str(nn),'.mat'];
        end
        estimate=1;
        save(filename)
        [jobname1,savefile1]=sge_spawn_matlab('make_template_auto_worker',{filename},{num2str(i)},results_dir,'',opt,Xserver); % distribute this job to a worker
        options1=[' -hold_jid ',jobname1{1},' '];
    end

    nn=0;
    filename=['NFAW_',num2str(i),'_',stime,'_',num2str(nn),'.mat'];
    while exist(filename,'file')
        nn=nn+1;
        filename=['NFAW_',num2str(i),'_',stime,'_',num2str(nn),'.mat'];
    end
    save(filename)
    [jobname1,savefile1]= sge_spawn_matlab('norm_fluid_auto_worker',{filename},{num2str(i)},results_dir,'output',[options1,opt]); % distribute this job to a worker
    jobname{i}=jobname1{1};
    savefile{i}=savefile1{1};
    options=[options,jobname{i},','];
    % USAGE:
    % [jobname,savefile]=sge_spawn_matlab(function_name,filenames,numbers,results_dir,stime,savefilestub,options)
end
%this depends on previous jobs: fclose(fid);
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
if exist('priority','var') && ~isempty(priority)
    options = [options ' -p ',num2str(priority),' '];
end
nn=0;
filename=['NFAM_',stime,'_',num2str(nn),'.mat'];
while exist(filename,'file')
    nn=nn+1;
    filename=['NFAM_',stime,'_',num2str(nn),'.mat'];
end
save(filename)
np=0;
njnam=['sge_vbm_',stime,'_',num2str(np)];
while exist(njnam,'dir')
    np=np+1;
    njnam=['sge_vbm_',stime,'_',num2str(np)];
end
remove_inputs = 0; % for testing purposes
[jobname1,savefile1]=sge_spawn_matlab2('sge_vbm_results',{filename},results_dir,'output',options,njnam,remove_inputs,Xserver);
return