% MATLAB script for ECS 452 by Asst. Prof. Dr. Prapun Suksompong. 

%% Generating the channel input x
x = randsrc(1,n,[S_X;p_X]); % channel input

%% Applying the effect of the channel to create the channel output y
y = DMC_Channel_sim(x,S_X,S_Y,Q); % channel output

% When the number of symbols are not too large, show the input string and
% output string on the command window
if n < 200
    num2str(x)
    num2str(y)
end

%% Statistical Analysis
% The probability values for the channel inputs
p_X                     % Theoretical probability
p_X_sim = hist(x,S_X)/n % Relative frequencies from the simulation
% The probability values for the channel outputs
q = p_X*Q               % Theoretical probability
q_sim = hist(y,S_Y)/n   % Relative frequencies from the simulation
% The channel transition probabilities from the simulation
Q_sim = [];
for k = 1:length(S_X)
    I = find(x==S_X(k)); LI = length(I);
    rel_freq_Xk = LI/n; 
    yc = y(I);
    cond_rel_freq = hist(yc,S_Y)/LI; Q_sim = [Q_sim; cond_rel_freq];
end
Q                       % Theoretical probability
Q_sim                   % Relative frequencies from the simulation


%% Naive Decoder
x_hat = y;

%% Error Probability
PE_sim = 1-sum(x==x_hat)/n % Error probability from the simulation
% Calculation of the theoretical error probability
PC = 0;
for k = 1:length(S_X)
    t = S_X(k);
    i = find(S_Y == t);
    if length(i) == 1
        PC = PC+ p_X(k)*Q(k,i);
    end
end
PE_theretical = 1-PC
