clc
clear variables
close all
N = 2e+6;
M = 3;
refArray(1) = 1i;
refArray(2) = 1;
refArray(3) = -1i;
data = ceil(M*rand(N,1));
s = refArray(data);
EsN0dB = 0:2:14;


figure(1);
plot(real(s),imag(s),'r*');
title('Constellation diagram for Transmitted Symbols');
xlabel('Inphase component');
ylabel('Quadrature component');
ser = zeros(1, length(EsN0dB));
ser_theory = zeros(1, length(EsN0dB));
ser_bound = zeros(1, length(EsN0dB));
for i=1:length(EsN0dB)
    
    dist = zeros(M, N);
    %-------------------------------------------
    %Channel Noise for various Es/N0
    %-------------------------------------------
    %Adding noise with variance according to the required Es/N0
    E = 10.^(0.1*EsN0dB(i));
    noise = 1/sqrt(2)*(randn(1,N)+1i*randn(1,N));
    y = sqrt(E)*s + noise;
    
    
    r_i = real(y);
    r_q = imag(y);
    
    plot(r_i,r_q,'*');
    title(['Constellation diagram for Received Symbols Es/N0=' num2str(EsN0dB(i)) 'dB']);
    xlabel('Inphase component');
    ylabel('Quadrature component');
    
    % ML detection
    
    for j = 1:M
    dist(j,:) = abs(y - sqrt(E)*refArray(j));
    end
    
    [minValue, ind] = min(dist);
    shat = refArray(ind);    
    errors = (shat ~= s);
    ser(i) = sum(errors)/N;
    ser_theory(i) = 4/3*qfunc(sqrt(E))+2/3*qfunc(sqrt(2*E));
    
end
figure(2);
semilogy(EsN0dB,ser,'r',EsN0dB,ser_theory,'g');hold on;
%legend('64QAM-Theory','64QAM-Sim');
xlabel('Es/N0(dB)');
ylabel('Symbol Error Rate (Ps)');
grid on;