%% Skript pro simulaci fyzicke vrstvy IEEE 802.11n

close all
clearvars
clear global
clc

tic
%% define some parameters ----------------------------------------
wifi_standard = '802dot11ac';

CH_BANDWIDTH = 'CBW20';

GuardInterval = 'normal'; % 'short', 'normal', 'doubled'
coding_type = 'BCC'; % 'BCC' or 'LDPC'
decision_type = 'LLR'; %'HD' - Hard decision values; 'LLR' - Log-likelihood ratio(LLR);

LENGTH_vec = 10; % pocet oktetu uzivatelskych dat (0--65535)

% MCSvec = [0 1];
MCSvec = 1:1;

%% define simulation parameters -------------------------------------------
channelType = 'awgn'; % 'awgn' or 'fad'
SNR = 0:20;

N_frames = 100; % the number of frames within inner loop (for each SNR value)
n_users = [1 1]; % [tx rx] tx always set to 1 % no MIMO, will be defined

single = true; % no parallel computing (for now)

showPlots = 1;
showMapping = 0;

for i_length = 1:length(LENGTH_vec)
    
    LENGTH = LENGTH_vec(i_length); % LENGTH parameter defines the number of octets in DATA field in a frame, LENGTH = {0; 65535}
    
    error_val = zeros(N_frames,length(SNR),length(MCSvec)); % initialize error values (rewrite using OOP) %%%%%%%%%
    
    for i_mcs = 1:length(MCSvec) % smycka promennych parametru (viz batch file)
        disp(['-----------------------------------------------------------------'])
        load_wifi_params;
        
        disp([wifi_standard,' > ',coding_type,', ',wifi_params.MCS(i_mcs).MCS,', M = ',num2str(wifi_params.MCS(i_mcs).M),', CR = ',sprintf('%2.2f',wifi_params.MCS(i_mcs).CR),', ',num2str(wifi_params.MCS(i_mcs).N_ss),' Spatial stream(s)']);
        disp(['-----------------------------------------------------------------'])
        
        % preallocate result variables
        results = result_allocation(SNR,N_frames,wifi_params);
        
        sim_file;
        
        results = result_all(results);
        
        % generate results file filename
        output_filename = load_filename2(SNR,N_frames,MCSvec(i_mcs),wifi_params,wifi_standard, CH_BANDWIDTH, coding_type, LENGTH, GuardInterval, decision_type);
        filename_suffix = [];
        save(fullfile('./results',[output_filename filename_suffix '.mat']));
        
        
    end % mcs loop
    
end % LENGTH loop

%% simulation results presentation
figure;
semilogy(SNR,results.ber_PSDU)
hold all
semilogy(SNR,results.ber_PSDU_plus_service)
semilogy(SNR,results.ber_coded_data)
semilogy(SNR,results.ber_uncoded_data)

legend('PSDU','PSDU + SERVICE','coded','uncoded')
axis([SNR(1) SNR(end) 10^(-8) 1])
grid on
xlabel('SNR [dB]')
ylabel('BER [-]')


t = toc