% gathern - Collect exactly n samples from a signal
%
% gathern  :: N:natural, signal(C,R), options -> [[C,N]], natural.
function [x,rem]=gathern(m,sig,varargin)
	opts=prefs('chunk',256,varargin{:});

	s=construct(sig);
	try % to make sure we dispose of s once opened
		chunk=uint32(opts.chunk);
		n=uint32(0); CHUNK=1:chunk; 
		x=zeros(channels(sig),m); 
		r=s.reader(opts.chunk);
		rem=0; 
		while rem==0 && n+chunk<=m
			[x(:,n+CHUNK),rem]=r();
			n=n+chunk;
		end
		if n<m && rem==0 % need more and not run out
			[y,rem]=r();
			x(:,n+1:m)=y(:,1:m-n);
			rem=(m-n)-(chunk-rem);
		end
	catch ex
		s.dispose();
		rethrow(ex);
	end
	s.dispose();
end


	
