function [z_deriv_new, x_deriv_new] = filter_slope(thresholdFlatDuration, z_deriv, x_deriv, degree)
%%  It finds sequence of points with 0 derivatives   
%   If the sequence consists of number of points bigger than the "thresholdFlatDuration" then: 
%   1. In case of first derivative  (degree=1), the profile seaward than the sequence and the sequence are deleted.
%   2. In case of second derivative (degree=2), zeros are assigned at the second derivative for this area. 

%   --------------------------------------------------------------------
% input:

% thresholdFlatDuration   =  if there are flat stretches longer than this
%                            threshold, the profil more seaward than that is deleted
% z_deriv                 =  vertical values of the derivative
% x_deriv                 =  cross shore location of the derivative 
% degree                  =  degree of the derivative: degree=1, if the input values refer to the first derivative 
%                                                      degree=2, if the input values refer to the second derivative 
%
% output:
% z_deriv_new             =  updated values for the derivative
% x_deriv_new             =  updated values for the cross shore distance

%   --------------------------------------------------------------------
% $Id: $
% $Date: $
% $Author: $
% $Revision: $
% $HeadURL: $
% $Keywords: $
%%
dummy                        =  z_deriv;
dummy(abs(dummy) > 0)        =  1;   
dsig                         =  diff([1 dummy 1]);
startIndex                   =  find(dsig < 0);
endIndex                     =  find(dsig > 0) - 1;
duration                     =  endIndex - startIndex + 1;
stringIndex                  =  (duration >= thresholdFlatDuration);
startIndex                   =  startIndex(stringIndex);
startIndex(startIndex == 1)  =  [];

if ~isempty(startIndex)
    
    if degree == 1
        id_break        =  startIndex(1);
        x_deriv_new     =  x_deriv(1 : id_break);
        z_deriv_new     =  z_deriv(1 : id_break);
    elseif degree == 2
        z_deriv(startIndex(1) : end) =  0;
        z_deriv_new     =  z_deriv;
        x_deriv_new     =  x_deriv;
    end
    
else
    z_deriv_new         =  z_deriv;
    x_deriv_new         =  x_deriv;
end

