%hDecodeLTESubframe Subframe decoding and EVM calculation
%   [EVM,PDSCHSYM] = hDecodeLTESubframe(SUBFRAMENO,SUBFRAME,SIMPARAMS,COUNT) 
%   decodes the SUBFRAME with number SUBFRAMENO given parameters in SIMPARAMS. It
%   returns the decoded symbols PDSCHSYM and the average EVM. It considers
%   the COUNT of received subframes to plot EVM measurements when all
%   subframes have been received.

%   Copyright 2020 The MathWorks, Inc.

function [EVM,pdschSym] = hDecodeLTESubframe(subframeNo,subframe,simParams,count)
 
    % Get parameters from Waveform Parameters block
    tm = simParams.waveConfig.tm;
    bandwidth = simParams.waveConfig.bandwidth;
    cellId = simParams.waveConfig.cellId;
    duplexing = simParams.waveConfig.duplexing; 
    windowing = simParams.waveConfig.windowing;
    stopTime = simParams.StopTime;
    
    % Store every received subframe to calculate EVM considering the whole waveform
    persistent subframeVector;
    subframeVector = [subframeVector; subframe];

    % Extract waveform information for demodulation
    lteTM = lteTestModel(tm,bandwidth,cellId,duplexing);
    lteTM.Windowing = windowing;
    [~,~,tmWaveformInfo] = lteTestModelTool(lteTM);

    % Output PDSCH symbols per subframe to update constellation plot
    cec.PilotAverage = 'TestEVM';
    tmWaveformInfo.NSubframe = subframeNo;
    EVMalg.EnablePlotting = 'Off';              % EVM plots disabled until all subframes have been received
    EVMalg.EnableCommandWindowOutput = false;   % EVM results disabled until all subframes have been received
    [~,~,measInfo] = hPDSCHEVM(tmWaveformInfo,cec,subframe,EVMalg);
    if ~isempty(measInfo.PDSCHSymbols)
        pdschSym = measInfo.PDSCHSymbols;
    else
        % Assign NaN value as Simulink does not accept empty arrays 
        pdschSym = NaN;
    end
    
    % Compute and display EVM measurements when all subframes have been received
    TotNumSubframes = floor(stopTime/simParams.tsubframe);
    if  count == TotNumSubframes        
        EVMalg.EnablePlotting = 'On';              % EVM plots enabled
        EVMalg.EnableCommandWindowOutput = true;   % EVM results enabled
        tmWaveformInfo.NSubframe = 0;              % Number of first subframe received
        [evmmeas,plots,~] = hPDSCHEVM(tmWaveformInfo,cec,subframeVector,EVMalg);
        assignin('base','plots',plots);
        EVM = evmmeas.RMS*100;
    else
        % Assign NaN value as Simulink does not accept empty arrays
        EVM = NaN;
    end

    % Save overall EVM to workspace
    assignin('base','EVMrms',EVM);
    
end