% codebounds.m -- compute analytical BERs and bounds for various codes.
%
% R. Kozick, November 2001

% Upper and lower bounds for Hamming(7,4) block code

pfine = logspace(-4, 0, 200);
zi = find(pfine <= 0.5);
pfine = pfine(zi);
PeU = 1 - (1-pfine).^7 - 7*(pfine).*(1-pfine).^6;  % Hamming(7,4)
PeL = PeU/4;

% Exact BER for 3 times repetition code

PeRep3 = pfine.^3 + 3*(pfine.^2).*(1-pfine);       % 3x repetition

% Upper bound for convolutional code

dfree = 5;         % Free distance for this convolutional code
Npfine = length(pfine);
for ip=1:Npfine
p = pfine(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

figure(1)
loglog(pfine, Pb, 'b-', pfine, PeU, 'r-', ...
  pfine, PeL, 'g-', pfine, pfine, 'k-', pfine, PeRep3, 'c--');
legend('CONV. CODE U.B.', 'HAMMING(7,4) U.B.', ...
'HAMMING(7,4) L.B.', 'UNCODED', '3 \times REPETITION CODE')
xlabel('ERROR PROBABILITY FOR BSC (p)')
ylabel('BER')
title('CODES OVER BSC')
axis([1e-4 0.5 1e-8 1])

