function mls_fluid_prep(varargin)
% This is a big, nasty routine to do fMRI SPM analysis
% Generally,
% To analyze BRIK files from a single subject, you should use fmri_new_spm.
% Not to worry, you WILL be prompted for any missing input arguments.
%
% this function will:
%      1. convert AFNI (*.BRIK, *.HEAD) files to AnalyzeImage(7.5) (*.img , *.hdr)
%         using the perl script brik2img1 installed on mr-matrix.mayo.edu in /usr/local/bin/
%      2. Try to distinguish Anatomical SPGR images from functional EPI images. (usually works)
%      3. Flip and re-orient the images in such that they are appropriate for SPM analysis.
%      4. co-register EPI volumes of each subject to the first EPI for that subject, creating a mean*.img
%      5. Use NMI to register mean*.img to the Anatomical scan , and apply these parameters to all EPI images.
%      6. (OPTIONAL) create a custom template from all the SPGR images.
%      7. Normalize T1 images to custom or MNI template, & apply these parameters to EPI images.
%      8. Smooth the Normalized EPI volumes by convolution with a Gaussian filter of the specified FWHM (defaults to 9 mm)
%      9. Enter the smoothed volumes into an SPM.mat data structure, and analyze the model,
%         complete with individualized contrasts for each session/subject.
% To create a custom template and normalize to it, using BRIK input
% files:
% mls_fmri_prep('BRIK','numsubjects',5,'sessionspersubject',3,'scanspersession',64,'smooth',9,'mktemplate','norm2custom')
% mls_fmri_prep('fmri','numsubjects',1,'sessionspersubject',5,'scanspersession',64,'stats')
% To create a custom template and normalize to it:
% mls_fmri_prep('numsubjects',5,'sessionspersubject',3,'scanspersession',64,'smooth',9,'mktemplate','norm2custom')
%
% To prompt the user for a template & priors to which to normalize:
% mls_fmri_prep('numsubjects',5,'sessionspersubject',3,'scanspersession',64,'smooth',9,'norm2custom')
%
% To normalize to MNI template
% mls_fmri_prep('numsubjects',5,'sessionspersubject',3,'scanspersession',64,'smooth',9,'norm2mni')
%
% Author: Matt Senjem, May 05, 2004.

% ver. 1.0
% Written by : Matt Senjem May 5, 2004.
%______________________________________________________________________________________________%

% ______________________________________________________________________________________________%

spm_defaults;
if nargin<1
    disp('Warning: no inputs specified !')
end
vbmLevel=0;
global defaults
if nargin==1 && iscell(varargin)
    foo=varargin{1};
    clear nargin
    narg=length(foo);
    clear varargin;
    varargin=foo;
    clear foo;
    %   [varargin{1:length(foo)}]=deal(foo);
else
    narg=nargin;
end
%  disp(['nargin = ',num2str(nargin)])
%  disp('varargin = ')
%  disp(varargin)
k=1;

while k<=narg

    if ischar(varargin{k}) && strcmpi(varargin{k},'numsubjects')
        if isnumeric(varargin{k+1})
            k=k+1;
            numsubjects=varargin{k};
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'optimal')
        if isnumeric(varargin{k+1})
            k=k+1;
            optimal = varargin{k};
        end
    elseif isstr(varargin{k}) & strcmpi(varargin{k},'stime')
        if ischar(varargin{k+1})
            k=k+1;
            stime = varargin{k};
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'results_dir')
        if isstr(varargin{k+1})
            k=k+1;
            results_dir = varargin{k};
        end
    elseif ischar(varargin{k}) && strcmp(varargin{k},'imgVols')
        if isstruct(varargin{k+1})
            k=k+1;
            imgVols=varargin{k};
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'sessionspersubject')
        if isnumeric(varargin{k+1})
            k=k+1;
            sesspersubj=varargin{k};
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'mktemplate')
        mktemplate=1;
        if ischar(varargin{k+1})
            if strcmpi(varargin{k+1},'t1')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','T1.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k+1},'pet')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','PET.mnc'));
                k=k+1;
            else
                error('must specify T1 or PET')
            end
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'flipepi')
        flipepi=1;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'stats')
        stats=1;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'vbm')
        vbmLevel=1;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'vbmonly')
        vbmLevel=2;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'flipanat')
        flipanat=1;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'checkreg')
        checkreg=1;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'pet')
        modality='pet';
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'fmri')
        modality='fmri';%modality2='';
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'fluid')
        modality='fluid';
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'norm2custom')
        norm2custom=1;
        if iscell(varargin{k+1})
            ctemplate_cell =varargin{k+1};
            k=k+1;
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'norm2mni')
        norm2mni=1;
        if ischar(varargin{k+1})
            if strcmpi(varargin{k+1},'t1')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','T1.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k},'t2')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','T2.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k},'pd')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','PD.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k},'spect')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','SPECT.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k},'pet')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','PET.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k},'epi')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','EPI.mnc'));
                k=k+1;
            elseif strcmpi(varargin{k},'transm')
                MNItemplate  = spm_vol(fullfile(spm('Dir'),'templates','transm.mnc'));
                k=k+1;
            else
                error('unknown modality')
            end
            ctemplate=MNItemplate;
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'smooth')
        smooth=1;
        if isnumeric(varargin{k+1})
            k=k+1;
            fwhm = [varargin{k} varargin{k} varargin{k} ];
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'voxsize')
        if isnumeric(varargin{k+1})
            k=k+1;
            voxsize = varargin{k};
            if length(voxsize)==1
            voxsize = [voxsize voxsize voxsize];
            elseif (length(voxsize)~=3 && length(voxsize)~=1)
                save
                error('voxsize should be length 1 or 3')
            end
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'prefix')
        if ischar(varargin{k+1})
            k=k+1;
            prefx=varargin{k};
        end
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'coreg')
        coreg=1;
    elseif ischar(varargin{k}) && strcmpi(varargin{k},'coreg&reslice')
        coreg=3;
        %	p = 1;%spm_input('Which option?',2,'m',...
        %	'Coregister only|Reslice Only|Coregister && Reslice', [1 2 3],3);
    else
        error(['unmkown input ', varargin{k}])
    end
    k=k+1;
end
%%
if ~exist('stime','var')
    stime=[date,'_',num2str(now)];%    stime = date;
end
%%

if ~exist('results_dir','var')
    results_dir = pwd;
    %    results_dir = spm_input('Directory to save results in?','+1','s',[pwd,filesep,stime]);

end
cd('/')
if ~exist(results_dir,'dir')
    mkdir(results_dir);
end
cd(results_dir)
%%
if ((exist('norm2custom','var') || exist('norm2mni','var')|| ...
        exist('coreg','var') || exist('coreg&&reslice','var') ||...
        exist('realign','var')) && ~exist('numsubjects','var'))
    numsubjects = spm_input('number of subjects','+1', 'e', 1);
end
if (exist('ctemplate_cell','var') && length(ctemplate_cell)==4)
    ctemplate = spm_vol(ctemplate_cell{1});
    cpriors = char(ctemplate_cell{2:4});
end
if (exist('mktemplate','var') || exist('norm2mni','var'))
    if ~exist('MNItemplate','var')
        MNItemplate  = spm_vol(spm_get(1,'*.IMAGE','Select MNI template for normalization'));
    end
end
if ~exist('modality','var')
    error('must specify a modality (fmri, fluid or pet)')
end
if (strcmpi('modality','fmri') && (exist('coreg','var') || exist('coreg&&reslice','var') || exist('realign','var')  || exist('stats','var')))
    if ~exist('sesspersubj','var')
        sesspersubj = spm_input('Num sessions per subject ', '+1', 'e',1);
    end
    if ~exist('scanspersess','var')
        scanspersess = spm_input('Num scans per session ', '+1', 'e',64);
    end
end
if exist('norm2custom','var') || exist('norm2mni','var')
    if exist('norm2custom','var') && norm2custom
        if ~exist('ctemplate','var')
            ctemplate = spm_vol(spm_get(1,'*.IMAGE','Select custom ctemplate for normalization'));
        end
        if ~exist('cpriors','var')
            priors = spm_get(3,'s*.IMAGE','Select gray/white and CSF prior images');
        else
            priors=cpriors;
        end

        if ~exist('NRMtemplateweight','var')
            NRMtemplateweight=0;
        end
        if ~exist('SEGtemplateweight','var')
            SEGtemplateweight=0;
        end
        if ~exist('bmask','var')
            bmask='';%fullfile(spm('Dir'),'apriori','brainmask.mnc');	%
        end
    elseif exist('norm2mni','var') && norm2mni
        if ~exist('dseg','var'),dseg=defaults.segment;end
        priors=      dseg.estimate.priors;
        NRMtemplateweight=1;
        SEGtemplateweight=1;
        bmask=fullfile(spm('Dir'),'apriori','brainmask.mnc');	% always use brainmask with MNI template

    end
end
if exist('imgVols','var')
    for v=1:length(imgVols)
        imlist{v} = imgVols(v).fname;
        %[pth,nam,ext] = fileparts(imlist{v});
        imgtmp =dir(imlist{v});
        %imgtmp.name = [pth,'/',imgtmp.name];
        imglist(v)=imgtmp;
        % VW=spm_vol(imglist(v).name);
        % AnatVols(v) = VW;
    end
    AnatVols=imgVols;
    clear imgVols;

else
    if strcmpi(modality,'fluid')
        imlist   = spm_get(Inf,'*.img',{'Select images (to warp)'});
        for i=1:length(imlist)
            [pth,nam] = fileparts(imlist{i});
            imgtmp =dir(imlist{i});
            imgtmp.name = [pth,'/',imgtmp.name];
            imglist(i)=imgtmp;
            rotateImgs = 0;%spm_input('Adjust pitch on oblique images (0.5 radians)?','+1','m','Yes|No',[1 0], 1);

            VW=spm_vol(imglist(i).name);
            if rotateImgs
                VW=adjust_pitch(VW,0.5);
            end

            AnatVols(i) = VW;
            % str=['Jac :',nam];
        %    fltr=['*',nam(5:end),'*.IMAGE'];
            % WW  = spm_get([0 Inf],{fltr},{str});
            nmi=ls([pth,'/../JacNMI/*',nam(5:end-4),'*.img']);
            rnmi=ls([pth,'/../JacRNMI/*',nam(5:end-4),'*.img']);
            % WW=ls([]);
            if ~isempty(nmi)
                EPIVols{i,1}   = spm_vol(nmi);
            end
            if ~isempty(rnmi)
                EPIVols{i,2}   = spm_vol(rnmi);
            end
            clear nmi rnmi
        end
    elseif strcmpi(modality,'pet')
        imlist   = spm_get(Inf,'*.img',{'Select images (to warp)'});
        if ~exist('prefx','var')
            prefx='';
        end
        for i=1:length(imlist)
            [pth,nam] = fileparts(imlist{i});
            try
                uscore = findstr('_',nam);
                diagnosis = nam(1:uscore(1)-1);
                pnam = nam(uscore(1)+1:uscore(2)-1);
            end
            imgtmp =dir(imlist{i});
            imglist(i)=imgtmp;
            VW=spm_vol(fullfile(pth,imglist(i).name));
            AnatVols(i) = VW;
            if exist('vbmLevel','var') && vbmLevel==2
                EPIVols = '';
            else
                if strcmpi(diagnosis,'ct')
                    diagnosis='Controls';
                end
                pet = [pth,'/../../../',diagnosis,'/',prefx,pnam,'.img'];
                if exist(pet,'file') 
                    EPIVols{i,1}   = spm_vol(pet);
                else
                    disp('couldn''t find PET volume')
                end
                if exist('pnam','var')
                    nnam = pnam;
                else
                    nnam=nam;
                end
                str=['Select PET :',nnam];
                fltr=['*',nnam,'*.IMAGE'];
                WW  = spm_get([0 1] ,{fltr},{str});
                if ~isempty(WW)
                    EPIVols{i,1}   = spm_vol(WW{1,1});
                end
            end
        end
    end
end
save('MFPparams.mat')
% ______________________________________________________________________________________________%
% flip them if requested
for i=1:length(imlist)
    if (exist('EPIVols','var') && size(EPIVols,2)>0)
        for j =1:size(EPIVols,2)
            if exist('flipepi','var') && flipepi
                try
                    flipped=flipimages(EPIVols{i,j},'perm');
                catch
                    flipped=flipimages(EPIVols(i,j),'perm');
                end
                EPIVols(i,j)=spm_vol(flipped);
                clear flipped
            end
        end
        if exist('flipanat','var') && flipanat
            flipped = flipimages(AnatVols(i),'perm');
            AnatVols(i)=spm_vol(flipped{1});
            clear flipped
        end
    end
end

if (exist('norm2custom','var') || exist('norm2mni','var') || exist('coreg','var') || exist('coreg&&reslice','var') || exist('realign','var') )
    if ~exist('AnatVols','var')
        AnatVols   = spm_vol(spm_get(Inf,'*.IMAGE','Select raw (not normalized) images'));
    end
    if exist('rotateImgs','var') && rotateImgs
        AnatVols=adjust_pitch(AnatVols,0.5);
    end
end
% ______________________________________________________________________________________________%

% create a custom template
if exist('mktemplate','var') && mktemplate &&  exist('AnatVols','var')
    [ctemplate ,cpriors] = make_template_auto(AnatVols,MNItemplate,1,1,0,1,0,1,0,1,0,0);
    priors=cpriors;
end
%% ______________________________________________________________________________________________%
if exist('coreg','var') && coreg
    disp('coregistering ... please wait')
    p = coreg;
    %% FILL HERE: DONE (beta)
    % coregister mean EPI to Anatomical
    %   spm_coreg(VG,VF,params)
    %
    %function run_ui(flags)
    flags=defaults.coreg;
    %spm('FnBanner',mfilename,'2.10');
    [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Coregister');
    spm_help('!ContextHelp',mfilename);


    if numsubjects < 1
        spm_figure('Clear','Interactive');

    end
    if p == 1 || p == 3,
        for i = 1:numsubjects,
            if strcmpi(modality,'fmri'),
                mireg(i)    = struct('VG',[],'VF',[],'PO','');

                % select target(s) % AnatVols=spm_vol(AnatNames);
                if  exist('AnatVols','var')
                    mireg(i).VG=AnatVols(i);
                else
                    PG          = spm_get(1,'IMAGE', ['Target image, subj ' num2str(i)]);
                    mireg(i).VG = spm_vol(PG);
                end
                % select source(s)
                if  exist('meanimgs','var') && length(meanimgs)==numsubjects
                    mireg(i).VF =meanimgs{1}{i};
                    PF  = meanimgs{1}{i}.fname;%[SPM_data{i}, '/', meanimgs{1}{i}.fname];
                else
                    PF          = spm_get(1,'mean*IMAGE', ['Source image, subj ' num2str(i)]);
                    mireg(i).VF = spm_vol(PF);
                end
                if exist('epiNames','var') && exist('EPIVols','var')
                    scanspersess2 = length(epiNames)/sesspersubj; % scans per session
                    if  scanspersess2 ~= scanspersess; error('scans per session doesn''t match # of files'); end
                    for s=1:sesspersubj
                        for lk=(s-1)*scanspersess+1:s*scanspersess
                            jk=(i-1)*s*scanspersess+lk;
                            tmp=epiNames{jk};
                            if lk>1
                                PO=strvcat(PO,tmp);
                            else
                                PO(lk,:)=tmp;
                            end
                        end
                    end
                else
                    PO = spm_get(Inf,'IMAGE', ['Other images, subj ' num2str(i)]);
                end
                if isempty(PO),
                    mireg(i).PO = PF;
                else
                    mireg(i).PO = strvcat(PF,PO);
                end
            elseif strcmpi(modality,'pet'),
                %  error('PET not yet supported in ''coreg'' mode');
                %%%%%%%%%new%%%%%%%%%%%%5
                mireg(i)    = struct('VG',[],'VF',[],'PO','');

                % select target(s) % AnatVols=spm_vol(AnatNames);
                if  exist('AnatVols','var')
                    mireg(i).VG=AnatVols(i);
                else
                    PG          = spm_get(1,'IMAGE', ['Target image, subj ' num2str(i)]);
                    mireg(i).VG = spm_vol(PG);
                end
                % select source(s)
                if  exist('EPIVols','var') && (size(EPIVols,1)==numsubjects || size(EPIVols,2)==numsubjects)
                    
                    try
                        PF  = EPIVols{i,1}.fname;%  meanimgs{1}{i}.fname;%[SPM_data{i}, '/', meanimgs{1}{i}.fname];
                        %mireg(i).VF =EPIVols{i,1};
                    catch
                        PF  = EPIVols{i}{1}.fname;%
                        %mireg(i).VF =EPIVols{i,1};
                    end
                    mireg(i).VF = spm_vol(PF);
                elseif  exist('EPIVols','var') && size(EPIVols,1)==numsubjects
                
                else
                    
                    save
                    error('couldn''t find PET images')
%                    PF          = spm_get(1,'mean*IMAGE', ['Source image, subj ' num2str(i)]);
%                    mireg(i).VF = spm_vol(PF);
                end
                if strcmpi(modality,'fmri')
                    if exist('epiNames','var') && exist('EPIVols','var')
                        scanspersess2 = length(epiNames)/sesspersubj; % scans per session
                        if  scanspersess2 ~= scanspersess; error('scans per session doesn''t match # of files'); end
                        for s=1:sesspersubj
                            for lk=(s-1)*scanspersess+1:s*scanspersess
                                jk=(i-1)*s*scanspersess+lk;
                                tmp=epiNames{jk};
                                if lk>1
                                    PO=strvcat(PO,tmp);
                                else
                                    PO(lk,:)=tmp;
                                end
                            end
                        end
                    else
                        PO = spm_get(Inf,'IMAGE', ['Other images, subj ' num2str(i)]);
                    end
                else PO='';
                end
                if isempty(PO),
                    mireg(i).PO = PF;
                else
                    mireg(i).PO = strvcat(PF,PO);
                end
                %%%%%%%%%%new%%%%%%%%%%%%5
            end

            clear PF
            clear PO
        end
    end

    % For each subject, call the program to perform the registration.
    %-----------------------------------------------------------------------
    spm('Pointer','Watch')
%    save foo.mat
    for i=1:numsubjects,
        if p == 1 || p == 3,% p==1 always
            spm('FigName',['Coregister subj ' num2str(i)],Finter,CmdLine);
            x  = spm_coreg(mireg(i).VG, mireg(i).VF,flags.estimate);
            M  = inv(spm_matrix(x));
            MM = zeros(4,4,size(mireg(i).PO,1));
            for j=1:size(mireg(i).PO,1),
                MM(:,:,j) = spm_get_space(deblank(mireg(i).PO(j,:)));
            end;
            for j=1:size(mireg(i).PO,1),
                spm_get_space(deblank(mireg(i).PO(j,:)), M*MM(:,:,j));
            end;
        end;
        if p == 2 || p == 3,% p==1 always
            spm('FigName',['Reslice subj ' num2str(i)],Finter,CmdLine);
            fprintf('Reslicing Subject %d\n', i);
            P         = strvcat(mireg(i).VG.fname,mireg(i).PO);
            flg       = flags.write;
            flg.mean  = 0;
            flg.which = 1;
            flg.mean  = 0;
            spm_reslice(P,flg);
        end;
    end;
    spm('FigName','Coregister: done',Finter,CmdLine);
    spm('Pointer');
    if exist('EPIVols','var') && ~isempty(EPIVols)
        disp('reloading EPIVols')
        for ep=1:size(EPIVols,1)
            for ep2=1:size(EPIVols,2)
                try
                    foo=spm_vol(EPIVols{ep,ep2}.fname);
                catch
                    foo=spm_vol(EPIVols{ep,ep2}{1}.fname);
                end
                EPIVols2{ep,ep2}=foo;
%                 try
%                     EPIVols(ep,ep2)=foo;
%                 catch
%                     EPIVols{ep,ep2}=foo;
%                 end
                clear foo;
            end
        end
    end
    clear EPIVols
    EPIVols = EPIVols2;
    clear EPIVols2
end
% ______________________________________________________________________________________________%
% normalize Anatomical to template (MNI or custom)
% and optionally apply the same parameters to the EPI / pet / Jacobian images.
if exist('norm2custom','var') ||  exist('norm2mni','var')
   % if ~exist('dseg','var'),dseg=defaults.segment;end

    for i=1:length(AnatVols)
        [pth,nam] = fileparts(AnatVols(i).fname);
        matname0 = fullfile(pth,[nam '_sn.mat']);
        if exist(matname0,'file')
            matfiles{i}=matname0;
        end
    end
    if ~exist('matfiles','var')
        matfiles   = {};%spm_get([0 length(AnatVols)],'*_sn.mat',{'Select *_sn.mat files'});
    end
    if ~exist('EPIVols','var') && vbmLevel<2;
        for i=1:length(AnatVols)
            [pth,nam] = fileparts(AnatVols(i).fname);
            if strcmpi(modality,'fluid')
                str=['Select Jacobian img for ',nam];
            elseif strcmpi(modality,'pet')
                str=['Select PET img for ',nam];
            end
            fltr=['*',nam(1:4),'*.IMAGE'];
            WW  = spm_get([0 1],{fltr},{str});
            if ~isempty(WW)
                EPIVols(i,:)   = spm_vol(WW);
            end
        end
    end
    if ~exist('EPIVols','var')
        EPIVols=[];
    end
    % dseg.estimate.priors=priors;
    % we should have the template && priors selected by now (I hope!!!)
    %% FILL HERE: DONE!! (beta)
    if ~exist('voxsize','var')
        if strcmpi(modality,'pet')
            voxsize='';
        elseif strcmpi(modality,'fluid')
            voxsize=.859;
        end
    end
    if strcmpi(modality,'pet')
        max_seg=3;
        norm_fluid_auto(AnatVols,matfiles,EPIVols,ctemplate,priors,1,1,...
        optimal,0,NRMtemplateweight,0,...
        SEGtemplateweight,0,max_seg,1, ...
        1,1,bmask,voxsize);
    elseif strcmpi(modality,'fluid')
        max_seg=3;
        norm_fluid_auto(AnatVols,matfiles,EPIVols,ctemplate,priors,1,1,...
        optimal,0,NRMtemplateweight,0,...
        SEGtemplateweight,0,max_seg,1, ...
        1,1,bmask,voxsize);
    end
    
    epj=0;
    for ep=1:length(AnatVols)
        for ej=1:size(EPIVols,2)
            epj=epj+1;
            [Epth,Enam,Eext]=fileparts(EPIVols{ep,ej}.fname);
            foo=fullfile(Epth,['w_' Enam Eext]);
            epiNames{epj}=foo;
            clear foo;
        end
    end
end
if exist('smooth','var') && smooth==1
    if exist('vbmLevel','var') && vbmLevel
        disp('Smoothing GM volumes ... please wait')
        for i=1:length(AnatVols)
            str   = sprintf('Smoothing Image %3d/%-3d ',i,length(AnatVols));
            fprintf('\r%-40s: %20s',str,' ')
            [pth,nam,ext] = fileparts(AnatVols(i).fname);
            GM{i} = fullfile(pth, ['mGw_', nam ext]);
            smoothGM{i} = fullfile(pth, ['s', num2str(fwhm(1)),'mGw_', nam ext]);
            spm_smooth(GM{i}, smoothGM{i},fwhm);
        end
    end
    if exist('epiNmaes','var')
        disp('Smoothing EPI volumes ... please wait')
        for i=1:length(epiNames)
            str   = sprintf('Smoothing Image %3d/%-3d ',i,length(epiNames));
            fprintf('\r%-40s: %20s',str,' ')
            [pth,nam,ext] = fileparts(epiNames{i});
            newname{i}=fullfile(pth, ['s',num2str(fwhm(1)), nam ext]);
            delname{i}=fullfile(pth, [nam ext]);
            spm_smooth(epiNames{i}, newname{i},fwhm);

        end
        if exist('delname','var')
            % mls_cleanup(delname);
            clear delname
        end
        %  delname={};
        if exist('newname','var')
            delname = newname;
        end
        fprintf('%s%15s',repmat(sprintf('\b'),1,15),'... done',sprintf('\n'))
        %-#
        clear epiNames;
        epiNames=newname;
        clear newname
    end
end
if exist('stats','var') && stats==1
    disp('generating stats... please wait')
    % ______________________________________________________________________________________________%
    %% FILL HERE: DONE!! (pre-beta)
    %% generate SPM model and contrasts for each subject/session.
    %% call mls_batch.m

    if numsubjects==1;
        if ~exist('SPM_data','var')
            [p1,n1] = fileparts(imlist{end});
            SPM_data{1} = p1;
        end
        afni_dir=[SPM_data{1},'/../'];
        Bnames = load([afni_dir,'BRIK']);
    end
    clear sessname;
    for s=1:sesspersubj

        if numsubjects==1;
            tmpnam = Bnames.BRIK(s+1);
            tmpnam2 = tmpnam.task;
            sessname{s}=tmpnam2;
        else
            sessname{s}=['session', num2str(s)];
        end
    end
    mls_batch(numsubjects, sesspersubj, sessname, scanspersess, epiNames);
    %%
    if exist('delname','var') 
        %mls_cleanup(delname);
    end

end
% ______________________________________________________________________________________________%

% ______________________________________________________________________________________________%

% check registration
if exist('checkreg','var') && checkreg
    spm_check_registration;
end