% EX Arm Cavity Length measurement (alog 9626)
% Transfer functions collected by D. Sigg and A. Staley on Jan 29, 2014
% Data consists of FSR frequency(MHz), Magnitude (dB), Phase (deg) 
% These values were measured at 1.3kHz
% Note (12Hz offset): 
%  IFR value:           Timing Comparator Value
%   24.992272            24.992260
%   24.992268            24.992256

c = 299792458;
N = 666; % integers away from FSR

load('Data.txt')
FSR_freq = Data(:,1) .* 1e6; % Hz, this value is multiplied by 666
mag_db = Data(:,2);
phase_deg = Data(:,3);
FSR_freq_scaled = FSR_freq - 24.992272e6;
rel_phase_deg = 25;
proj = cos((phase_deg-25).*pi/180).*db2mag(mag_db);

% cut data
load('Data_Short.txt')
FSR_freq_2 = Data_Short(:,1) .* 1e6; % Hz, this value is multiplied by 666
FSR_freq_2 = FSR_freq_2 - 12; % for 12Hz offset
mag_db_2 = Data_Short(:,2);
phase_deg_2 = Data_Short(:,3);
FSR_freq_scaled_2 = FSR_freq_2 - 24.992271e6;
rel_phase_deg = 25;
proj_2 = cos((phase_deg_2-25).*pi/180).*db2mag(mag_db_2);


lin_fit = polyfit(FSR_freq_scaled_2, proj_2, 1);
lin_reg = polyval(lin_fit, FSR_freq_scaled_2);

zero_cal = -lin_fit(2)/lin_fit(1) + 24.992271e6;

figure(1)
clf;
plot(FSR_freq_scaled_2, proj_2,'*',FSR_freq_scaled_2, lin_reg);
grid on;
set(gcf, 'color', 'w')
xlim([-110,100]); 
ylabel('Magnitude');
xlabel('Frequency Scaled [Hz]');
title('Finding Zero Crossing');

zero_crossing = zero_cal;
FSR_zero_crossing = zero_cal/N;
L = c/(2*FSR_zero_crossing)

% we repeated the above to confirm the zero crossing...
load('Data_2.txt')
FSR_freq_3 = Data_2(:,1) .* 1e6; % Hz, this value is multiplied by 666
FSR_freq_3 = FSR_freq_3 - 12; % for 12Hz offset
mag_db_3 = Data_2(:,2);
phase_deg_3 = Data_2(:,3);
FSR_freq_scaled_3 = FSR_freq_3 - 24.992271e6;
rel_phase_deg = 25;
proj_3 = cos((phase_deg_3-25).*pi/180).*db2mag(mag_db_3);



lin_fit_2 = polyfit(FSR_freq_scaled_3, proj_3, 1);
lin_reg_2 = polyval(lin_fit_2, FSR_freq_scaled_3);

zero_cal_2 = -lin_fit_2(2)/lin_fit_2(1) + 24.992271e6;

figure(2)
clf;
plot(FSR_freq_scaled_3, proj_3, 'o', FSR_freq_scaled_3, lin_reg_2);
grid on;
set(gcf, 'color', 'w')
xlim([-40,30]); 
ylabel('Magnitude');
xlabel('Frequency Scaled [Hz]');
title('Finding Zero Crossing');

zero_crossing_2 = zero_cal_2;
FSR_zero_crossing_2 = zero_cal_2/N;
L_2 = c/(2*FSR_zero_crossing_2)
