% ASLtbx_resetimgorg.m
% function for reseting the mat file or the mat matrix so the origin will
% be in the center of the image box. Note: another function may be needed
% for the non-axially acquired image especially when it was converted into
% Nifti format using non-SPM software. Display the image to check that.
% Ze Wang. All rights reserved. Upenn
function ASLtbx_resetimgorg(P)
filenum=size(P,1);
v=spm_vol(P);
[pth,nam,ext,num] = spm_fileparts(P(1,:));
for i=1:size(v,1)
    if filenum==1
        if size(v,1)>1
            imgfilename=[fullfile(pth, nam) ext ',i'];
        else
            imgfilename=P;
        end
    else
        imgfilename=P(i,:);
    end
    V    = v(i);
    M    = V.mat;
    vox  = sqrt(sum(M(1:3,1:3).^2));
    if det(M(1:3,1:3))<0, vox(1) = -vox(1); end;
    orig = (V.dim(1:3)+1)/2;
    off  = -vox.*orig;
    M    = [vox(1)  0      0      off(1)
        0      vox(2) 0      off(2)
        0      0      vox(3) off(3)
        0      0      0      1       ];
    spm_get_space(imgfilename,M);
end