function [Sorted_true_IT_array,dt_array,mean_I_array]=Level_Refining_MOD(I_data,Fit_It,time_data,true_levels)

%Initializing Arrays
I_fit=Fit_It(:,2);
mean_I_array=zeros(1,1);
dt_array=zeros(1,1);
true_IT_array=zeros(1,2);

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);

           I_Fit_array=I_fit(padded_level_pts(i):padded_level_pts(i+1));
           current_level_mean=median(I_Fit_array);

           previos_I_array=I_fit(padded_level_pts(i-1):padded_level_pts(i));
           previous_mean=median(previos_I_array);

           next_I_array=I_fit(padded_level_pts(i+1):padded_level_pts(i+2));
           next_mean=median(next_I_array);

           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)];
           true_IT_array=[true_IT_array;mean_event_data];
           dt_array(i-1)=sub_event_size;
           mean_I_array(i-1)=current_mean;
    end    

   %left_baseline
   event_starting_index=true_levels(1);
   t_data=time_data(1:event_starting_index-1);
   I_array=I_data(1:event_starting_index-1);
   current_level_mean=weighted_mean(I_array);
   sub_event_size=size(t_data,1);
   Left_mean_event_data=[t_data repmat(current_level_mean,sub_event_size,1)];
   
   %right_baseline
   event_ending_index=true_levels(end);
   t_data=time_data(event_ending_index+1:end);
   I_array=I_data(event_ending_index+1:end);
   current_level_mean=weighted_mean(I_array);
   sub_event_size=size(t_data,1);
   Right_mean_event_data=[t_data repmat(current_level_mean,sub_event_size,1)];
   
   true_IT_array=[Left_mean_event_data;true_IT_array(2:end,:);Right_mean_event_data];%there's a zero at the top due to intialization condition.
   [~, ia, ~]=unique(true_IT_array(:,1));
   Sorted_true_IT_array=true_IT_array(ia,:);
end