% MC Cavity Length measurement (alog 9626)
% Transfer functions collected by A. Staley on Jan 30, 2014
% Data consists of FSR frequency(MHz), Magnitude (dB), Phase (deg) 
% These values were measured at 1.6kHz


c = 299792458;
N = [1 5]; % integers away from FSR

% TF collected w/ ch2 from REFL9 (1 FSR away)
load('Data.txt')
FSR_freq = Data(:,1) .* 1e6; % Hz
mag_db = Data(:,2);
phase_deg = Data(:,3);
FSR_freq_scaled = FSR_freq - 9.099172e6;
proj = cos((phase_deg-66).*pi/180).*db2mag(mag_db);

% cut data
load('Data_Short.txt')
FSR_freq_2 = Data_Short(:,1) .* 1e6; % Hz
%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 - 9.099172e6;
proj_2 = cos((phase_deg_2-66).*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) + 9.099172e6;

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

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

% from REFL45
load('Data_2.txt')
FSR_freq_3 = Data_2(:,1) .* 1e6 *5; % Hz, this value is multiplied by 5
%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 - (5*9.099172e6);
proj_3 = cos((phase_deg_3-66).*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) + (5*9.099172e6);

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

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