% Brief summary of this function.
% Detailed explanation of this function.

function  [ber] = imdd_example_live(varargin)
    
    curFolder = pwd;
    funcFolder=fileparts(mfilename('fullpath'));
    if ~isempty(funcFolder)
        cd(funcFolder);
    end
    
    parameters;

    % Parse optional input arguments
    if ~isempty(varargin)
        var_s = varargin{1};
        if isstruct(var_s)
            fields = fieldnames(var_s);
            for i = 1:numel(fields)
                eval([fields{i}, ' = ',  num2str( var_s.(fields{i}) ), ';']);
                fprintf("%s <-- %.2f \n", fields{i}, var_s.(fields{i}));
            end
        else
            error('Optional variables should be passed as a struct.');
        end
    end

    

    Pform       = Pulseformer("fsym",fsym,"fdac",4*fsym,"pulse","rrc","pulselength",16,"rrcalpha",rcalpha);

    [Digi_sig,Symbols,Bits] = PAMsource(...
        "fsym",fsym,"M",M,"order",19,"useprbs",1,...
        "fs_out",fdac,...
        "applyclipping",0,"clipfactor",1.5,...
        "applypulseform",apply_pulsef,"pulseformer",Pform,...
        "randkey",random_key,...
        "db_precode",db_precode,"db_encode",db_encode,...
        "mrds_code",0,"mrds_blocklength",512).process();

    Digi_sig.spectrum("displayname",'Digi Spectrum','fignum',10,'normalizeTo0dB',1);

    %%%%% AWG
    % El_sig = M8199A("kover",kover).process(Digi_sig);
    El_sig = AWG("fdac",fdac,"f_cutoff",fsym,"lpf_active",0,"kover",kover,"bit_resolution",12,"upsampling_method","samplehold","precomp_sinc_rolloff",1).process(Digi_sig);
    % El_sig.spectrum("displayname",'Digi Spectrum','fignum',100,'normalizeTo0dB',0);
    % El_sig = El_sig.setPower(0,"dBm");

    %%%%% Low-pass el. components %%%%%%
    El_sig = Filter('filtdegree',4,"f_cutoff",tx_bw_nyquist.*f_nyquist,"fs",fdac*kover,"filterType",filtertypes.butterworth,"active",true).process(El_sig);
   
    %%%%% Electrical Driver Amplifier %%%%%%
    El_sig = Amplifier("amp_mode","ideal_no_noise","gain_mode","gain","amplification_db",3).process(El_sig);
    El_sig = El_sig.normalize("mode","oneone");

    %%%%% MODULATE E/O CONVERSION %%%%%%
    [Opt_sig] = EML("mode",eml_mode.im_cosinus,"power",3,"fsimu",El_sig.fs,"lambda",laser_wavelength,"bias",vbias,"u_pi",u_pi,"linewidth",laser_linewidth,"randomkey",random_key+1).process(El_sig);

    %%%%%% Fiber %%%%%%
    Opt_sig    = Fiber("fsimu",Opt_sig.fs,"fiber_length",link_length/1000,"alpha",0.3,"D",0,"lambda0",1310,"gamma",0,"Dslope",0.07).process(Opt_sig);

    %%%%%% ROP %%%%%%
    Rx_sig = Amplifier("amp_mode","ideal_no_noise","gain_mode","output_power","amplification_db",rop).process(Opt_sig);

    

    %%%%%% PD Square Law %%%%%%
    Rx_sig = Photodiode("fsimu",fdac*kover,"dark_current",2e-08,"responsivity",1,"temperature",20,"nep",1.8e-11).process(Rx_sig);

    
    %%%%%% Low-pass RX (PD, El. Connectors and Scope %%%%%%
    Rx_sig = Filter('filtdegree',4,"f_cutoff",rx_bw_nyquist.*f_nyquist,"fs",fdac*kover,"filterType",filtertypes.butterworth,"active",true).process(Rx_sig);

    % %%%%%% Low-pass Scope %%%%%%
    %dactivated in scope module!
    Lp_scpe = Filter('filtdegree',4,"f_cutoff",10e9,"fs",fadc,"filterType",filtertypes.butterworth,"active",true);

    % Rx_sig.spectrum("displayname",'Analog Rx Spectrum','fignum',100,'normalizeTo0dB',1);

    %%%%%% Scope %%%%%%
    Scpe_sig = Scope("fsimu",fdac*kover,"fadc",fadc,...
        "delay",0,"fixed_delay",0,"filtertype",filtertypes.butterworth,...
        "samplingdelay",0,"rand_samplingdelay",0,"freq_offset",0,"samp_jitter",0,...
        "adcresolution",8,"quantbuffer",0.1,'block_dc',1,'lpf_active',0,'H_lpf',Lp_scpe).process(Rx_sig);

    % Scpe_sig.spectrum("displayname",'Digital (256 GSa/s) Rx Spectrum','fignum',100,'normalizeTo0dB',1);

    %%%%%% Sample to 2x fsym %%%%%%
    Scpe_sig =  Scpe_sig.resample("fs_in",fadc,"fs_out",2*fsym);

    %%%%%% Sync Rx signal with reference %%%%%%
    [Scpe_sig,S] = Scpe_sig.tsynch("reference",Symbols,"fs_ref",fsym);

    Scpe_sig.spectrum("displayname",'Prior DSP (2x fsym) Spectrum','fignum',100,'normalizeTo0dB',1);
    
    %%% EQUALIZING
    ber = struct();
    switch eq_mode

        case equalizer_structure.ffe

            %FFE
            if db_precode
                Bits_ = PAMmapper(M,0).demap(Symbols);
            else
                Bits_ = Bits;
            end

            eq_ffe = EQ("Ne",ffe_order,"Nb",dfe_order,"training_length",len_tr,"training_loops",5,"dd_loops",5,"K",2,"DCmu",mu_dc,"DDmu",[mu_ffe mu_dfe],"DFEmu",0.005,"FFEmu",0,"plotfinal",0,"ideal_dfe",1);
            % eq_ffe     = FFE("epochs_tr",5,"epochs_dd",5,"len_tr",len_tr,"mu_dd",mu_ffe(1),"mu_tr",0,"order",ffe_order(1),"sps",2,"decide",0);
            % eq_ffe     = FFE_DCremoval("epochs_tr",5,"epochs_dd",5,"len_tr",len_tr,"mu_dd",mu_ffe(1),"mu_tr",0,"order",ffe_order(1),"sps",2,"decide",0,"dc_buffer_len",512,"mu_dc",0.05);

            [eq_sig,eq_noise,ber.ber_ffe,totalErrors] = vnle( eq_ffe,M,Scpe_sig ,Symbols, Bits_);
            eq_noise.spectrum("displayname",'Noise Spectrum after FFE','fignum',41,'normalizeTo0dB',0);

        case equalizer_structure.vnle

            if db_precode
                Bits_ = PAMmapper(M,0).demap(Symbols);
            else
                Bits_ = Bits;
            end


            %VNLE
            eq_vnle = EQ("Ne",vnle_order,"Nb",dfe_order,"training_length",len_tr,"training_loops",5,"dd_loops",5,"K",2,"DCmu",mu_dc,"DDmu",[mu_ffe mu_dfe],"DFEmu",0.005,"FFEmu",0,"plotfinal",0,"ideal_dfe",1);
            [eq_sig,eq_noise,ber.ber_vnle,totalErrors] = vnle(eq_vnle,M,Scpe_sig ,Symbols, Bits_);
            eq_noise.spectrum("displayname",'Noise Spectrum after VNLE','fignum',41,'normalizeTo0dB',0);
        case equalizer_structure.vnle_pf_mlse

            if db_precode
                Bits_ = PAMmapper(M,0).demap(Symbols);
            else
                Bits_ = Bits;
            end

            %VNLE + PF + MLSE
            eq_mlse     = EQ("Ne",vnle_order,"Nb",dfe_order,"training_length",len_tr,"training_loops",5,"dd_loops",5,"K",2,"DCmu",mu_dc,"DDmu",[mu_ffe mu_dfe],"DFEmu",0.005,"FFEmu",0,"plotfinal",0,"ideal_dfe",1);
            eq_mlse     = FFE_DCremoval("epochs_tr",5,"epochs_dd",5,"len_tr",len_tr,"mu_dd",mu_ffe(1),"mu_tr",0,"order",ffe_order(1),"sps",2,"decide",0,"dc_buffer_len",512,"mu_dc",0.05);
            eq_mlse     = FFE("epochs_tr",5,"epochs_dd",5,"len_tr",len_tr,"mu_dd",mu_ffe(1),"mu_tr",0,"order",ffe_order(1),"sps",2,"decide",0);
          
            pf_         = Postfilter("ncoeff",1);
            mlse_       = MLSE("DIR",[0,0],"duobinary_output",0,"M",[],"trellis_states",[]);
            [eq_sig,eq_noise,ber.ber_mlse,totalErrors] = vnle_postfilter_mlse(eq_mlse , pf_, mlse_,M, Scpe_sig ,Symbols, Bits_);
            pf_.showFilter(eq_noise);
            eq_noise.spectrum("displayname",'Noise Spectrum after VNLE+PF','fignum',41,'normalizeTo0dB',0);
        case equalizer_structure.db_precoded

            %EQ targets DB => less precompensation; pre-coded
            mlse_db_pre = MLSE("DIR",[1,1],"duobinary_output",1,"M",M,"trellis_states",PAMmapper(M,0).levels);
            eq_db_pre = EQ("Ne",vnle_order,"Nb",dfe_order,"training_length",len_tr,"training_loops",5,"dd_loops",5,"K",2,"DCmu",mu_dc,"DDmu",[mu_ffe mu_dfe],"DFEmu",0.005,"FFEmu",0,"plotfinal",0,"ideal_dfe",1);
            [eq_sig,eq_noise,ber.ber_db,totalErrors] = duobinary_target(eq_db_pre, mlse_db_pre,M, Scpe_sig ,Symbols, Bits);
            eq_noise.spectrum("displayname",'Noise Spectrum after DB','fignum',41,'normalizeTo0dB',0);
            %->append BER to DB

        case equalizer_structure.db_encoded

            %db signaling => db encoded
            mlse_db_enc = MLSE("DIR",[1,1],"duobinary_output",1,"M",M,"trellis_states",PAMmapper(M,0).levels);
            eq_db_enc = EQ("Ne",vnle_order,"Nb",dfe_order,"training_length",len_tr,"training_loops",5,"dd_loops",5,"K",2,"DCmu",mu_dc,"DDmu",[mu_ffe mu_dfe],"DFEmu",0.005,"FFEmu",0,"plotfinal",0,"ideal_dfe",1);
            [eq_sig,eq_noise,ber.ber_db_enc,totalErrors] = duobinary_signaling(eq_db_enc, mlse_db_enc,M, Scpe_sig ,Symbols, Bits);
            %->append BER to DB
    end

    fprintf('BER FFE: %.2e \n',ber.ber_mlse);
    % % El_sig.spectrum("displayname",'Tx Spectrum','fignum',10,'normalizeTo0dB',1);
    % Scpe_sig.spectrum("displayname",'Rx Spectrum','fignum',100,'normalizeTo0dB',1);
    
    
    
    
    if ~isempty(curFolder)
        cd(curFolder);
    end
end