function ZCR = zero_crossing_rate(y, wind, winover, padd, smooth)

% ZCR = zero_crossing_rate(y, wind, winover, padd, smooth)
% 
% This function calculates the zero-crossing rate.
% 
% y         - input column vector
% wind      - length of window in samples or window samples
% winover   - window overlapp in samples
% padd      - if set to 1, the last segment will be padded by 
%             zeros if necessary (default: 0)
% smooth    - smoothing [on/off] (default off)
% ZCR       - output zero-crossing rate collumn vector

%% Paths and variables
if ((nargin < 2) || (isempty(wind)))
    wind = hamming(0.02*fs);
end
if ((nargin < 3) || (isempty(winover)))
    winover =  length(wind)/2;
end
if ((nargin < 4) || (isempty(padd)))
    padd = 0;
end
if ((nargin < 5) || (isempty(smooth)))
    smooth = 0;
end

%% Segment the signal
[rows, cols] = size(y);
if ((rows == 1) || (cols == 1))
    if (rows < cols)
        y = y.';
    end
    Y = segmentation(y, wind, winover, padd);
else
    Y = y;
end

%% Calculate the zero-crossing rate
Y(Y >= 0) =  1;
Y(Y < 0)  = -1;
Y = abs(Y((1:end - 1), :) - Y((2:end), :));

ZCR = sum(Y == 2)./(size(Y, 1) + 1);

%% Smooth ZCR estimation (if smooth == 1)
if smooth == 1
    for i = 2:(length(ZCR) - 1)
        ZCR(i) = median(Z((i - 1):(i + 1)));
    end
end