function PE = PE_minDist(C,p)
% Function PE_minDist computes the error probability P(E) when code C
% is used for transmission over BSC with crossover probability p.
% Code C is defined by putting all its (valid) codewords as its rows.
M = size(C,1); % the number of (valid) codewords
k = log2(M);
n = size(C,2); 

% Generate all possible n-bit received vectors
Y = dec2bin(0:2^n-1)-'0';

% Normally, we need to construct an extended Q matrix. However, because
% each conditional probability in there is a decreasing function of the
% (Hamming) distance, we can work with the distances instead of the
% conditional probability. In particular, instead of selecting the max in
% each column of the Q matrix, we consider min distance in each column.
dminy = zeros(1,2^n); % preallocation
for j = 1:(2^n)
    % for each received vector y,
    y = Y(j,:);
    % find the minimum distance 
    % (the distance from y to the closest codeword)
    d = sum(mod(bsxfun(@plus,y,C),2),2);
    dminy(j) = min(d);
end

% From the distances, calculate the conditional probabilities.
% Note that we compute only the values that are to be selected (instead of
% calculating the whole Q first).
n1 = dminy; n0 = n-dminy;
Qmax = (p.^n1).*((1-p).^n0);
% Scale the conditional probabilities by the input probabilities and add 
% the values. Note that we assume equally likely input.
PC = sum((1/M)*Qmax);
PE = 1-PC;
end