% Binary symmetric channel demo (BSC)

% Probability of bit error on BSC

pvec = 0.1:0.1:0.5;   % Vector of p values
Np = length(pvec);    % Number if different p values

M = 3;     % Number of times to repeat bit through channel
RUNs = 100;

for pind = 1:Np
    p = pvec(pind);

error_count = 0;
for run=1:RUNs

% Generate input bit to channel

z = unifrnd(0, 1);
if (z <= 0.5)
    x = 0;
else
    x = 1;
end

% Put x through BSC:

for m=1:1:M

z = unifrnd(0, 1);
if (z <= p)
    y(m) = not(x);
else
    y(m) = x;
end

end  % end for loop over M

xhat = median(y);      % Majority decision/decoding rule

if (xhat ~= x)
    error_count = error_count + 1;
%    fprintf('ERROR\n');
% else
%    fprintf('CORRECT\n');
end

end % end for loop over RUNs

BER(pind) = error_count/RUNs;

fprintf('p = %.2f: %d errors in %d runs => BER = %f\n', p, error_count, ...
    RUNs, BER(pind));


end % end loop over p values

% pfine = 0.01:0.01:0.5;
pfine = logspace(-4, 0, 200);
Pe = pfine.^3 + 3*(pfine.^2).*(1-pfine);

figure(1)
plot(pvec, BER, 'bx', pfine, Pe, 'k-')
xlabel('ERROR PROBABILITY FOR BSC (p)')
ylabel('BER')
title('BER FOR 3-TIMES REP. CODE OVER BSC')

figure(2)
loglog(pvec, BER, 'bx', pfine, Pe, 'k-')
legend('SIMULATION', 'ANALYTICAL')
xlabel('ERROR PROBABILITY FOR BSC (p)')
ylabel('BER')
title('BER FOR 3-TIMES REP. CODE OVER BSC')
