function [eCANModuleClock, BaudRatePrescaler, BaudRate, errorID] = calceCANBaudRatePrescaler(sysclkoutInMHz, TSEG1, TSEG2, BaudRatePrescalerRaw, SampleNumbers, SubFamily)
%CALCECANBAUDRATEPRESCALER Summary of this function goes here
%   Detailed explanation goes here

% Copyright 2012-2022 MathWorks, Inc.

errorID = '';
switch SubFamily
    case {'2803x', '2805x', '2806x', '2833x'}
        sysclk_divider = 2;
    case '2834x'
        sysclk_divider = 4;
    otherwise
        sysclk_divider = 1;
end
eCAN_clk = sysclkoutInMHz * 1e6 / sysclk_divider; % MHz to Hz

bit_time = TSEG1 + TSEG2 + 1;

if TSEG1 < TSEG2
    errorID = 'tgtPrefsPeripheralTSEGsCompare';
end

BaudRatePrescaler = BaudRatePrescalerRaw;

if isequal(SubFamily, '280x') || isequal(SubFamily, '281x') || ...
   isequal(SubFamily, '2803x') || isequal(SubFamily, '2804x') || ...
   isequal(SubFamily, '2805x') || isequal(SubFamily, '2806x') || ...
   isequal(SubFamily, '2833x') || isequal(SubFamily, '2834x')
    % For the special case of BRP = 1, the Information Processing Time (IPT) is equal to 3 time
    % quanta (TQ). This is not compliant to the ISO 11898 Standard, where the IPT is defined to be less
    % than or equal to 2 TQ. Thus the usage of this mode (BRPreg = 0) is not allowed
    if BaudRatePrescalerRaw < 2
        errorID = 'tgtPrefsPeripheralCANBRP';
        BaudRatePrescaler = 2;
    end
    % The value of baud rate prescalar should be between 2 and 256
    if BaudRatePrescalerRaw > 256
        errorID = 'tgtPrefsPeripheralCANBRP';
        BaudRatePrescaler = 256;
    end
else
    if BaudRatePrescalerRaw < 1
        errorID = 'tgtPrefsPeripheralCANBRP_1024';
        BaudRatePrescaler = 1;
    end
    % The value of baud rate prescalar should be between 1 and 1024
    if BaudRatePrescalerRaw > 1024
        errorID = 'tgtPrefsPeripheralCANBRP_1024';
        BaudRatePrescaler = 1024;
    end
end

if strcmp(SampleNumbers, 'Sample_three_times') && BaudRatePrescalerRaw < 5
    errorID = 'tgtPrefsPeripheralCANSAMSample';
    BaudRatePrescaler = 5;
end

BaudRate = eCAN_clk /(BaudRatePrescaler * bit_time);
eCANModuleClock = eCAN_clk / 1e6; % Hz to MHz
