function [idx, val] = mfs_peaks(y, option)

# usage: [idx, val] = mfs_peaks(y, option)
#
# Input  y(:)     Array with input values
#        option   String defining option (see below, optional)
#
# Output idx(:)   Array with peak indices
#        val(:)   Array with peak values (optional)
#
# Options:  "max"   find maxima (default)
#           "min"   find minima
#           "both"  find maxima and minima
#
# The function finds peaks by comparing the differences between
# two neighbouring points.
#
# -------------------------------------------------------------------

# Copyright (c) 2020 by Johannes Wandinger

# Initialize

  idx = []; val = [];

# Check arguments

  if (nargin < 1 || nargin > 2)
     print_usage();
  end
  if (nargout < 1 || nargout > 2)
     print_uage();
  end

  if (nargin == 1)
     option = "max";
  elseif (! ischar(option))
     error("getpeaks: option must be a string: \"max\", \"min\" or \"both\"\n");
  end

# Compute differences and their shifted product

  dy = diff(y);
  p  = dy(1 : end-1) .* dy(2 : end);

# Find any peaks

  idxall = find(p < 0);

  if (isempty(idxall)) return; end

# Process option

  switch option

  case "both"
     idx = idxall + 1;

  case "max"
     ix  = find(dy(idxall) > 0);
     idx = idxall(ix) + 1;

  case "min"
     ix  = find(dy(idxall) < 0);
     idx = idxall(ix) + 1;

  otherwise
     error("getpeaks: unknown option \"%s\"\n", option);

  end

  val = y(idx);

end
