% Figure 3.27: BER of Orthogonal STBC and Quasi-Orhogonal STBC for a 4x1
% MIMO system and a QPSK input
% ERRATA: caption in book should be "BER of OSTBC and QOSTBC"
% Elisabeth de Carvalho, April 2012


clear all

% number of channel realizations. This number needs to be increased when
% estimating small probabilities
It = 50000;

% SNR range in dB
SNRdBvalues = [0:2:30];


% variable initialization: BER for each channel iteration
PPostbc     = zeros(1,It);
PPqostbc    = zeros(1,It);
PPsiso      = zeros(1,It);


SNRidx = 0;
for SNRdB=SNRdBvalues
    SNRdB
    SNRidx = SNRidx + 1;    % SNR index
    SNR = 10^(SNRdB/10);    % SNR in linear scale
    
    
    % iterations on channel realizations
    for kk=1:It
        
        % generate channels 
        H  = (randn(1,4) + j * randn(1,4)) / sqrt(2);        % 1x4 MISO channel
        h1 = H(1,1); h2 = H(1,2); h3 = H(1,3); h4= H(1,4);   % subchannels 
    
        %%%% Orthogonal STBC
        % equivalent channel 
        HH_o = [h1 h2 h3 h4;
            h2 -h1 h4 -h3;
            h3 -h4 -h1 h2;
            h4 h3 -h2 -h1;
            h1' h2' h3' h4';
            h2' -h1' h4' -h3';
            h3' -h4' -h1' h2';
            h4' h3' -h2' -h1'];
        % computation of post-processing SNR for stream 1
        R = inv(HH_o'*HH_o);
        SNRostbc = SNR/4/R(1,1); 
        % BER for uncoded QPSK input
        PPostbc(kk) = 0.5*erfc(sqrt(0.5*SNRostbc));
        
        
        %%%%  Quasi-Orthogonal STBC
        % equivalent channel 
        HH_qo = [h1  -h2  -h3   h4;
            h2'  h1' -h4' -h3';
            h3' -h4'  h1' -h2';
            h4   h3   h2   h1];
        % computation of post-processing SNR for stream 1
        R = inv(HH_qo'*HH_qo );
        SNRqostbc = SNR/4/R(1,1);
        % BER for uncoded QPSK input 
        PPqostbc(kk) = 0.5*erfc(sqrt(0.5*SNRqostbc));

        
        %%%%  SISO
        SNRsiso = SNR*norm(h1)^2;
        % BER for uncoded QPSK input
        PPsiso(kk) = 0.5*erfc(sqrt(0.5*SNRsiso));
        
    
    end
    
    % average over channel realizations
    Postbc(SNRidx)  = mean(PPostbc)
    Pqostbc(SNRidx) = mean(PPqostbc)
    Psiso(SNRidx)   = mean(PPsiso)
    
    
end


figure(1)
semilogy(SNRdBvalues, Psiso,'k--+','linewidth',1)
hold on
semilogy(SNRdBvalues, Pqostbc,'k-s','linewidth',1)
semilogy(SNRdBvalues, Postbc,'k-*','linewidth',1)
axis([SNRdBvalues(1) SNRdBvalues(end) 10e-8 1])
title('Bit error rate for a QPSK input - i.i.d. Rayleigh slow fading channel')
xlabel('Average SNR \rho (dB)')
ylabel('BER')
legend('SISO','Quasi-Orthogonal STBC','Orthogonal STBC',3)
grid
hold off

