function dummy = refreshpz(Editor,event,varargin)
%REFRESHPZ  Refreshes plot after compensator update.

%   Author(s): P. Gahinet
%   Copyright 1986-2000 The MathWorks, Inc. 
%   $Revision: 1.11 $  $Date: 2000/08/15 20:14:57 $

% REVISIT
dummy = [];

persistent PZListener

nGains = 25;  % Number of gain values while dragging

% Process events
switch event 
case 'init'
   % Initialization for dynamic gain update (drag).
   PZGroup = varargin{1};    % Modified PZGROUP

   % Switch editor's RefreshMode to quick
   Editor.RefreshMode = 'quick';
   
   % Use NGAINS gain values for root locus refreshing
   MinGain = log10(Editor.LocusGains(2));
   MaxGain = log10(Editor.LocusGains(end-2));
   UpdateGains = [Editor.LocusGains(1) , ...
         logspace(MinGain,max(MinGain+1,MaxGain),nGains) , ...
         Editor.LocusGains(end-1:end)];

    % Install listener on PZGROUP data
   PZListener = handle.listener(PZGroup,'PZDataChanged',...
       {@LocalUpdatePlot Editor UpdateGains});

case 'finish'
   % Clean up after dynamic gain update (drag)
   % Return editor's RefreshMode to normal
   Editor.RefreshMode = 'normal';
   
   % Delete listener
   delete(PZListener);
   PZListener = [];
end



%-------------------------Local Functions-------------------------

%%%%%%%%%%%%%%%%%%%%%%%
%%% LocalUpdatePlot %%%
%%%%%%%%%%%%%%%%%%%%%%%
function LocalUpdatePlot(PZGroup,event,Editor,UpdateGains)
% Update plot
HG = Editor.HG;
LoopData = Editor.LoopData;

% Identify moved PZVIEW group (corresponding to PZGROUP)
MovedGroup = HG.Compensator(LoopData.Compensator.PZGroup==PZGroup);

% Update position of moved pole/zero
MovedHandles = [MovedGroup.Zero;MovedGroup.Pole];
NewValues = [PZGroup.Zero;PZGroup.Pole];
set(MovedHandles,{'Xdata'},num2cell(real(NewValues),2),...
    {'Ydata'},num2cell(imag(NewValues),2))

% Get uptodate open-loop model
NormOpenLoop = LoopData.OpenLoop;
GainMag = abs(getgain(LoopData));

% Add gain values where branches cross (for more smoothness)
LocusGains = unique([UpdateGains,LocalCrossGains(NormOpenLoop)]);

% Update locus data and closed-loop locations
Roots = fastrloc(NormOpenLoop,[LocusGains,GainMag]);
Editor.LocusRoots = Roots(:,1:end-1);
Editor.ClosedPoles = Roots(:,end);

% Update plot
if ~isempty(Roots)
    set(HG.Locus,{'Xdata'},num2cell(real(Editor.LocusRoots),2),...
        {'Ydata'},num2cell(imag(Editor.LocusRoots),2))
    set(HG.ClosedLoop,{'Xdata'},num2cell(real(Editor.ClosedPoles)))
    set(HG.ClosedLoop,{'Ydata'},num2cell(imag(Editor.ClosedPoles)))
end



%%%%%%%%%%%%%%%%%%%%%%%
%%% LocalCrossGains %%%
%%%%%%%%%%%%%%%%%%%%%%%
function gmult = LocalCrossGains(NormOpenLoop)
% Computes gain crossings

[z,p,k] = zpkdata(NormOpenLoop,'v');
gmult = rlocmult(z,p,k);


   

