% MCVADriver - driver script for Monte Carlo simulation of
% wide-band system with VA
%
% Simulation driver script to control execution and maintain statistics.
%
% See also:
%   MCVA for simulation of system

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

% simulation parameters
EsOverN0dB = 0:1:10;  % vary SNR between 0 and 10dB
MaxSymbols = 1e5;     % simulate at most this many symbols
MinFrames  = 100;     % simulate at least this many frames

% 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 ) );
NumFrames  = 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)  + MCVA( Parameters );
        NumSymbols(kk) = NumSymbols(kk) + Parameters.NSymbols;
        NumFrames(kk)  = NumFrames(kk)  + 1;
        
        % compute Stop condition
        Done = (NumErrors(kk) > MinErrors || NumSymbols(kk) > MaxSymbols) && ...
            NumFrames(kk) > MinFrames;
    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

%% save results
ErrorRate = NumErrors./NumSymbols;
ConfInt  = ZValue * sqrt( ErrorRate .* (1-ErrorRate) ./ NumSymbols );

save MCVAData.mat ErrorRate ConfInt EsOverN0dB;
