function [BSL,BSR,dt_array,mean_I_array]=Level_Refining_Light(I_data,BSL,mean_I_array,BSR,time_data,true_levels)

%Initializing Arrays
I_fit=[BSL;mean_I_array;BSR];
mean_I_array=zeros(1,1);
dt_array=zeros(1,1);

padded_level_pts=sort([1;true_levels;size(I_data,1)]);%padding is done for the ease of accounting for the baseline points later in the for loop
starting_levels=size(padded_level_pts,1)-1;

   
    for i=2:starting_levels-1

           t_data=time_data(padded_level_pts(i):padded_level_pts(i+1));
           I_array=I_data(padded_level_pts(i):padded_level_pts(i+1));
           sub_event_size=size(t_data,1);

           current_level_mean=I_fit(i);
           previous_mean=I_fit(i-1);
           next_mean=I_fit(i+1);

           if current_level_mean<previous_mean && current_level_mean<next_mean
                   %downward pulse like event
                    current_mean=Level_Mean_Universal(I_array);

               elseif current_level_mean>previous_mean && current_level_mean>next_mean %upwards. These are typically sharp
                    %upward pulse like event
                    current_mean=Level_Mean_Universal(I_array);
               else
                    %intermediate level rather than a peak or a valley
                    current_mean=Level_Mean_Universal(I_array);
           end

           %Saving data
           mean_event_data=[t_data repmat(current_mean,sub_event_size,1)];
           dt_array(i-1)=sub_event_size;
           mean_I_array(i-1)=current_mean;
    end    

   %left_baseline
   event_starting_index=true_levels(1);
   I_array=I_data(1:event_starting_index);
   BSL=weighted_mean(I_array);
   
   %right_baseline
   event_ending_index=true_levels(end);
   I_array=I_data(event_ending_index:end);
   BSR=weighted_mean(I_array);
 
end