% This script looks at how long the SUS lock channels take until they are turn off
% after lock loss. There is an option to indicate how many seconds after
% lockloss to query per channel.

% We will import the new list of channels of interest that do not include
% L3 channels for QUAD suspensions with exception of ETMY:

fid = fopen('Doing_similar_for_H1/H1_SUS_channels_for_analysis.txt');
seconds_before_lockloss = 10; % number of seconds before lockloss to query
seconds_after_lockloss = 80;  % number of seconds after lockloss to query

SUS_channels = {};
i = 1;
tline = fgetl(fid);
while ischar(tline)
    disp(tline);
    SUS_channels{i}=tline;
    tline = fgetl(fid);
    i = i+1;
end
fclose(fid);
clear tline

% Segment times: two collumns: Start_lock End_lock
Segments = importdata('Doing_similar_for_H1/Segments_Lownoise_LOCK_NOMINAL_starttime_endtime_from_20161022_till_20161210_H1.txt');
Seg_diff = Segments(:,2)-Segments(:,1);
Ind = find(Seg_diff>=15);
Segments = Segments(Ind, :);

% Query the data using GWData, in particular 'get_data'
GWData.make_kerberos_ready;
data = cell(1,length(Segments));
h_aux = sprintf('Querying data of %d segments for %d channels', length(Segments), length(SUS_channels));
h = waitbar(0, h_aux);
for i = 1:length(Segments)
    try
        % NOTE: IMPORTANT for data request errors:
        % Some data segments may not exist so in that case we catch the
        % error letting the corresponding data{i} = [] empty.
        [data{i}, t] = get_data(Segments(i, 2)-seconds_before_lockloss, Segments(i, 2)+seconds_after_lockloss, SUS_channels);
    catch err
        data{i} = [];
        fprintf(1,'ERROR: Data segment %d does not exist\n%s\nMove to next segment...\n', i, err.message);
    end
    h_aux = sprintf('Querying data of segment %d of %d for %d channels...', i, length(Segments), length(SUS_channels));
    waitbar(i/length(Segments), h, h_aux);
end
sampling_period = t(2) - t(1);
close(h);
clear h_aux

% Create range of all channels for all data segments, making it zero for
% those empty data segments. It will be a matrix of dimensions: Segments x Channels
range_data = zeros(length(Segments),length(SUS_channels));
for i = 1:length(Segments)
    if ~isempty(data{i})
        for j = 1:length(SUS_channels)
        	range_data(i,j) = range(data{i}(:,j));
        end
    end
end

% Find the column index of those channels whose range is not always zero
% for all data segments:
Channel_Ind_Range_Nonzero = [];
for i = 1:length(SUS_channels)
    if (any(range_data(:,i) ~= 0))
    Channel_Ind_Range_Nonzero = [Channel_Ind_Range_Nonzero; i];
    end
end

% Plot the nonzero ranges in figures grouped per Suspension channels, when more than 10 then 
% use another figure, label the figure with suspension name.
% First identify how many channels per suspension:
plot_suspensions = {};
I_SUSChan = {};
for i =1:length(Channel_Ind_Range_Nonzero)
    aux_sus = strtok(SUS_channels{Channel_Ind_Range_Nonzero(i)}(8:end), '_');
    [answer, Loc] = ismember(aux_sus, plot_suspensions);
    if answer
        I_SUSChan{Loc} = [I_SUSChan{Loc}(:); Channel_Ind_Range_Nonzero(i)];
    else
        plot_suspensions = {plot_suspensions{:}, aux_sus};
        I_SUSChan = {I_SUSChan{:}, (Channel_Ind_Range_Nonzero(i))};
    end
end

% How long do the channels in 'Channel_Ind_Range_Nonzero' take to turn off after a lockloss:
% We will be reading from the end of the queried segment (no less than 40
% secs after lockloss) which should be zero once channel is turned off:

% We will store the seconds from lockloss on a matrix same dimensions than
% 'range_data' (segment, channel) which we initiate to -1 to allow for zero
% seconds turn off, that is turn off just after lockloss:
turnoff_secs = -1*ones(size(range_data));
Ind_lockloss = seconds_before_lockloss / sampling_period;
for i = 1:length(Segments)
    if ~isempty(data{i})
        for j = 1:length(Channel_Ind_Range_Nonzero)
        	Ind = find(data{i}(:,Channel_Ind_Range_Nonzero(j)), 1, 'last');
            if ~isempty(Ind)
                turnoff_secs(i, Channel_Ind_Range_Nonzero(j)) = t(Ind) - t(Ind_lockloss);
            else
                turnoff_secs(i, Channel_Ind_Range_Nonzero(j)) = -10; % It corresponds to the case when the
                % channel is all zero.
            end
        end
    end
end
turnoff_secs_median = median(turnoff_secs); % It calculates de median of each column of 'turnoff_secs'
% therefore the median of the number of seconds to turn off from lockloss of all the segments per channel.

% We will have figure of 3x3 grids, with each subplot showing 'time to zero' plots of
% channels for same suspension and no more than 10 plots per subplot.
% Number of figures required:
fig_h=[];
fig_name = 'Segment number VS Time to zero from lockloss';
fig_h_aux = figure('Name', fig_name,'Position',[32 183 1409 622]);
fig_h = [fig_h, fig_h_aux];
subplot_rows = 2;
subplot_cols = 3;
plot_per_fig = 9;
colors = {'y', 'm', 'c', 'r', 'g', 'b', 'k', [0.5 0.5 0.5], [0.5 0 0.5]};

total_subplots = subplot_rows * subplot_cols;
i = 1;
j = 1;
k = 1;
chan = 1;
aux_cell = {};
while chan <= length(I_SUSChan) 
    if i <= total_subplots
        subplot(subplot_rows, subplot_cols, i);
        if k+plot_per_fig-1 < length(I_SUSChan{chan})
            %plot(turnoff_secs(:, I_SUSChan{chan}(k:k+plot_per_fig-1)));
            aux_cell = cell(1, 2*plot_per_fig);
            for n=k:k+plot_per_fig-1
                hold on
                plot(turnoff_secs(:, I_SUSChan{chan}(n)), 'Color', colors{n-k+1});
                aux_cell{2*(n-k) + 1} = SUS_channels{I_SUSChan{chan}(n)};
                line([1 length(Segments)],[turnoff_secs_median(I_SUSChan{chan}(n)) turnoff_secs_median(I_SUSChan{chan}(n))], 'Color',  colors{n-k+1}, 'LineStyle', '--');
                aux_cell{2*(n-k) + 2} = ['Median-' SUS_channels{I_SUSChan{chan}(n)}];
            end
            title(plot_suspensions{chan})
            k = k+plot_per_fig;
        else
            %plot(turnoff_secs(:, I_SUSChan{chan}(k:end)));
            aux_cell = cell(1, 2*(length(I_SUSChan{chan}) - k + 1));
            for n=k:length(I_SUSChan{chan})
                hold on
                plot(turnoff_secs(:, I_SUSChan{chan}(n)), 'Color', colors{n-k+1});
                aux_cell{2*(n-k) + 1} = SUS_channels{I_SUSChan{chan}(n)};
                line([1 length(Segments)],[turnoff_secs_median(I_SUSChan{chan}(n)) turnoff_secs_median(I_SUSChan{chan}(n))], 'Color',  colors{n-k+1}, 'LineStyle', '--');
                aux_cell{2*(n-k) + 2} = ['Median-' SUS_channels{I_SUSChan{chan}(n)}];
            end
            title(plot_suspensions{chan})
            chan = chan+1;
            k = 1; % Restart counting.
        end
        for m= 1:length(aux_cell)
            aux_cell{m} = strrep(aux_cell{m}, '_', '\_');
        end
        axis tight;
        legend(aux_cell, 'FontSize', 8)
        %legend('hide');
        i = i+1;
    else
        fig_h_aux = figure('Name', fig_name,'Position',[32 183 1409 622]);
        fig_h = [fig_h, fig_h_aux];
        i = 1; % Restart counting.
    end
end

clear Ind
