% MCOFDMDriver - driver script for OFDM Monte Carlo simulation
%
% Simulation driver script to control execution and maintain statistics.
%
% See also:
%   MCOFDM for simulation of system

%% Parameters
% comms parameters delegated to script SimpleSetParameters
OFDMSetParameters;

% simulation parameters
EsOverN0dB = 0:0.5:9; % vary SNR between 0 and 9dB
MaxSymbols = 1e6;     % simulate at most 1000000 symbols

% desired confidence level an size of confidence interval
ConfLevel   = 0.95;
ZValue      = Qinv( ( 1-ConfLevel )/2 );
ConfIntSize = 0.1;  % confidence interval size is 10% of estimate 
% For the desired accuracy, we need to find this many errors.
MinErrors  = ( ZValue/ConfIntSize )^2;     

Verbose    = true;  % control progress output

%% simulation loops
% initialize loop variables
NumErrors  = zeros( size( EsOverN0dB ) );
NumSymbols = zeros( size( EsOverN0dB ) );

% outer loop loops over simulation parameterEsOverN0dB
for kk = 1:length( EsOverN0dB )
    % set Es/N0 for this iteration
    Parameters.EsOverN0 = dB2lin( EsOverN0dB(kk) );
    % reset stop condition for inner loop
    Done = false;
    
    % progress output
    if (Verbose)
       disp( sprintf( 'Es/N0: %0.3g dB',  EsOverN0dB(kk) ) );
    end
    
    % inner loop iterates until enough errors have been found
    while ( ~Done )
        NumErrors(kk)  = NumErrors(kk)  + MCOFDM( Parameters );
        NumSymbols(kk) = NumSymbols(kk) + Parameters.NSymbols;
        
        % compute Stop condition
        Done = NumErrors(kk) > MinErrors || NumSymbols(kk) > MaxSymbols;
    end
    
    % progress output
    if (Verbose)
        disp(sprintf( 'Symbols: %8d, Errors: %5d, Rate: %0.3g\n\n', ...
            NumSymbols(kk), NumErrors(kk), ...
            NumErrors(kk)/NumSymbols(kk) ) );
    end
    
end