function a=bufferdata(source,L,varargin)
% bufferdata - collect elements of sequence into sequence of arrays
%
% bufferdata :: 
% 	  data [[N]]	  ~'source signal',
%	  L:natural	     ~'buffer width',
%	-> data [[N,L]]. ~'buffered sequence (no-overlapping)'.


if nargin==1 && isa(source,'bufferdata'), a=source; 
elseif nargin==0, a=bufferdata([],1);
else
	sz=size1(source);
	
	a.dim = length(sz)+1; 
	a.width = L;
	[a.buf,source] = readcat(a.dim,source,L); 

	if isempty(a.buf), a=[];
	else
		% sort out function table
		ft.datafn=@datafn;
		ft.stringfn=@stringfn;
		ft.nextfn = @nextfn;

		a=class(a,'bufferdata',ddata(source,[sz L],ft));
	end
end

function s=stringfn(a), s=sprintf('buffer(%d)',a.width);
function x=datafn(a), x=a.buf;
function a=nextfn(a)
	% read next lot of values and make an array
	src=source(a);
	[a.buf,src]=readcat(a.dim,source(a),a.width);
	if isempty(a.buf), a=[];
	else
		a=setsource(a,src);
		%!! what if i<L?
		%a.length=size(source(a),a.dim);
	end

function [buf,src]=readcat(dim,src,L)
	buf=[];
	for i=1:L
		if isempty(src), break; end
		buf=cat(dim,buf,head(src));
		src=next(src);
	end
	
