% Plot BER versus Eb/No in dB for Hamming(7,4) and 3 times repetition code
% and rate 1/2 convolutional code.
%
% Rich Kozick, December 2001

EbN0dB = -1.6:0.1:9.6;
EbN0 = 10.^(EbN0dB/10);
pvec = Qf(sqrt(2*EbN0));

% Hamming code upper and lower bounds:
k = 4;    % Number of message bits per block
n = 7;    % Number of codeword bits per block
PeUe = 1 - (1-pvec).^7 - 7*(pvec).*(1-pvec).^6;
PeLe = PeUe/k;

% 3-times repetition code:
PeRep3e = pvec.^3 + 3*(pvec.^2).*(1-pvec);

% Upper bound for convolutional code:

dfree = 5;         % Free distance for this convolutional code
Np = length(pvec);
for ip=1:Np
p = pvec(ip);

done = 0; 
k = dfree; 
Pb(ip) = 0;
while (~done)
  Pk = 0;
  if (mod(k,2))    % k is odd
    for ee = (k+1)/2:k
      Pk = Pk + nchoosek(k,ee)*p^ee*(1-p)^(k-ee);
    end
  else             % k is even
    for ee = k/2:k
      Pk = Pk + nchoosek(k,ee)*p^ee*(1-p)^(k-ee);
    end
    Pk = Pk + 0.5*nchoosek(k,k/2)*p^(k/2)*(1-p)^(k/2);
  end
  ck = (k-4)*2^(k-5);
  dPb = ck*Pk;
  Pb(ip) = Pb(ip) + dPb;
% if (dPb < 1e-8)
  if (k >= 10)
    done = 1;
  else
    k = k+1;
  end    
end

end  % for loop ip

% BER versus Eb/N0 for BPSK signals

figure(1)
semilogy(EbN0dB, Pb, 'b-', EbN0dB, PeUe, 'r-', EbN0dB, PeLe, 'g-', ...
EbN0dB, PeRep3e, 'k-', EbN0dB, pvec, 'k--')
legend('CONV. CODE U.B. (HARD DEC.)', 'HAMMING (7,4) U.B.', ...
'HAMMING (7,4) L.B.', '3 \times REPETITION CODE', 'UNCODED')
xlabel('E_b / N_0  (dB)')
ylabel('BER')
title('BER FOR BPSK IN AWGN')
axis([-1.6 9.6 1e-6 .5])
grid
