% =============================================================
% This is a system test driver for SDR Detector : test_bpsk.m
% Test a channel with fat matrix and BPSK signalling.
% =============================================================
% Test          :   S-02
% Developed by  :   Nick (Mikalai) Kisialiou,
%                   Prof. Zhi-Quan Luo,
% Contacts      :   kisi0004@umn.edu, luoxx032@umn.edu
% =============================================================

fprintf('=====================================================\n');
fprintf('=           Test driver for SDR Detector            =\n');
fprintf('=====================================================\n');
fprintf('+ Starting simulations\n');
clear opts;

% Array of SNRs to simulate
SNRS = [8 10 30 100 300 1000]; 
len = length(SNRS);

% Number of transmitters
TX = 30;
fprintf('+ TX = %d\n', TX);
% Number of receivers
RX = 25;
fprintf('+ RX = %d\n', RX);

% Number of Monte-Carlo runs
NRUNS = 10;
fprintf('+ Number of runs per SNR level = %d\n', NRUNS);

% ---------------------- SDR Detector ----------------------
time_sdr = zeros(1,len);
max_time_sdr = zeros(1,len);
errors_sdr = zeros(1,len);

% ----------------------------------------------------------
% Loop over all SNR levels 
for k = 1 : len,
    % Pick the SNR level from the specified array
    rho = SNRS(k);
    fprintf('+ Running SNR = %f [dB]\n', 10*log10(rho));
    % Monte-Carlo simulation loop
    for i = 1 : NRUNS,
        % Generate random channel and random data
        A = randn(RX,TX); 
        H = sqrt(rho/TX)*A;
        x = sign(randn(TX,1)); 
        v = randn(RX,1); 
        y = H*x + v;      
 
        % --------------------------------------------------
        % Run SDR Detector
        opts.snr = rho;
        tic;
        [Xdec, Fsdr] = sdr_detector(H, y, opts);
        toc_time = toc;
        if (toc_time > max_time_sdr(k)),
            max_time_sdr(k) = toc_time;
        end
        time_sdr(k) = time_sdr(k) + toc_time;
        errors_sdr(k) = errors_sdr(k) + sum(x ~= Xdec); 
    end
    
    % Compute the BER for the current SNR
    ber_sdr(k) = errors_sdr(k) / (NRUNS * TX);
end

% Average time it took the detectors to run
time_sdr = time_sdr / NRUNS;

disp('============ SDR Detector statistics : =============');
time_sdr
max_time_sdr
ber_sdr

fprintf('+ Simulations complete\n');
fprintf('=====================================================\n');

% ==============================================================
% End of test driver for SDR Detector
% ==============================================================


