function iterate_gui(stfn,S0,varargin)
% iterate_gui - iterate state transformer under GUI control
%
% iterate_gui :: 
%    (A->A,handle)   ~'state transformer function',
%    A               ~'initial state'
% -> gui.
%
% The idea is that the state transformer returns a handle to a
% GUI element to be used for advancing the sequence. You click
% on that element to move to the next element of the sequence.
% Button 2 rewinds to the beginning of the sequence.

% to do: user configurable keys to allow multiple plotseqs
% in same figure, each watching different keys.

	opts=prefs('keyctl','set',varargin{:});

	[S,h]=stfn(S0);
	set(h,'ButtonDownFcn',@btndn);
	switch opts.keyctl
		case 'set', addkbcallback(gcf), addkbcallback(gcf,@keypress);
		case 'add', addkbcallback(gcf,@keypress);
	end

	function next()
		if isempty(S), beep; 
		else 
			[S,h]=stfn(S); 
			set(h,'ButtonDownFcn',@btndn);
		end
	end

	function rewind(), [S,h]=stfn(S0); set(h,'ButtonDownFcn',@btndn); end
	function btndn(a,b)
		if strcmp(get(gcf,'SelectionType'),'alt'), rewind();
		else next(); end
	end

	function keypress(b)
		switch b.Character
			case {'b','r'}, rewind();
			case {' ','n'}, next();
		end
	end
end % of main function

