function [ph_uw,msd] = CtSent_InterpPUgrid(path,phsbas)
%CtSent_InterpPUgrid unwrap PS/DS from unwrapped gridded ifgs 
%
%   Andy Hooper, June 2007
%   Zhangfeng Ma, April 2021
% ============================================================
% 03/2012 AH: Allow for all zero wrapped phase values
% 03/2012 AH: Allow for non-complex wrapped phase
% ============================================================

fprintf('Unwrapping from grid...\n')
oldFolder = cd(path);
uw=load('phwgrid','nzix','n_ps','grid_ij','ph');
uu=load('phugrid'); 
[~] = cd(oldFolder);
[n_ps,n_ifg]=size(phsbas);
gridix=zeros(size(uw.nzix));
gridix(uw.nzix)=[1:uw.n_ps];
    
ph_uw=zeros(n_ps,n_ifg,'single');
phsbas = exp(1i*phsbas);
for i=1:n_ps
    ix=gridix(uw.grid_ij(i,1),uw.grid_ij(i,2));
    if ix==0
        ph_uw(i,:)=nan; % wrapped phase values were zero
    else
        ph_uw_pix=uu.ph_uw(ix,:);
        if isreal(uw.ph)
          ph_uw(i,:)=ph_uw_pix+angle(exp(1i*(phsbas(i,:)-ph_uw_pix)));
        else
          ph_uw(i,:)=ph_uw_pix+angle(phsbas(i,:).*exp(-1i*ph_uw_pix));
        end
    end
end
msd=uu.msd;
oldFolder = cd(path);
save('phuw.mat','ph_uw','msd','-v7.3');
[~] = cd(oldFolder);
end

