function [tSlotStartTimes_out, taskSlotCounterValues] = slotSyncTask...
    (tTaskStartTimes, sampleTimeMultipleOfBaseRate, tSlotStartTimes_in)
%

%   Copyright 2015 The MathWorks, Inc.

% Tolerate rounding errors
tMult = round(sampleTimeMultipleOfBaseRate);
tolerance = 1000*eps(sampleTimeMultipleOfBaseRate(1));
assert(max(tMult-sampleTimeMultipleOfBaseRate)<tolerance, ...
       'All sample times must be a multiple of the base rate');


if isempty(tSlotStartTimes_in)
    % Initialize using data for first task
    assert(isequal(tMult, [1 0]), 'Must start with a base rate task');
    tSlotStartTimes_out = tTaskStartTimes;
    taskSlotCounterValues = (1:length(tTaskStartTimes))';
    return
end

% Based on sample time multiple of base rate calculate the expected slot counter
% for this task
period = tMult(1); % period as multiple of base rate
offset = tMult(2); % offset as multiple of base rate
taskSlotCounterValuesExpected = ((1+offset) ...
                                 : period ...
                                 : length(tTaskStartTimes)*period)';

tSlotStartTimes_out = tSlotStartTimes_in;
taskSlotCounterValues = taskSlotCounterValuesExpected;

% We may need to bring forward the slot start time, e.g. if the measured start
% time of a sub-rate occurs before the corresponding base rate start time
if any(tTaskStartTimes < tSlotStartTimes_in(taskSlotCounterValues))
    tSlotStartTimes_out(taskSlotCounterValues) = ...
        min(tTaskStartTimes, tSlotStartTimes_in(taskSlotCounterValues));
end





