function [pduBitsWithCRC, accessAddress] = helperBLEPHYRx(rxWaveform, phyMode, sps, accessAddress, channelIdx)
%helperBLEPHYRx BLE PHY waveform receiver
%   [PDUBITSWITHCRC, ACCESSADDRESS] = helperBLEPHYRx(RXWAVEFORM, PHYMODE,
%   SPS, ACCESSADDRESS, CHANNELIDX) decodes BLE waveform and returns the
%   decoded bits (including CRC), PDUBITSWITHCRC, along with the access
%   address, ACCESSADDRESS.

%   Copyright 2019 The MathWorks, Inc.

accessAddressBin = de2bi(hex2dec(accessAddress), 32)';

% Create and configure the receiver System objects
initRxParams = helperBLEReceiverInit(phyMode, sps, accessAddressBin);

[bits, accessAddress] = helperBLEPracticalReceiver(rxWaveform, initRxParams, channelIdx);

% Initialize
pduBitsWithCRC = [];
octetLen = 8; % Number of bits for an octet
% Refer Bluetooth core specification, v5.0, Vol6, PART B, Section 2.1
crcLen = 3*octetLen;    % Three octets
% Refer Bluetooth core specification, v5.0, Vol6, PART B, Section 2.4
headerLen = 2*octetLen; % Two octets

if(~isempty(bits))
    % Fetch the length field from the decoded bits
    pduLenField = double(bits(9:16)); % Second byte of the PDU header
    % Calculate size of the "payload" field of the Link Layer PDU in bits
    payloadLenInBits = comm.internal.utilities.bi2deRightMSB(pduLenField', 2) * octetLen;
    % Calculate size of the Link Layer PDU (Header | Payload | CRC)
    pduLen = payloadLenInBits + crcLen + headerLen;
    % Fetch the Link Layer PDU from the decoded bits
    if length(bits) >= pduLen
        pduBitsWithCRC = bits(1:pduLen);
    end
end
end