function s1gWavGenPlotGrid(tx,cfg,titleStr,varargin)
%s1gWavGenPlotGrid Featured example helper function
%
%   Plot OFDM demodulated grid and highlight subcarrier use

%   Copyright 2016-2017 The MathWorks, Inc.

% Extract data field from PPDU
sr = wlanSampleRate(cfg);
Tltf2n = 40*(wlan.internal.numVHTLTFSymbols(cfg.NumSpaceTimeStreams)-1);
Tpreamble = (80+80+80+Tltf2n)*1e-6; % Duration of short preamble
dataIdx = round((Tpreamble*sr))+1:size(tx,1);

% Extract data portion of waveform
data = tx(dataIdx,:);

Ns = round(40e-6*sr);        % Symbol duration in samples
[Nsamples,Nt] = size(data);
Nsym = Nsamples/Ns;          % Number of OFDM symbols
ofdmInfo = wlan.internal.s1gOFDMConfig(cfg.ChannelBandwidth, ...
    cfg.GuardInterval,'Data',cfg.NumSpaceTimeStreams, ...
    cfg.TravelingPilots,Nsym);

% OFDM demodulate S1G Data field
Ngi = ofdmInfo.CyclicPrefixLength;  % CP duration in samples
Nfft = ofdmInfo.FFTLength;          % FFT length
sym = complex(zeros(Nfft,Nsym,Nt)); % Demodulated OFDM symbols
for n = 1:Nsym
    samples = data(Ns*(n-1)+(1:Ns),:); % Extract samples for a symbol
    sym(:,n,:) = permute(fftshift(fft(samples(Ngi+1:end,:))),[1 3 2]);
end    

dInd = ofdmInfo.DataIndices;
pInd = ofdmInfo.PilotIndices;
nullColor = 0;
dataColor = 0.5;
pilotColor = 1;
c = nullColor*ones(Nfft,Nsym); % Container for color per element
if size(pInd,2)==Nsym
    c(sub2ind(size(c),pInd(:),reshape(repmat((1:Nsym),size(pInd,1),1),[],1))) = pilotColor;
    c(sub2ind(size(c),dInd(:),reshape(repmat((1:Nsym),size(dInd,1),1),[],1))) = dataColor;
else
    c(pInd,:,:) = pilotColor;
    c(dInd,:,:) = dataColor;
end
figure;
% Create patches of the same color for legend
p(1) = patch(0,0,nullColor);
p(2) = patch(0,0,dataColor);
p(3) = patch(0,0,pilotColor);

% Draw surface and fix view
% Transmit antenna to plot
if nargin>3
    ntx = varargin{1};
else
    ntx = 1;
end
surface((1:Nfft)-Nfft/2+1,1:Nsym,abs(sym(:,:,ntx).'),c.');
view(160,60);
ylabel('OFDM symbol number');
xlabel('Subcarrier index')
zlabel('Magnitude');
zlim([0 15]);
title(titleStr);
legend(p,'Null','Data','Pilot');
end