function seggui(action)
% function seggui(action), if action = img, init
%
% an image segmentation demo
%
% Daniel A. Spielman, Yale University, Oct 3, 2006

if (isnumeric(action)),

  clf;

  img = action;

  u = [];
  u.img = img;
  u.pts = [];
  set(gcf,'UserData',u);

  h = image(img);

  hold on

  set(h,'ButtonDownFcn','seggui(''setpoint'')');

  h = uimenu('Label','Segmentation');
  h1 = uimenu(h,'Label','Segment');
  h2 = uimenu(h,'Label','Clear');

  set(h1,'Callback','seggui(''part'')');
  set(h2,'Callback','seggui(''clear'')');

else % is an action

if strcmp(action,'clear'),

  cla;

  u = get(gcf,'UserData');

  h = image(u.img);

  hold on

  set(h,'ButtonDownFcn','seggui(''setpoint'')');

  u.pts = [];

  set(gcf,'UserData',u);

elseif strcmp(action,'setpoint'),

  cp = get(gca,'CurrentPoint');
  cp = cp(1,[1 2]);

  plot(cp(1),cp(2),'ko','MarkerFaceColor','w');

  u = get(gcf,'UserData');

  if (isempty(u.pts)),
    u.pts = cp;
  else
    u.pts = [u.pts;cp];
  end

  set(gcf,'UserData',u);

elseif strcmp(action,'part'),

  u = get(gcf,'UserData');

  display('segmenting -- please wait');
  [v,a] = imgFlowSep(u.img, u.pts);

  if (size(v,2) == 2)

    figure;
    subplot(1,2,1);

    sz = size(u.img);
    image(reshape(v(:,1)*64,[sz(1),sz(2)]));

    colormap(gray);

    subplot(1,2,2);
    imcut2(u.img,sparsecut(a,v(:,1)));    

  end

  if (size(v,2) == 3)

    figure;
    subplot(2,2,1);

    sz = size(u.img);
    image(reshape(v,[sz(1),sz(2),3]));

    for i = 1:3,
      subplot(2,2,1+i);
      imcut(u.img,sparsecut(a,v(:,i)));    
    end
    

  end

  if (size(v,2) > 3),
    for i = 1:size(v,2),
     figure;
     imcut(u.img,sparsecut(a,v(:,i)));    
    end
  end

end

end
