function Hand = handZPK(Hand, handles)
% handZPK
%   Change pole/zero for eraser

%   Project: IMPACT
%   Title of Code: handZPK
%   Relevant additional documentation:
%   Developer: Carlos Gonzalez
%   External Dependencies: NA
%
%   Disclaimer
%   CAUTION: It is strongly recommended that changes to this code
%   should be avoided without first consulting with authors.
 

Hand.zpk = '';
C = handles.C;
ptX = Hand.prevPoint(1);
ptY = Hand.prevPoint(2);
Data = handles.Data;
vecX = Data.zpX;
[z, p, k] = zpkdata(C);
z = z{1}; p = p{1};
Hand.z = z;
Hand.p = p;
Hand.k = k;

hAx = gca;
hMag = handles.hMag;
if hAx==hMag(1)
    vecY = 20*log10(Data.zpMag);
else vecY = Data.zpPhase;
end
xLim = get(gca, 'XLim');
yLim = get(gca, 'YLim');

dist = abs(ptX - vecX);
[temp, ind] = sort(dist);
vecX = vecX(ind);
vecY = vecY(ind);

% check if rz, cz, rp, cp
zpClick = 0;
for m = 1:numel(vecX)
    if checkRange(ptX, ptY, vecX(m), vecY(m), xLim, yLim)
        valX = vecX(m);
        zpClick = 1;
        break;
    end
end
Hand.zpkInd = [];
if zpClick % withine eraser range
    ind = getXY(valX, z);
    if ~isempty(ind)
        if isreal(z(ind))
            Hand.zpk = 'rz';
        else Hand.zpk = 'cz';
        end
    else
        ind = getXY(valX, p);
        if isreal(p(ind))
            Hand.zpk = 'rp';
        else
            Hand.zpk = 'cp';
        end
    end
    Hand.zpkInd = ind;
end

% check gain
if ~strcmp(Hand.zpk, '')
    return;
end
Data = handles.Data;
if hAx==hMag(1)
    vecY = get(hMag(2), 'YData');
else
    return;
end
vecX = Data.w;

% 
for m = 1:numel(vecX)
    if checkRange(ptX, ptY, vecX(m), vecY(m), xLim, yLim)
        Hand.zpk = 'k'; 
        break;
    end
end
