clear all
%
n = 5;  % n-bit words sent over BSC
%
% Codewords are
%
x(1) = 0; x(2) = 7; x(3) = 31;
N = length(x);
fprintf('\nThe codewords are:\n\n')
for i = 1:N
   fprintf('x(%d) = %s\n',i,dec2bin(x(i),n))
end
%
% Decoding sets are
%
% D{1} = words with Hamming weight 0 or 1
% D{2} = words with Hamming weight 2 or 3
% D{3} = words with Hamming weight 4 or 5
%
D = cell(1,N);
d = zeros(1,N); % counter for size of each cell
for i = 0:2^n-1
   hw = sum(bitget(i,[1:n])); % Compute Hamming weight
   if hw < 2
      d(1) = d(1) + 1;
      D{1}(d(1)) = i;
   elseif hw < 4
      d(2) = d(2) + 1;
      D{2}(d(2)) = i;
   else
      d(N) = d(N) + 1;
      D{N}(d(N)) = i;
   end
end
fprintf('\nThe decoding sets are:\n\n')
for l = 1:N
   for i = 1:d(l)
      fprintf('D{%d}(%d) = %s\n',l,i,dec2bin(D{l}(i),n))
   end
   fprintf('\n')
end
%
% Compute Prob of correct detection
%
s = 0;
for i = 1:N
   % Compute W^n(y:y in D_i|x_i)
   si = 0;
   for l = 1:d(i)
      prob = W(n,x(i),D{i}(l));
      si = si + prob;
   end
   fprintf('Wn(D{%g}|x(%g)) = %g\n',i,i,si)
   s = s + si;
end
fprintf('\nThe average probability of error is %g\n',1-s/N)
fprintf('\nThe rate of the code is %g.\n\n',log2(N)/n)
