% Binary symmetric channel with 3-times repetition code.
%
% R. Kozick, Sept. 2001

% Probability of bit error on BSC

% pvec = 0.1:0.1:0.5;   
pvec = logspace(-3, 0, 12);    % Vector of p values
zi = find(pvec <= 0.5);        % Keep only the values <= 0.5
pvec = pvec(zi);
Np = length(pvec);             % Number of different p values
Np = Np+1;
pvec(Np) = 0.5;                % Add p=0.5 to end of vector

M = 3;        % Number of times to repeat bit through channel
RUNs = 1e4;
return
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);
zi = find(pfine <= 0.5);
pfine = pfine(zi);
Pe = pfine.^3 + 3*(pfine.^2).*(1-pfine);

figure(1)
plot(pvec, BER, 'bo:', pfine, Pe, 'k-', pfine, pfine, 'r-')
legend('SIMULATION', 'ANALYTICAL', 'UNCODED')
xlabel('ERROR PROBABILITY FOR BSC (p)')
ylabel('BER')
title('BER FOR 3-TIMES REP. CODE OVER BSC')

figure(2)
loglog(pvec, BER, 'bo:', pfine, Pe, 'k-', pfine, pfine, 'r-')
legend('SIMULATION', 'ANALYTICAL', 'UNCODED')
xlabel('ERROR PROBABILITY FOR BSC (p)')
ylabel('BER')
title('BER FOR 3-TIMES REP. CODE OVER BSC')
axis([1e-4 0.5 1e-7 1])

save bsckoz_out.mat
