function [avgFreqDev,centerFreq,maxFreqDev] = helperModulationCharacteristicsTest(waveform,sps)
%helperModulationCharacteristicsTest Returns modulation characteristics
%test values for Bluetooth low energy and basic rate.
%   [AVGFREQDEV,CENTERFREQ,MAXFREQDEV] =
%   helperModulationCharacteristicsTest(WAVEFORM,SPS) performs modulation
%   characteristics test on the FM demodulated waveform, WAVEFORM.
%
%   AVGFREQDEV is a scalar or 1x2 vector containing average frequency
%   deviation(s) of the test sequences.
%
%   CENTERFREQ is a column vector or Nx2 vector containing sequence center
%   frequencies calculated over each byte of two test sequences, N depends
%   on the number of bytes in the waveform.
%
%   MAXFREQDEV is a column vector containing maximum frequency deviations
%   of first or second test sequence.
%
%   WAVEFORM is a Nsx2 vector containing FM demodulated waveforms of two
%   test sequences, where Ns represents the number of time-domain samples.
%
%   SPS denotes the number of samples per symbol.

%   Copyright 2020 The MathWorks, Inc.

bitsPerByte =8;
spb = sps*bitsPerByte; % Samples per byte
numOfBytes = length(waveform)/spb;
centerFreq = zeros(numOfBytes-1,size(waveform,2));
freqDev = zeros(numOfBytes-1,size(waveform,2));
maxFreqDev = zeros((numOfBytes-1)*bitsPerByte*size(waveform,2)/2,1);
for ii = 1:numOfBytes-1
    % For first test sequence, maximum frequency deviations are calculated
    % over 2nd, 3rd, 6th, 7th of the 8 bits. Average of all the maximum
    % frequency deviations is calculated.
    bitPosition1 = [2 3 6 7]; % First sequence bit positions
    waveformDiffFreqArray1 = waveform(spb*(ii-1)+4*sps+1:spb*(ii)+4*sps,1);
    centerFreq(ii,1) = mean(waveformDiffFreqArray1);
    bitfreqOffset1 = zeros(1,4);
    for i = 1:4
        bitFrequency1 = mean(waveformDiffFreqArray1((bitPosition1(i)-1)*sps+1:bitPosition1(i)*sps));
        bitfreqOffset1(i) = abs(bitFrequency1-centerFreq(ii,1));
    end
    freqDev(ii,1) = mean(bitfreqOffset1);
    if size(waveform,2) ==2
        % For second test sequence, maximum frequency deviations are
        % calculated over all the 8 bits. Average of all the maximum
        % frequency deviations is calculated.
        bitPosition2 = 1:8; % First sequence bit positions
        waveformDiffFreqArray2 = waveform(spb*(ii-1)+sps+1:spb*(ii)+sps,2);
        centerFreq(ii,2) = mean(waveformDiffFreqArray2);
        bitfreqOffset2 = zeros(1,8);
        for i = 1:8
            bitFrequency2 = (waveformDiffFreqArray2((bitPosition2(i)-1)*sps+1:bitPosition2(i)*sps));
            bitfreqOffset2(i) = max(abs(bitFrequency2-centerFreq(ii,2)));
        end
        maxFreqDev((ii-1)*bitsPerByte+1:bitsPerByte*ii,1) = bitfreqOffset2.';
        freqDev(ii,2) = mean(bitfreqOffset2);
    else
        maxFreqDev((ii-1)*bitsPerByte/2+1:bitsPerByte/2*ii,1) = bitfreqOffset1.';
    end
end
avgFreqDev = mean(freqDev); % Average frequency deviations for the two sequences
end