function MatDefAtl = LDDMMInterp3Atl2Pt(Atl, Hx, Hy, Hz, resample, perm)


% This function interpolates the images using the LDDMM generated
% deformation fields that are mapping the atlas into the coordinates of patient.
% The deformation fileds are already extracted through
% the "GetTransformLDDMM" matlab function. The input image (Atl) should
% ordered correctly along the x-y axis (rows and columns) otherwise use
% perm to flip the rows and columns.
% 
% Atl: Atlas image - raw file
% Hx, Hy,Hz: matlab extracted 3D deformation files (from Atlas to Patient)
% perm: flip along the row and column (0 or 1) 
% resample: string expressing the type of interpolation ('linear', 'cubic', 'spline');
% MatDefAtl: Matlab interpolated deformed atlas image (equivalent to patient)
% 
% ICM Oct. 2006


if (perm ~= 0) && (perm ~= 1)
    
    error('Permutaion value should be either 0 or 1.');
    
end    
    


if ~strcmp(resample,'linear') && ~strcmp(resample,'cubic') && ~strcmp(resample,'spline') 
    
    error('Interploation method should be linear, cubic, or spline.');
    
end



if perm == 1
    
    Atl = permute(Atl,[2 1 3]);
    
end


[row, col, sl] = size(Atl);

[X,Y,Z] = meshgrid(0:row - 1,0:col - 1,0:sl - 1);

MatDefAtl = interp3(X,Y,Z, Atl, Hx, Hy, Hz, resample);