function lines = image_lines( img, lines, name )
%IMAGE_LINES  Edit two groups of lines in the image.
%
%   lines = image_lines( img, lines )
%
%   Edit two groups of lines in the image. Demonstration of EDIT_LINES usage.
%
%   Input:
%     lines .. structure, fields:
%       .x1, .y1 .. end points of the lines from the first group
%       .x2, .y2 .. end points of the lines from the second group
%
%     Coordinates are in the form [ ... [beg_i;end_i] ... ] where
%     beg_i is the i-th line start point and end_i is the i-th line end point.
%
%   Output:
%     lines .. modified structure

% (c) 2010-09-16 Martin Matousek
% Last change: $Date$
%              $Revision$

  if ~exist( 'lines', 'var' ) || isempty( lines )
    lines = struct;
  end

  style1 = { 'color', 'r', 'linewidth', 2, 'tag', '1' };
  style2 = { 'color', 'y', 'linewidth', 2, 'tag', '2' };
  style3 = { 'color', 'b', 'linewidth', 2, 'tag', '3' };
  style4 = { 'color', 'g', 'linewidth', 2, 'tag', '4' };

  fig = figure;
  if exist( 'name', 'var' )
    set( f, 'name', name, 'numbertitle', 'off' );
  end

  imagesc( img );
  hold on
  if isfield( lines, 'x1' )
    plot( lines.x1', lines.y1', style1{:} );
  end

  if isfield( lines, 'x2' )
    plot( lines.x2', lines.y2', style2{:} );
  end

  if isfield( lines, 'x3' )
    plot( lines.x3', lines.y3', style3{:} );
  end

  if isfield( lines, 'x4' )
    plot( lines.x4', lines.y4', style4{:} );
  end

  hold off
  axis image
  edit_lines( gcf, { style1 style2 style3 style4 } );

  fprintf( 'Edit the lines.\n' );
  fprintf( 'Press a key in the figure: ''1'' - ''4'' .. change a line style\n');
  input( 'Press <Enter> in the command window when done.' );

  lines = extract_lines( lines, fig, '1' );
  lines = extract_lines( lines, fig, '2' );
  lines = extract_lines( lines, fig, '3' );
  lines = extract_lines( lines, fig, '4' );

  close( fig );

end % fcn.


function elines = extract_lines( lines, fig, id )
  h = findobj( fig, 'tag', id );
  x = get( h, 'xdata' );
  y = get( h, 'ydata' );

  if iscell( x )
    x = cell2mat( x );
    y = cell2mat( y );
  end

  lines.(['x' id]) = x;
  lines.(['y' id]) = y;
  elines = lines;
end % fcn.
