% Toolbox for batch processing ASL perfusion based fMRI data.
% All rights reserved.
% Ze Wang @ TRC, CFN, Upenn 2004

    par;
    orgpwd=pwd;
% get the subdirectories in the main directory
clear matlabbatch
for sb =1:length(PAR.subjects) % for each subject 
    fprintf('smoothing subject %u  %s.........',sb,PAR.subjects{sb})
    %go get the sessions
        %now get all images to smooth!
        %prepare directory
        %P=[];
        for c=1:PAR.ncond
            if isempty(PAR.condirs{sb,c}), continue; end
            cd(PAR.condirs{sb,c});
            delete sflt*.nii           
            %eval(['!rm -f '  PAR.condirs{sb,c} '/sflt*']);
%           P=spm_select('ExtFPList', PAR.asldir{sb,ses,c}, ['^flt_r.*\.nii$'],1:600);
                    P=spm_select('ExtFPList', PAR.condirs{sb,c}, ['^flt_r.*\.nii$'],1:1000);

            fprintf('      %u images \n',size(P,1))
            %put files in spm volumes:
            %P = spm_get('Files', dir_func,...
		    %    ['w' PAR.conprefs{c} '*img']);
            %take image per image smooth
            for im=1:size(P,1)
               %this is actual image
               Pim=P(im,:);
               [pth,nam,ext] = fileparts(P(im,:));
                t = find(ext==',');
                n = [1 1];
               if ~isempty(t),
                   % to speed up, output each volume into an separate image
                   % file
                    Qim   = fullfile(pth,['s' nam '_' num2str(im,'%.3d') '.nii,' num2str(1)]);
               else
                    Qim=fullfile(pth,['s' spm_str_manip(Pim,'dt')]);
               end
               %now call spm_smooth with kernel defined at PAR
               spm_smooth(Pim,Qim,PAR.FWHM);
            end
            Qf=spm_select('FPList',PAR.condirs{sb,c},['^sflt_rimages_.*\.nii$']);
            if size(Qf,1)~=size(P,1) fprintf('# of smoothed images are not the same as the # of images to be smoothed!\n');end
           clear Qfname;
            for kk=1:size(Qf,1)
                   
               Qfname{kk,1} = Qf(kk,:);
            end
            clear matlabbatch;
            
            matlabbatch{1}.spm.util.cat.vols = Qfname;
            [pth,nam,ext] = fileparts(Qf(1,:));
            filename=fullfile(pth,[nam(1:end-4)  '4D.nii']);
            matlabbatch{1}.spm.util.cat.name = filename;
            matlabbatch{1}.spm.util.cat.dtype = 4;
            cfg_util('run', matlabbatch);  
            for im=1:size(Qf,1)
			delete(Qf(im,:));	
                %eval(['!rm -f ' Qf(im,:)]);
            end
            
           
        end % end for c
       cd(orgpwd);
end  % end for sb

