% transfer - Transfer samples from a signal to a sink
%
% transfer :: signal(C,R), sink(C,R) -> action natural.
% 
% Returns the number of samples transfered.
function n=transfer(sig,sink,varargin)
	opts=options('chunk',512,varargin{:});
	chunk=uint32(opts.chunk);

	u=construct(sink);
	try
		write=u.writer(chunk);
		s=construct(sig);
		try % to make sure we dispose of s once opened
			n=uint32(0); CHUNK=1:chunk; 
			x=zeros(channels(sig),chunk); % buffer
			r=s.reader(opts.chunk);
			rem=0; 
			s.start();
			u.start(); 
			while rem==0 
				[x,rem]=r();
				if rem==0, rem=write(x); 
				else rem=rem+write(x(:,1:end-rem));
				end
				n=n+(chunk-rem);
			end
			u.stop();
			s.stop();
		catch ex
			s.dispose();
			rethrow(ex);
		end
	catch ex
		u.dispose();
		rethrow(ex);
	end

	s.dispose();
	u.dispose();
end
