% schedrec - Schedule events where each event returns the next event.
%
% schedrec :: schedule => sched_api.

function API=schedrec(sch0,varargin)
	opts=options('error',0,'weight',1,varargin{:});

	ERROR=opts.error*opts.weight; 
	K=opts.weight;

	warning('off','MATLAB:TIMER:STARTDELAYPRECISION');

	Next=sch0; 
	Timer=timer('TimerFcn',@timercb,'StopFcn',@chain);
	chain(Timer,[]);

	API.dispose = @()delete(Timer);
	API.get_mean_error = @get_error;
	API.get_schedule = @get_tail;
	API.set_schedule = @set_tail;

	function e=get_error, e=ERROR/K; end
	function sch=get_tail, sch=Next; end
	function set_tail(sch)
		Next=sch; 
		if isrunning(Timer), stop(Timer); 
		else chain(Timer,[]);
		end
	end

	function timercb(o,e)
		[err,Next]=Next{2}(Next{1}); %,e.Data.time);
		ERROR = ERROR+err; K = K+1;
	end

	function chain(o,e)
		correction=ERROR/K;

		while true
			if isempty(Next), 
				fprintf('\n| schedrec stopping\n'); 
				return; 
			end
			delay=Next{1}-correction-nows;
			if delay>=0.001, break; end
			[err,Next]=Next{2}(Next{1});
		end

		set(o,'StartDelay',delay); 
		start(o);
	end
end
