function y = zeroCrossings(X, type, threshold)
% Find the zero crossings in X.  Type is a string that can be
% either 'pos', 'neg', or 'all' meaning zero crossings from
% negative to positive, positive to negative, or both,
% respectively.  Threshold is the size of the smallest difference
% across zero that still counts as a zero crossing.

if(nargin < 2) type = 'all'; end
if(nargin < 3) threshold = 0; end

% $$$ d = ndiff(sign(X),1)/2 .* abs(ndiff(X,1));
d = ndiff(sign(X),1)/2;

switch type
  case 'pos'
    y = (d >= threshold) .* d;
  case 'neg'
    y = (d <= -threshold) .* -d;
  case 'all'
    y = (abs(d) >= threshold) .* d;
end
