N = 1000;
np_dBm = -100.0; % noise power in dBm
mlevel = 4;

% signal 
x = round((mlevel-1)*rand(1,N));

% modulation
bitPerSymbol = sqrt(mlevel);
b = -2.*mod(x,(bitPerSymbol))+bitPerSymbol-1;
a = 2.*floor(x./(bitPerSymbol))-bitPerSymbol+1;
xmod = a + i.*b;

%generating noise
np = 10 ^((np_dBm - 30)/10);
rnd = sqrt(np/2);
rnd_phase = 0.01;
noise = rnd*randn(1,length(xmod)) + rnd*randn(1,length(xmod))*j;
phase_noise = rnd_phase*randn(1,length(xmod)) + rnd_phase*randn(1,length(xmod))*j;
phase_shift = exp(phase_noise.*pi*j);

%adding noise to the modulated signal
xmod_no = (xmod + noise).*phase_shift;


xmod_no_2layer = reshape(xmod_no,2,[]);
cb_01 = 1/sqrt(2).*[1;1]; 
cb_11 = 1/sqrt(2).*[1;-1];
cb_21 = 1/sqrt(2).*[1;j];
cb_31 = 1/sqrt(2).*[1;-j];

cb_02 = 1/sqrt(2).*[1 0;0 1];
cb_12 = 1/2.*[1 1;1 -1];
cb_22 = 1/2.*[1 1;j -j];

xmod_no_2layer_cb_02 = cb_02 * xmod_no_2layer;
xmod_no_2layer_cb_02 = reshape(xmod_no_2layer_cb_02,1,[]);

figure;
subplot(2,2,1); plot(real(xmod),imag(xmod),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('A');
subplot(2,2,2); plot(real(xmod_no),imag(xmod_no),'ro'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('B');
subplot(2,2,3); plot(real(xmod_no_2layer_cb_02),imag(xmod_no_2layer_cb_02),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('C');
subplot(2,2,4); plot(real(xmod_no),imag(xmod_no),'ro', real(xmod_no_2layer_cb_02),imag(xmod_no_2layer_cb_02),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('D');


xmod_no_2layer_cb_12 = cb_12 * xmod_no_2layer;
xmod_no_2layer_cb_12 = reshape(xmod_no_2layer_cb_12,1,[]);

figure;
subplot(2,2,1); plot(real(xmod),imag(xmod),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('A');
subplot(2,2,2); plot(real(xmod_no),imag(xmod_no),'ro'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('B');
subplot(2,2,3); plot(real(xmod_no_2layer_cb_12),imag(xmod_no_2layer_cb_12),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('C');
subplot(2,2,4); plot(real(xmod_no),imag(xmod_no),'ro', real(xmod_no_2layer_cb_12),imag(xmod_no_2layer_cb_12),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('D');


xmod_no_2layer_cb_22 = cb_22 * xmod_no_2layer;
xmod_no_2layer_cb_22 = reshape(xmod_no_2layer_cb_22,1,[]);

figure;
subplot(2,2,1); plot(real(xmod),imag(xmod),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('A');
subplot(2,2,2); plot(real(xmod_no),imag(xmod_no),'ro'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('B');
subplot(2,2,3); plot(real(xmod_no_2layer_cb_22),imag(xmod_no_2layer_cb_22),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('C');
subplot(2,2,4); plot(real(xmod_no),imag(xmod_no),'ro', real(xmod_no_2layer_cb_22),imag(xmod_no_2layer_cb_22),'bo'); axis([-mlevel/2 mlevel/2 -mlevel/2 mlevel/2]);title('D');

