% sinkarray - sink that collects data in an array
%
% sinkarray ::
%    ([[C,L]] -> action void) ~'function to do something with array on dispose',
%    C:natural ~'number of channels,
%    L:natural ~'capacity of sink',
%    R:nonneg  ~'sampling rate'
% -> sink(C,R).

classdef sinkarray < sink
	properties (GetAccess=private,SetAccess=immutable)
		chans    % natural
		length   % natural
		fs       % nonneg
		cont     % [[C,N]] -> void
	end
	methods
		function s=sinkarray(cont,ch,len,rate)
			if nargin<4, rate=nan; end
			s.chans=ch;
			s.length=len;
			s.fs=rate;
			s.cont=cont;
		end

		function s=tostring(sig),
			s=sprintf('sinkarray(%s,<%dx%d>)',tostring(sig.cont),sig.chans,sig.length);
		end

		function c=channels(s), c=s.chans; end
		function c=rate(s), c=s.fs; end
		function s=construct(sig)

			length=sig.length;
			ch=channels(sig);
			array=zeros(ch,length);
			pos=0;

			s.start   = @nop;
			s.stop    = @nop;
			s.dispose = @dispose;
			s.writer  = @writer;

			function dispose, sig.cont(array(:,1:pos)); end

			function r=writer(n)
				r = @next;
				CHUNK = 1:uint32(n);
				function rem=next(x) 
					n=size(x,2);
					if pos+n<=length
						array(:,pos+CHUNK)=x; rem=0; 
						pos=pos+n;
					else
						rem=n-(length-pos);
						array(:,pos+1:end)=x(:,1:rem);
						pos=length;
					end
				end
			end
		end
	end
end
