function x=blockdata(gen,dur,s0,varargin)
% blockdata - Signal as a sequence of blocks from signal generator object
%
% blockdata :: 
%    gen(A,B{1:N}) ~'signal generator object with state A and N params B',
%    seq(natural)  ~'number of samples to generate in each block',
%    A             ~'initial state',
%    seq(B{1})     ~'sequence of 1st param values',
%    ...           
%    seq(B{N})     ~'sequence of Nth param values',
% -> seq([[1,_]])  ~'heterogenous sequence of arrays'.
%
% The main point of this construct is to maintain state
% between calls to the block method of the signal generator, and
% also to supply the generator with a sequence of parameter
% values.

	nargs=length(varargin)+1;
	params=cellmap(@dd,varargin); % make sure all input sequences actually are
	perm=[nargs+1,1,2:nargs];
	x=zipaccum(@blockgen,s0,[{dd(dur)},params]); 

	% !! NOTE: it would also be possible to NOT maintain state between calls,
	% so that each block would start from the same initial state
	% x=zipwith(@blockgen_nostate,dd(dur),params{:}); 

	function [y,state]=blockgen(varargin)
		% this is weird - for some reason Matlab crashes if I call block
		% directly from here, but is ok if I go via the non-nested bblock
		[y,state]=bblock(gen,varargin{perm});
	end
	
%	function y=blockgen_nostate(theta)
%		y=block(gen,s0,ceil(theta{1}),theta{2:end});
%	end
end

function [y,s]=bblock(varargin) 
	[y,s]=block(varargin{:}); 
end

