%Copyright 2005-2018 The MathWorks, Inc.
function ts = mdl_derive_sampletime_for_sldvdata(mdlSampleTimes)
% MDL_DERIVE_SAMPLETIME_FOR_SLDVDATA
% This functions is used by SLDV for harness generation. It is invoked with a 
% sorted list of sample times. In the discrete case there is no 0 rate, and
% the first sample-time is the fundamental sample-time. This is the normal
% mode of invocation for SLDV. However, SLDV supports generating a harness
% for models that have continuous rates. In this case, this function is
% used to compute the gcd of all the discrete sample-times in the model.
%
% References:
% This function uses slexecGCD for calculating the GCD of rates. This in turn
% dispatches to slexec::util::math::gcd32 which is the function used by
% Simulink to calculate base rates.
%

    if mdlSampleTimes(1)~=0 || ...
            length(mdlSampleTimes) == 1
        % When the block in consideration has no discrete sample times, the
        % input contains a single entry of 0. In such cases, there are no
        % entries to find GCD of, and we return the 0 value itself as sample
        % time. (G1554640)
        ts = mdlSampleTimes(1);
    else
        % This branch is executed only if there is a continuous rate in the
        % model.
        sampleTimes = mdlSampleTimes(2:end);
        ts = computeBaseRate(sampleTimes);
    end
end

function baseRate = computeBaseRate(rates)
% compute the base rate. rates array should be sorted.
% todo: handle offsets in this code. It is only handling period right now.
if isempty(rates) || any(rates == 0.0)
    baseRate = 0.0;
    return;
end

% filter out Infs and NaNs
rates = rates(rates ~= inf);
rates = rates(rates ~= -inf);
rates = rates(~isnan(rates));

% only consider absolute value
rates = abs(rates);

baseRate = slexecGCD(rates);

end
