%
format long
clear all
clc
%% Creating system parameters based on IEEE 802.11a OFDM
FFT = 64; % FFT Length, 
Gi = 1/4; % Guard Interval of Preamble and Symbol
LGS = 6;  % Lower Gurad Band Subcarrier
UGS = 5;  % Upper Guard Band Subcarrier
M = 4; % Using QPSK modulation
Num_of_Symbol = 1e3; % Number of Symbol
PilotIndex = [12; 26; 40; 54]; % 4 pilot subcarriers with index following IEEE802.11a standard
%
%% Creating 10 short training sequence
t1 = zeros(53,1);
t1(3) = 1+1i;t1(11) = 1+1i;t1(23) = 1+1i;t1(39) = 1+1i;t1(43) = 1+1i;t1(47) = 1+1i;t1(51) = 1+1i;
t1(7) = - t1(3);t1(15) = - t1(3);t1(19) = - t1(3);t1(31) = - t1(3);t1(35) = - t1(3);
short = sqrt(13/6).*t1; % Normalized factor 

short_pre = [zeros(6,1); short; zeros(5,1);];
short_train = []; % Short training symbol
for i1 = 1:10
    short_train = [short_train; short_pre];
end    

%% Creating 2 long training sequence
t2 = ones(53,1);
t2(27) = 0;
t2(3) = -1;t2(4) = -1;t2(7) = -1;t2(9) = -1;t2(16) = -1;t2(17) = -1;t2(20) = -1;t2(22) = -1;t2(29) = -1;t2(30) = -1;
t2(33) = -1;t2(35) = -1;t2(37) = -1;t2(38) = -1;t2(39) = -1;t2(40) = -1;t2(41) = -1;t2(44) = -1;t2(45) = -1;
t2(47) = -1;t2(49) = -1;

long_pre = [zeros(6,1); t2; zeros(5,1);];
long_train = [long_pre; long_pre];  % Long training symbol
%% Creating Data Symbol

hMod = comm.OFDMModulator('FFTLength',FFT,'NumGuardBandCarriers',[LGS;UGS],'InsertDCNull',true,'PilotInputPort',true,...
        'PilotCarrierIndices',PilotIndex,'CyclicPrefixLength',FFT*Gi,'NumSymbols',Num_of_Symbol,'Windowing', true, 'WindowLength', 8); % 
showResourceMapping(hMod);
t3 = info(hMod);
data = randi([0 M-1],t3.DataInputSize); % Creating random number with size Number of data carrier x Number of Symbol , 48*1e4 
t4 = reshape(data,numel(data),1); % Reshaping to collum vector
t5 = comm.PSKModulator('ModulationOrder',M,'SymbolMapping','Gray'); % Creating PSK Modulator
data_mod = step(t5,t4); % Modulation
t6 = reshape(data_mod,t3.DataInputSize); % Revert symbol to orgin size 48*1e4
%
d_pilot = randi([0 1],t3.PilotInputSize); 
t7 = reshape(d_pilot,numel(d_pilot),1);
t9 = comm.BPSKModulator;
t10 = step(t9,t7);
t11 = reshape(t10,t3.PilotInputSize);

dataOFDM = step(hMod,t6,t11); % Modulate OFDM methods
%% OFDM Frame
ofdm_frame = [short_train; long_train; dataOFDM];
frame = interp(ofdm_frame,2);
%% Creating *.mat file using savesvarecording function
clearvars -except frame 
sampleFreq = 20e6; % 20 MHz bandwidth

centerFreq = 5.805*1e9; % 5.805 GHz

savevsarecording( 'C:\users\Anh\Documents\MATLAB\thesis\ofdm.mat', frame, sampleFreq, centerFreq)
