%% Code to generate receive beampatterns for the proposed codebook

clear all
close all
clc


OSR = 4; % oversampling ratio at BS
N_t = 32; 
N_r = (128/OSR)*OSR;
d_r = 0.5/OSR;
d_t = 0.5; % regular array at the transmitter

SNR_dB = 10;
SNR = 10.^(0.1.*SNR_dB);

dod_true = [5];
doa_true = [30];

a_steer_set = [0 0]; % choice of steering angles
lev_set = [1 1 ]; % choice of levels 
s_set = [1 2]; %stages considered

figure

for loop_outer=1:length(a_steer_set) 
    
    a_steer = a_steer_set(loop_outer);  % we ignore angle steering here
    s = s_set(loop_outer);
    L = length(doa_true);
    path_gain_angle = 2*pi*rand(L,1) - pi;
    alpha = ones(L,1).*exp(1j.*path_gain_angle); 
    A_RX = gen_a(N_r,d_r, doa_true);
   
    W_mrc_sd = sqrt(1/N_r).*A_RX;

    Nsnap = 1;

    M = 128;
    K = 2; %  Beams per stage

    ncodes = K^s;
    W = get_code_TX(N_t, d_t, M, K, s);

    phi_d2 = 0:1:360;
    received_pattern = zeros(K,length(phi_d2));


    lev_s2 = lev_set(loop_outer);
    lev_corr_fact = 2 - abs(cosd(- a_steer)) -  abs(sind(-a_steer));
    lev = lev_s2/lev_corr_fact;


    for k =1:ncodes
        a_ref = W(:,k);
        
        for i=1:length(phi_d2)
            dod_true = phi_d2(i);
            A_TX = gen_a(N_t,d_t, dod_true);
            H_true = sqrt(1/L).*A_RX*diag(alpha)*A_TX';
            N_noise = sqrt(1/2).*(randn(N_r,Nsnap) + 1j.*randn(N_r,Nsnap));
            X = sqrt(SNR(1)).*H_true*repmat(a_ref,1,Nsnap) + N_noise;             
            Y = sigma_delta_ADC(X,a_steer,d_r,lev);          
            R_y = (1/Nsnap).*Y*Y';
            received_pattern(k,i) = abs(W_mrc_sd'*R_y*W_mrc_sd);        
        end
    end

subplot(1,length(a_steer_set),loop_outer)
for k=1:ncodes
     polarplot(phi_d2*pi/180,received_pattern(k,:)./(sqrt(N_t)*N_r),'LineWidth',1.2);
    hold on;
end
grid on
title(['\psi = ',num2str(a_steer),'^0, c=1, stage = ',num2str(loop_outer)]);






end

