global defaults;
defaults=spm_get_defaults;
flags = defaults.coreg;


    par;
for sb =1:PAR.nsubs % for each subject 
    % get mean in this directory
  %PG - Tar(G)et image, NEVER CHANGED
  %PF - Source image, transformed to match PG
  %PO - (O)ther images, originally realigned to PF and transformed again to PF

  % TARGET
  % get (NOT skull stripped structural from) Structurals
 
        PG=spm_select('FPList', PAR.structdir{sb},  ['^' PAR.structprefs '.*\.nii$'] );
        if isempty(PG)
            PG=spm_select('FPList', PAR.structdir{sb}, ['^' PAR.structprefs '.*\.img$'] );
            
        end
        PG=spm_select('FPList', PAR.structdir{sb}, ...
            ['^t1_noskull.nii$' ]);
        
    for c=1:PAR.ncond
        
%            Psource=spm_select('FPList', PAR.condirs{sb,c}, ['^mean' PAR.subjects{sb} '.*img$']);
           Psource=spm_select('FPList', PAR.condirs{sb,c}, ['^EPI_noskull.nii']);
            
        % get files in this directory
        PO=[];
        Ptmp=spm_select('EXTFPList', PAR.condirs{sb,c}, ['^flt_r.*\.nii'], 1:300);

            if isempty(Ptmp)
              fprintf('!!!!!! No images found for %s and condition %d\n',PAR.subjects{sb},c);
              continue;
            end
          PO=strvcat(PO,Ptmp);
          Ptmp=spm_select('ExtFPList', char(PAR.condirs{sb,c}),  ['^' PAR.fmriprefix{c} '\w*\.nii$'], 1:1000 );
          PO=strvcat(PO,Ptmp);
          Ptmp=spm_select('ExtFPList', char(PAR.condirs{sb,c}), ['^ra' PAR.fmriprefix{c} '\w*\.nii$'], 1:1000);
          if isempty(Ptmp)
            Ptmp=spm_select('FPList', char(PAR.condirs{sb,c}), ['^ra' PAR.fmriprefix{c} '\w*\.img$']);
          end
          PO=strvcat(PO,Ptmp);
          Ptmp=spm_select('EXTFPList', PAR.condirs{sb,c}, ['^sflt_r.*\.nii'], 1:1000);
          PO=strvcat(PO,Ptmp);
          
          
          rbim_dir = fullfile(PAR.root,PAR.subjects{sb}, PAR.rbimdir);
            
            P=strvcat(P, spm_select('FPList', rbim_dir, sprintf('.^%s_BEN_.*.nii',PAR.subjects{sb})));

        
            %PO = PF; --> this if there are no 'other' images
            if isempty(PO) 
                PO=Psource;
            else
                PO = strvcat(Psource,PO);
            end
            [output]=ASLtbx_spmcoreg(PG, Psource, PO);
       
    
  end
end