## -*- texinfo -*-
## @deftypefn {FunctionFile} {@var{y} = } hysteresis (@var{on},@var{off},@var{x})
##
## Output a counting integer in the vector @var{y} everytime @var{x}
## crosses the hysteresis set up by @var{on} and @var{off}.
##
## @example
## @group
## @code{hysteresis(-1,0,[1,0,1,0,-1,-2,-1,0,1,0,-2,-2,-2])}
## @result{} [0,0,0,0,1,1,1,1,0,0,2,2,2]
## @end group
## @end example
## @end deftypefn

function y = hysteresis(on,off,x)
  # Check the arguments
  if (nargin!=3 || !isscalar(on) || !isscalar(off) || !isvector(x))
    print_usage();
  endif
 
  # Build the output
  num = 1;
  n = length(x);
  y = zeros(1,n);

  i = 1;
  if (on < off)
    while (i <= n)
      # Put 0 as output until we drop below on
      while (i<=n && x(i)>on)
        y(i) = 0;
        i = i+1;
      endwhile
      # Put num as output until we come above off
      while (i<=n && x(i)<=off)
        y(i) = num;
        i = i+1;
      endwhile
      num = num+1;
    endwhile
  else
    while (i <= n)
      # Put 0 as output until we come above on
      while (i<=n && x(i)<on)
        y(i) = 0;
        i = i+1;
      endwhile
      # Put num as output until we drop below off
      while (i<=n && x(i)>=off)
        y(i) = num;
        i = i+1;
      endwhile
      num = num+1;
    endwhile
  endif
endfunction
