
datarate = 112e9;
M = 6;
laser_linewidth = 0;
kover = 32;
fsym = round(datarate*1e-9 / log2(M))*1e9;
fdac = 256e9;

% 1) PRBS Generation
O = 18; %order of prbs
N = 2^(O-1); %length of prbs
[~,seed] = prbs(O,1); %initialize first seed of prbs
bitpattern=[];

for i = 1:log2(M)
    [bitpattern(:,i),seed] = prbs(O,N,seed);
end

if M == 6
    bitpattern = reshape(bitpattern,[],1);
    bitpattern = bitpattern(1:end-mod(length(bitpattern),5));
end

% 2 ) Build Inf. signal class
bits = Informationsignal(bitpattern);


alphas = flip([0.01,0.05,0.1,0.2,0.3,0.4]);
LP_awg = Filter('filtdegree',5,"f_cutoff",70e9,"fs",fdac*kover,"filterType",filtertypes.butterworth);
AWG_=AWG("fdac",fdac,"dac_min",-1,"dac_max",1,"H_lpf",LP_awg,"kover",kover,"bit_resolution",16,"lpf_active",1,"normalize2dac",1,"upsampling_method","samplehold");


% 3) Digi modulation -> PAM-M signal
digimod_out = PAMmapper(M,0).map(bits);
digimod_out.fs = fsym;

X = Pulseformer("fsym",fsym,"fdac",fdac,"pulse","rrc","pulselength",16,"rrcalpha",alphas(a)).process(digimod_out);

% plot_eye(X.signal,X.fs,fsym);
% 5) AWG (lowpass, quantization, sample and hold)
X = AWG_.process(X);

f=figure(12);
f.Name = 'spectrum';
spectrum_plot(X.signal,X.fs,'spectrum');

figure(4)
LP_awg.showHere();

disp(['El. power: ',num2str(X.power),' dBm (into 50 Ohm)']);
disp(['El. RMS voltage: ',num2str(sqrt(mean(X.signal.^2))),' V']);
disp(['max voltage: ',num2str(max(X.signal)),' V']);

rms_ = rms(X.signal);
max_ = max(X.signal);
min_ = min(X.signal);
figure(1);
hold on
plot(X.signal,'LineWidth',0.1);
yline([max_, min_],'LineWidth',2,'LineStyle','--');
yline([rms_, -rms_],'LineWidth',2,'LineStyle',':');
ylim([-3 3]);
title(['AWG output: ',num2str(X.power), 'dBm']);

f=figure(12);
f.Name = 'spectrum';
spectrum_plot(X.signal,X.fs,'spectrum');

% 6) Lowpass behavior before laser
LP_modulator= Filter('filtdegree',4,"f_cutoff",70e9,"fs",fdac*kover,"filterType",filtertypes.butterworth);
X =  LP_modulator.process(X);


% 7) Normalize signal to 0dB rms
figure(1);subplot(1,2,1);plot(X.signal,'LineWidth',0.1);ylim([-3 3]);title(['AWG output: ',num2str(X.power), 'dBm into 50 Ohm']);

% 1) Laser; Modulation ->  OPTICAL DOMAIN
u_pi = 2;
vbias = -1;
extmodlaser = EML("mode",eml_mode.im_cosinus,"power",0,"fsimu",X.fs,"lambda",1290,"bias",vbias,"u_pi",u_pi,"linewidth",laser_linewidth,"randomkey",5);

E = X.normalize("mode","oneone");
figure(1);subplot(1,2,2);plot(E.signal,'LineWidth',0.1);ylim([-3 3]);title(['scaled to modulator; ',num2str(E.power), 'dBm']);
disp(['El. power: ',num2str(E.power),' dBm (into 50 Ohm)']);

[Opt,extmodlaser] = extmodlaser.process(E);

f=figure(12);
f.Name = 'spectrum';
spectrum_plot(X.signal,X.fs,'spectrum');

plot_eye(E.signal,E.fs,fsym);

figure(111)
hold on
scatter(E.signal(1:100000),(abs(Opt.signal(1:100000)).^2)*1e3,0.1,'.','DisplayName','Modulator TF')
xlabel('Input in V')
ylabel('Output in mW')







