% All rights reserved.
% Ze Wang @ TRC, CFN, Upenn 2004
%
% Batch calculation for the perfusion signals.
orgpwd=pwd;
for groupnum=1
    par;
for sb = 1:length(PAR.subjects) % for each subject
    clear P;
    fprintf('Generate mask image for #%g %s... %g subjects left...\n',sb,PAR.subjects{sb},length(PAR.subjects)-sb)
    for b = 1:PAR.nsess(sb) % for each session
        P=[];
        for c=1:PAR.ncond
        % creating a mask image for removing background
        if ~isempty(PAR.condirs{sb,b,c})
            P = spm_select('FPList',PAR.condirs{sb,b,c},   ['^mean.*\.nii$']);
            if isempty(P)
                P = spm_select('FPList',PAR.condirs{sb,b,c},   ['^mean.*\.img$']);
            end
            P=P(1,:);
            cd(PAR.condirs{sb,b,c});
           !rm -f mask*
           if strcmp(P,'/')==1, fprintf('No mean images for subject %s!\n',PAR.condirs{sb,b,c});continue;end
           eval(['!bet ' P  ' ' fullfile(spm_str_manip(P,'h'),'mask.nii') ' -m -f 0.35']);

           eval(['!gunzip ' fullfile(PAR.condirs{sb,b,c}, ['*mask*.nii.gz']) ]);
           
           !mv mask_mask.nii mask_bet.nii
           !mv mask.nii EPI_noskull.nii
           v=spm_vol(P);
            vm=spm_vol('mask_bet.nii');
            dat=spm_read_vols(vm);
            v.fname=vm.fname;
            v=spm_write_vol(v,dat);
            vm=spm_vol('EPI_noskull.nii');
            dat=spm_read_vols(vm);
            v.fname=vm.fname;
            v=spm_write_vol(v,dat);
       
           
        end
        end
    end
end
end