function drawlines(h,event)
%DRAWLINES  Draw segmented lines on top of an image
%
% example usage:
%  h = image(data);
%  p = get(h,'parent');
%  drawlines(p)
%
% $Id: drawlines.m,v 1.2 2002/07/09 19:03:43 tobin Exp tobin $

r = get(gca,'parent');

if nargin == 1,
   
   state.UserData = get(h,'UserData');
   state.mode = 'idle';
   
   set(r,'WindowButtonDownFcn','drawlines(gca,''down'')');   
   set(h,'UserData',state);
   
   return;
end

state = get(h,'UserData');

cp = get(h,'currentpoint');

f = gcf;  % figure

button = get(f,'SelectionType'); 

point = [cp(1,1) cp(1,2)];

% what we really need is a state machine model (-:

if strcmp(button,'normal'),
  
  if strcmp(state.mode,'drawing'),
    % add a new point to the current line
    XData = get(state.line,'XData');
    YData = get(state.line,'YData');
    
    XData = [XData cp(1,1)];
    YData = [YData cp(1,2)];
    
    set(state.line,'XData',XData);
    set(state.line,'YData',YData);
    
  elseif strcmp(state.mode,'idle'),
    % start a new line
    state.line = line([cp(1,1)],[cp(1,2)]);
    state.mode = 'drawing';
  
    set(state.line,'color',[1 0 0]);
  end
  
elseif strcmp(button,'alt'),
  
  if strcmp(state.mode,'idle'),
    moveplot(state.line,'axy');
  end
  
  if strcmp(state.mode,'drawing'),
    state.mode = 'idle';
  end

end

disp(sprintf('The new mode is "%s"',state.mode));

set(h,'UserData',state);

