function moveit2skewview(h, doX, doY, callback, finalcallback);
%MOVEIT   Move a graphical object in 2-D.
%   Move an object in 2-D. Modify this function to add more functionality
%   when e.g. the object is dropped. It is not perfect but could perhaps
%   inspire some people to do better stuff.
%
%   % Example:
%   t = 0:2*pi/20:2*pi;
%   X = 3 + sin(t); Y = 2 + cos(t); Z = X*0;
%   h = patch(X,Y,Z,'g')
%   axis([-10 10 -10 10]);
%   moveit2(h);
%
% Author: Anders Brun, anders@cb.uu.se
%

% UserData strategy:
%   the actual object being moved holds the flags and callback
%   gcf/gcbf - holds data on callback, including which object is
%   being moved


if nargin < 2; doX = 1; end
if nargin < 3; doY = 1; end
if nargin < 4; callback = []; end
if nargin < 5; finalcallback = []; end

% Unpack gui object
userdata = get(h,'UserData');

% Store parameters
userdata.doX = doX;
userdata.doY = doY;
userdata.callback = callback;
userdata.finalcallback = finalcallback;

% Make a fresh figure window
set(h,'ButtonDownFcn',@startmovit);

% Store gui object at object level
set(h,'UserData',userdata);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function startmovit(src,evnt)
% Unpack gui object
userdata = get(src,'UserData');

% Remove mouse pointer
set(gcbf,'PointerShapeCData',nan(16,16));
set(gcbf,'Pointer','custom');

% Set callbacks
thisfig = gcbf();
set(thisfig,'WindowButtonMotionFcn',@movit);
set(thisfig,'WindowButtonUpFcn',@stopmovit);
figuserdata.src = src;

% Store starting point of the object
figuserdata.startpoint = get(gca,'CurrentPoint');
figuserdata.X = get(src,'XData');
figuserdata.Y = get(src,'YData');
figuserdata.doX = userdata.doX;
figuserdata.doY = userdata.doY;
figuserdata.callback = userdata.callback;
set(gcbf, 'UserData', figuserdata);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function movit(src,evnt)
% Unpack gui object
thisfig = gcbf();
figuserdata = get(gcbf,'UserData');
userdata = get(figuserdata.src,'UserData');

% Do "smart" positioning of the object, relative to starting point...
pos = get(gca,'CurrentPoint')-figuserdata.startpoint;
XYData = [figuserdata.X, figuserdata.Y];
outpt = XYData + [userdata.doX * pos(1,1), userdata.doY * pos(1,2)];

if userdata.doX; set(figuserdata.src,'XData', outpt(1)); end
if userdata.doY; set(figuserdata.src,'YData', outpt(2)); end

if ~isempty(userdata.callback); userdata.callback(outpt); end

drawnow;

% Store gui object
%set(gcbf,'UserData',gui);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function stopmovit(src,evnt)

% Clean up the evidence ...

thisfig = gcbf();
figuserdata = get(thisfig,'UserData');
userdata = get(figuserdata.src,'UserData');

if ~isempty(userdata.finalcallback); userdata.finalcallback(); end

set(gcbf,'Pointer','arrow');
set(src,'WindowButtonUpFcn','');
set(src,'WindowButtonMotionFcn','');
drawnow;
%set(figuserdata.src,'UserData','');
set(gcbf,'UserData',[]);


