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


% load spm defaults
global defaults;
defaults=spm_get_defaults;
% Get realignment defaults
defs = defaults.realign;

clear P;
% dirnames, 
% get the subdirectories in the main directory
fg=spm_figure('FindWin','Graphics');
if isempty(fg)
    spm_figure('Create','Graphics','Graphics','on')
else
    set(fg,'Visible','on');
    spm_figure('Clear',fg);
end
clear s sb c b
for groupnum=1
    par;
for sb =1:length(PAR.subjects) % for each subject 
    clear P;
   
    fprintf('Realigning subject #%g''s data...%g subjects left...\n',sb,length(PAR.subjects)-sb)
    for b = 1:PAR.nsess(sb)
 
        for c=1:ncond 
            
            fprintf('%s session%d Condition %g ......',PAR.subjects{sb},b,c);

            P=spm_select('ExtFPList', PAR.condirs{sb, c},   ['^a' PAR.fmriprefix{c} '\w*\.nii$'],1:1000);
            if isempty(P)
                P=spm_select('FPList', char(PAR.condirs{sb,c}),  ['^a' PAR.fmriprefix{c} '\w*\.img$']);
                if isempty(P)
                    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n NO epi file\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
                    continue;
                end
            end;
         realignfig=fullfile(PAR.condirs{sb,c},'realignfig.jpg');

        defs.printstr=['print -djpeg -painters -append -noui ' realignfig];
        reaFlags = struct(...
            'quality', defs.estimate.quality,...  % estimation quality
            'fwhm', 5,...                         % smooth before calculation
            'rtm', 1,...                          % whether to realign to mean 
            'PW',''...                            %
            );
        % Flags to pass to routine to create resliced images
        % (spm_reslice)
        resFlags = struct(...
            'interp', 1,...                       % trilinear interpolation
            'wrap', defs.write.wrap,...           % wrapping info (ignore...)
            'mask', defs.write.mask,...           % masking (see spm_reslice)
            'which',2,...                         % write reslice time series for later use
            'mean',1);                            % do write mean image

         % Run the realignment
        spm_realign(P, reaFlags);
        eval(defs.printstr);
        % Run the reslicing
        spm_reslice(P, resFlags);
    
        end
    end
end
end
clear res* s P b c fg
