%% CLF transfer function 120uW trans
%% load data

CLFTF_amp = load('CLF_TFamp_Oct312019.TXT'); 
CLFTF_phase = load('CLF_TFph_Oct312019.TXT');
CLFTF_ampx = CLFTF_amp(:,1); %freq
CLFTF_ampy = CLFTF_amp(:,2); %amp
CLFTF_phy = CLFTF_phase(:,2); %phase

CLFTFamp = 10.^(CLFTF_ampy/20); %dB to power ratio
CLFcmplx = CLFTFamp.*exp(i.*deg2rad(CLFTF_phy)); 
CLFOLmag = abs(CLFcmplx);
CLFOLphase = angle(CLFcmplx);

%% Generic common mode board components

VCXOV2Hz = 925; %Hz/V calibration for CLF AOM

CLF_CMgain = 0.35; %-9dB
CLF_fastgain = 1.99; %6dB
CLF_cal = 2.9; %RF6 -3dBm, 2.9Vpp measured at -2dBm. close enough

CM_comp = zpk(-2.*pi.*[4e3  ], -2*pi.*[40 ], 1);
CM_boost1 = zpk(-2.*pi.*[10  ], -2*pi.*[0 ], 1);
CM_boost2 = zpk(-2.*pi.*[2e3  ], -2*pi.*[20 ], 1);
SLOW_boost = zpk(-2.*pi.*[400  ], -2*pi.*[4 ], 1);
SLOW_filters = zpk(-2.*pi.*[  ], -2*pi.*[100e3 ], 100e3*2*pi);
PZTdriver = zpk(-2.*pi.*[  10 ],...
            -2*pi.*[ 1 400], (1/10)*400*20); %PZTdriver gain = 20
%PFD = zpk(-2.*pi*[],-2.*pi*[0], 1.6*2.*pi); %1.6V/rad, 32deg/V, has to be measured in the lab
%PZT = zpk([],[], 10.6e6); %PZT calibration Hz/V
%PM = zpk(-2*pi*[60],-2*pi*[10], (1/60)*10*.00136); %Pomonabox. No longer
%used

%% CLF stuff

VCXOV2Hz = 925; %Hz/V calibraitno for CLF AOM done at 3MHz

flat = zpk([],[], 2*VCXOV2Hz); %Hz/V factor of 2 because calibrated at 3MHz but used for 6MHz
oneonf = zpk([],-2*pi*[0], 2*pi ); %phase detection frequency actuation

%VCO = zpk(-2*pi*[ 40],-2*pi*[1.6], 281479.*(1/40).*1.6); %Hz/V 80MHz VCO calibration at DC
mysteriouspole = zpk([],-2*pi*[5e3 30e3], (2*pi)^2*5e3*20e3 ); %prob VCXO

common_path = CLF_CMgain.*CM_boost1.*CM_boost2;
fast_path = flat*oneonf*mysteriouspole; 

CLF_TF = CLF_cal*common_path.*fast_path;


[CLFamp, CLFphase] = bode(CLF_TF, 2*pi*CLFTF_ampx); 
CLFamp = squeeze(CLFamp);
CLFphase = squeeze(CLFphase);
CLFfilter = CLFamp.*exp(i.*deg2rad(CLFphase));
CLFOLmagzpk = abs(CLFfilter);
CLFOLphasezpk = angle(CLFfilter);

%% Plot CLF TF
figure(228);
subplot(2,1,1);
semilogx(CLFTF_ampx, 20*log10(CLFOLmag),...
    CLFTF_ampx, 20*log10(CLFOLmagzpk), '--', 'LineWidth', 1.5, 'Color', [0.8500 0.3250 0.0980]);
xlabel('Frequency, Hz'), ylabel('Gain, dB');
ylim([-80,60])
xlim([1e2,1e5])
legend('Measured', 'Calculated')
title('CLF TF Oct 31, 2019');
grid on;
subplot(2,1,2);
semilogx(CLFTF_ampx, rad2deg(CLFOLphase),...
    CLFTF_ampx, rad2deg(CLFOLphasezpk),'--', 'LineWidth', 1.5, 'Color', [0.8500 0.3250 0.0980]);
xlabel('Frequency, Hz'), ylabel('Phase, deg.');
xlim([1e2,1e5])
grid on;

