% add path to Dttdata
addpath /ligo/svncommon/IscSVN/iscmodeling/trunk/DttData
meas_dtt = DttData('CHARD_Y_OLG_SS_2W.xml');
[meas.F,meas.TF] = meas_dtt.transferFunction('H1:ASC-CHARD_Y_IN2','H1:ASC-CHARD_Y_IN1');

addpath(genpath('/ligo/svncommon/MatlabTools/'));

% Time from which to look at the control filter
filter_time = 1219697417; %1176153508; %1155950008; %1155952008;%1151686815;% tconvert('4 July 2016 17:00:00');

% If we've already downloaded Foton files from that time, use them. Otherwise, fetch.
if exist(['./filter_files/h1_filter_files_' num2str(filter_time) '/h1_archive/'],'dir') ~= 0
    disp('Loading locally saved filter files...');
    filt_dir = ['./filter_files/h1_filter_files_' num2str(filter_time) '/h1_archive/'];
else
    disp('Fetching new filter files...');
    [filt_dir, result, command] = GWFilt.CDS_fetch_files('H1', filter_time, './filter_files', true);
end

disp('Loading saved filters');
[~,flt_ASC,  ~] = GWFilt.CDS_load([filt_dir '/H1ASC.txt'], {'ASC-DHARD_Y', 'ASC-DHARD_P', 'ASC-CHARD_Y', 'ASC-CHARD_P'});

boost = GWFilt.CDS_merge(flt_ASC.ASC_CHARD_Y, 1, [4]).get_zpk;
[boost_mag, boost_phase] = bode(boost, 2*pi*meas.F);

new_loop = meas.TF.*10.*(squeeze(boost_mag).*exp(1i*pi*squeeze(boost_phase)/180));

% get the closed loop gain
cl_meas = 1./(1-meas.TF);
cl_new = 1./(1-new_loop);



figure(1)
subplot(2,1,1)
loglog(meas.F, abs(meas.TF), '.',...
    meas.F, abs(new_loop), 'o')
title('open loop gain')
xlim([0.4, Inf])
legend('Current loop', 'add boost and 20 dB gain',...
    'FontSize', 15)
grid on
subplot(2,1,2)
semilogx(meas.F, (180/pi)*angle(meas.TF),'.',...
    meas.F, (180/pi)*angle(new_loop), 'o')
grid on
xlim([0.4, Inf])

print('-dpng', 'CHARD_Y_OLG.png')
figure(2)
subplot(2,1,1)
loglog(meas.F, abs(cl_meas), '.',...
    meas.F, abs(cl_new), 'o')
grid on
xlim([0.4, Inf])
title('Closed loop response')
legend('Current loop', 'add boost and 20dB gain', ...
    'FontSize', 15)
subplot(2,1,2)
semilogx(meas.F, (180/pi)*angle(cl_meas),'.',...
    meas.F, (180/pi)*angle(cl_new), 'o')
grid on
xlim([0.4, Inf])

print('-dpng', 'CHARD_Y_closed_loop.png')