function [x,y] = getline(fig,s)
%GETLINE Track mouse movement with rubberbanded line.
%	[X,Y] = GETLINE(FIG) tracks the movement of a mouse in
%	the figure FIG.  The mouse movement is tracked with a 
%	rubberbanded polyline.  Returns the selected line endpoints,
%	X and Y in axes coordinates. Left mouse button adds a new
%	point to the polygon, right mouse button (shift-click
%	on the Macintosh) or <cr> finishes the polygon.
%	XY = GETLINE(FIG) returns the data coordinates in a 2-column
%	matrix.
%
%	See also GETRECT.

%	Clay M. Thompson 1-28-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.13 $  $Date: 1993/08/10 02:20:04 $

% How this works: This function waits for buttonpresses.  After
% a button press the current point is saved, and a call-back is
% installed as a button motion function to draw a rubber-banded 
% dashed line from this saved point to the current point.  When
% the button is pressed again, the current point is saved and the
% process is started all over.  This continues until a <cr> or
% right mouse button is pressed.

global Pt1 Pt2 hline fig ax

if nargin<1, fig = gcf; end

if nargin==2, % Process call-backs
  if strcmp(s,'motion'),
    if length(hline)>0,
      Pt2 = get(ax,'CurrentPoint'); Pt2 = Pt2(1,1:2);
      set(hline,'Xdata',[Pt1(1) Pt2(1)],'Ydata',[Pt1(2) Pt2(2)])
    end
  else
    error('Invalid call-back');
  end
  return
end

figure(fig), ax = gca;
c = [.9 .9 .91];

% Create an invisible line to preallocate the xor line color.
handles = line(min(get(ax,'xlim'))*ones(1,2),min(get(ax,'ylim'))*ones(1,2),...
               'eraseMode','xor','linestyle','--','Color',c,'visible','off');

if any(get(ax,'view')~=[0 90]), error('GETLINE works only on 2-D plots'); end
curse = get(gcf,'pointer');
set(gcf,'pointer','crosshair');

btndown = get(gcf,'windowbuttondownfcn');
btnup = get(gcf,'windowbuttonupfcn');
btnmotion = get(gcf,'windowbuttonmotionfcn');
set(gcf,'windowbuttondownfcn','','windowbuttonupfcn','')

Pts = []; handles = []; done = 0; first = 1;
while ~done
  done = waitforbuttonpress;
  if gcf==fig,
    axes(ax) % Protect against user clicking in another axis
    Pt1 = get(ax,'CurrentPoint'); 
    Pt1 = Pt1(1,1:2);
    Pts = [Pts;Pt1];
    if ~strcmp(get(fig,'selectiontype'),'normal'), 
      done = 1; 
      hline = [];
    else
      hline = line(Pt1(1)*ones(1,2),Pt1(2)*ones(1,2),'eraseMode','xor', ...
               'linestyle','--','Color',c);
      if first,
        set(fig,'WindowButtonMotionFcn','getline(gcf,''motion'')')
        first = 0;
      end
      handles = [handles hline];
    end
    drawnow
  end
end
delete(handles)
set(fig,'pointer',curse);
clear global Pt1 Pt2 hline fig ax
set(gcf,'windowbuttondownfcn',btndown,'windowbuttonupfcn',btnup, ...
        'windowbuttonmotionfcn',btnmotion)
if nargout < 2, x = Pts; return, end
if ~isempty(Pts), x = Pts(:,1); y = Pts(:,2); else x = []; y = []; end


