function Y=rndwindow(X,span,dim,varargin)
% rndwindow - get random windows of a signal
%
% rndwindow :: 
%    [Size:[1,E]] ~'E-dimensional signal array',
%    L:natural    ~'span of windows to extract',
%    D:1..E       ~'dimension to operate along',
%    randstate    ~'intial state of rngs'
% -> seq [arrset(Size,D,L)] ~'seq of arrays of size L in Dth dimension'.

	opts=prefs('state',rndstate,'circular',0,varargin{:});

	sz=size1(X);
	if nargin<3, dim=length(sz); end
	len=sz(dim);
	ran=[0,span-1];

	if opts.circular, 
		ithresh=len-span+1;
		Y=map(@exwin_circ,rndzip(@()randnat(len),opts.state));
	else 
		Y=map(@exwin,rndzip(@()randnat(len-span+1),opts.state));
	end

	function y=exwin(i), y=extract(X,dim,i+ran); end
	function y=exwin_circ(i), 
		if i<=ithresh
			y=extract(X,dim,i+ran);
		else
			y=cat(dim,extract(X,dim,[i,len]),extract(X,dim,[1,span-(1+len-i)]));
		end
	end
	
	function s=strfn(a)
		s=sprintf('rndwindow(%s,%d)',tostring(X),span);
	end
end

	




