function handles=scatui(fig2,plotfn,X,varargin)
% scatui - scat with interactive point clicking ui
%
% scatui ::
%    handle          ~'figure to do secondary plot',
%    (natural->unit) ~'function to do secondary plot',
%    [[N,E]]         ~'array of N points in E-space'
% -> action handle.
%
% This does several things:
% 1. Plots 3d scatter plot as stereo pairs in fig 1
% 2. Sets up stereo 3D cursor.
% 3. Sets up button click callbacks so you can
%    click to select one of the points
% 4. Starts the whole thing rotating so you can
%    see what shape it is without going cross-eyed
	  
	% transpose if it looks appropriate
	if size(X,1)<5, X=X'; end
	if size(X,2)>2
		pick=@(t,o)pick3d(t,get(o,'XData'),get(o,'YData'),get(o,'ZData'));
		curf=@(t,varargin)cursor3d(t(1:3),varargin{:});
	else
		pick=@(t,o)pick3d(t,get(o,'XData'),get(o,'YData'),zeros(size(X,1),1));
		curf=@(t,varargin)cursor2d(t(1:2),varargin{:});
	end

	% do scat in current figure
	handles=scat(X,varargin{:}); fig1=gcf;
	curs=[];

	% get info about scatter plot
	set(handles,'ButtonDownFcn',@btndown);

	function btndown(obj,dummy)
		r=get(get(obj,'Parent'),'CurrentPoint'); % get clicked point from axes
		[x,i]=pick(r,obj);      	% find nearest point
		if isempty(curs)
			curs=curf(x);
		else	
			curf(x,curs);      	% move cursor
		end	
		% title(sprintf('pick: %d',i));
		figure(fig2); plotfn(i); 	% do plot in other figure
		figure(fig1); drawnow;  	% return to this figure
	end
end



