function relocptr(action,varargin)
%RELOCPTR  Adjust pointer position when changing axes limits.
%
%   See also SISOTOOL

%   Author(s): P. Gahinet
%   Copyright 1986-2000 The MathWorks, Inc. 
%   $Revision: 1.6 $  $Date: 2000/06/14 19:59:12 $

persistent Transform isLogX isLogY

switch action(1)
case 'i'  % init
   % Compute the transformation from norm. axis position to screen position
   Axes = varargin{1};  % Axes wrt which the new location is defined
   Transform = LocalAxis2Screen(Axes);   
   isLogX = strcmp(get(Axes,'Xscale'),'log');
   isLogY = strcmp(get(Axes,'Yscale'),'log');
   
case 'm'  % move pointer
   % Move pointer
   NewX = varargin{1};    % Target X position in axis coordinates
   NewY = varargin{2};    % Target Y position in axis coordinates
   Xlim = varargin{3}(1:2);  % X limits
   Ylim = varargin{3}(3:4);  % Y limits
   
   % Compute normalized axis coordinates
   if isLogX,
       NormX = (log2(NewX) - log2(Xlim(1))) / (log2(Xlim(2))-log2(Xlim(1)));
   else
       NormX = (NewX-Xlim(1)) / (Xlim(2)-Xlim(1));
   end
   if isLogY,
       NormY = (log2(NewY)-log2(Ylim(1))) / (log2(Ylim(2))-log2(Ylim(1)));
   else
       NormY = (NewY-Ylim(1)) / (Ylim(2)-Ylim(1));
   end
   
   % Reset pointer location.
   % RE: When pointer is reset in each cycle, use dead zone to prevent drifting
   DeadZone = 0.02;
   NewLoc = Transform(1:2) + Transform(3:4) .* [NormX NormY];
   if any(abs(get(0,'PointerLocation')-NewLoc) > DeadZone*Transform(3:4))
      drawnow
      set(0,'PointerLocation',NewLoc)
   end
   
end


%----------------- Local functions -----------------


%%%%%%%%%%%%%%%%%%%%
% LocalAxis2Screen %
%%%%%%%%%%%%%%%%%%%%
function T = LocalAxis2Screen(ax)
% Axis to screen coordinate transformation.
%
%   T = AXIS2SCREEN(AX) computes a coordinate transformation 
%       T = [xo yo rx ry] 
%   that relates the normalized axes coordinates [xa;ya] of a 
%   given point to its screen coordinate [xs;ys] (in the root 
%   units) by
%       xs = xo + rx * xa
%       ys = yo + ry * ya
%
%   See also SISOTOOL.

% Get axes normalized position in figure
AxisPos = LocalGetNormPos(ax);

% Get figure's normalized position in screen
FigPos = LocalGetNormPos(get(ax,'Parent'));

% Transformation norm. axis coord -> norm. fig. coord.
T = AxisPos;

% Transformation norm. axis coord -> norm. screen coord.
T(1:2) = FigPos(1:2) + FigPos(3:4) .* T(1:2);
T(3:4) = FigPos(3:4) .* T(3:4);

% Transform to screen units
ScreenSize = get(0,'ScreenSize');
T(1:2) = ScreenSize(1:2) + ScreenSize(3:4) .* T(1:2);
T(3:4) = ScreenSize(3:4) .* T(3:4);


%%%%%%%%%%%%%%%%%%%
% LocalGetNormPos %
%%%%%%%%%%%%%%%%%%%
function Pos = LocalGetNormPos(Handle)
%   Determine if mag. plot is slipping out of focus.

Units = get(Handle,'Units');
if strcmp(Units,'normalized')
   Pos = get(Handle,'Position');
else
   set(Handle,'Units','normalized')
   Pos = get(Handle,'Position');
   set(Handle,'Units',Units)
end
