% 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});
            v=spm_vol(P);
            dat=spm_read_vols(v);
            dat(isnan(dat))=0;
            mask=dat>0.2*max(dat(:));
            ndat=zeros(size(dat));
            ndat(mask)=dat(mask);
           
           
            v.fname='mask_bet.nii';
            v.dt(1)=4;
            v=spm_write_vol(v,mask);
            v.fname='EPI_noskull.nii';
            v.dt(1)=16;
            v=spm_write_vol(v, ndat);
                  
           
        end
        end
    end
end
end