% batch segmentation using the new segmentation approach in spm8
% Toolbox for batch processing ASL perfusion based fMRI data.
% All rights reserved.
% Ze Wang @ TRC, CFN, Upenn 2004
%
%segment spm
% apply segm to already normalized images


for groupnum=1:length(PAR.groupname)
    par;
    
    fprintf('%s\n',repmat(sprintf('-'),1,30))
    disp('Segmenting T1 images for all subjects, it takes a while....');
    fprintf('%s\n',repmat(sprintf('-'),1,30))


    if strcmp(spm('ver',[],1),'SPM8')==0
        close all;
        addpath /pkg/spm8 -begin
    end
    
        
    for sb=1:PAR.nsubs  %
        for nses=1:PAR.nsess(sb)
            str   = sprintf('sub: #%3d/%3d: %-5s, session:  #%3d/%3d\n',sb,PAR.nsubs,PAR.subjects{sb},nses,PAR.nsess(sb) );
            fprintf('\r%-40s  %30s\n',str,' ')
             P =spm_select('FPList',PAR.structdir{sb,nses},              ['^' PAR.structprefs '.*\.nii$']);
             if isempty(P)
                P=spm_select('FPList', char(PAR.structdir{sb}), ['^' PAR.structprefs '.*\.img$']);
                if isempty(P)
                    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n NO struct file\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
                    continue;
                end
             end;
             ASLtbx_spmnsegment(P);   % this requires SPM12. The output will be c1* c2* c3* images and the spatial normalization transfer file y_
        end
    end
   
end
