function X=rndscanl(gen,s0,varargin)
% rndscanl - Random scanl 
%
% rndscanl ::
%    (S,A -> rndgen S) ~'random scanner',
%    S                 ~'initial state',
%    seq A, 
%    rndstate                  ~'initial random state'
% -> seq S.

	n=length(varargin)-1;
	rs0=varargin{n+1};
	if n>1,
		X=zipaccum(@zafn,{s0,rs0},varargin{1:n});
	elseif n==1
		X=mapaccum(@mafn,{s0,rs0},varargin{1});
	else
		X=unfold(@ufn,{s0,rs0});
	end

	function [x,s]=ufn(s0)
		setrndstate(s0{2});
		x=gen(s0{1});
		s={x,getrndstate};
	end
	
	function [x,s]=mafn(y,s0)
		setrndstate(s0{2});
		x=gen(s0{1},y);
		s={x,getrndstate};
	end
	
	function [x,s]=zafn(varargin)
		s0=varargin{n+1};
		setrndstate(s0{2});
		x=gen(s0{1},varargin{1:n});
		s={x,getrndstate};
	end
end
	


