function [indx] = nearest(array, val, insideflag, toleranceflag)

% NEAREST return the index of an array nearest to a scalar
%
% Use as
%   [indx] = nearest(array, val, insideflag, toleranceflag)
%
% The second input val should be a scalar.
%
% If not specified or if left empty, the insideflag and the toleranceflag
% will default to false.
%
% The boolean insideflag can be used to specify whether the value should be
% within the array or not. For example nearest(1:10, -inf) will return 1,
% but nearest(1:10, -inf, true) will return an error because -inf is not
% within the array.
%
% The boolean toleranceflag is used when insideflag is true. It can be used
% to specify whether some tolerance should be allowed for values that are
% just outside the array. For example nearest(1:10, 0.99, true, false) will
% return an error, but nearest(1:10, 0.99, true, true) will return 1. The
% tolerance that is allowed is half the distance between the subsequent
% values in the array.
%
% See also FIND, DSEARCHN

% Copyright (C) 2002-2025, Robert Oostenveld and Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% input checks
mbreal(array);
mbvector(array);
mbreal(val);
if ~isscalar(val), ft_error('The selected value should be a scalar, non-scalar value is not supported anymore due to ambiguity in functional behavior'); end
if  isnan(val),    ft_error('The selected value should not be NaN');  end

if nargin<3 || isempty(insideflag)
  insideflag = false;
end

if nargin<4 || isempty(toleranceflag)
  toleranceflag = false;
end

% ensure that it is a column vector
array = array(:);

% determine the most extreme values in the array
minarray = min(array);
maxarray = max(array);

% do some strict checks whether the value lies within the min-max range
if insideflag
  if ~toleranceflag
    if val<minarray || val>maxarray
      if isscalar(array)
        ft_warning('the selected value %g should be within the range of the array from %g to %g', val, minarray, maxarray);
      else
        ft_error('the selected value %g should be within the range of the array from %g to %g', val, minarray, maxarray);
      end
    end
  else
    if ~isequal(array, sort(array))
      ft_error('the input array should be sorted from small to large');
    end
    if numel(array)<2
      ft_error('the input array must have multiple elements to compute the tolerance');
    end
    mintolerance = (array(2)-array(1))/2;
    maxtolerance = (array(end)-array(end-1))/2;
    if val<(minarray-mintolerance) || val>(maxarray+maxtolerance)
      ft_error('the value %g should be within the range of the array from %g to %g with a tolerance of %g and %g on both sides', val, minarray, maxarray, mintolerance, maxtolerance);
    end
  end % toleragceflag
end % insideflag

% FIXME it would be possible to do some soft checks and potentially give a
% warning in case the user did not explicitly specify the inside and
% tolerance flags

% note that [dum, indx] = min([1 1 2]) will return indx=1
% and that  [dum, indx] = max([1 2 2]) will return indx=2
% whereas it is desired to have consistently the match that is most towards the side of the array

if val>maxarray
  % return the last occurrence of the largest number
  [dum, indx] = max(flipud(array));
  indx = numel(array) + 1 - indx;

elseif val<minarray
  % return the first occurrence of the smallest number
  [dum, indx] = min(array);

else
  % implements a threshold to correct for errors due to numerical precision
  % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=498 and http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1943
  %   if maxarray==minarray
  %     precision = 1;
  %   else
  %     precision = (maxarray-minarray) / 10^6;
  %   end
  %
  %   % return the first occurrence of the nearest number
  %   [dum, indx] = min(round((abs(array(:) - val)./precision)).*precision);

  % use find instead, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1943
  wassorted = true;
  if ~issorted(array)
    wassorted = false;
    [array, xidx] = sort(array);
  end

  indx2 = find(array<=val, 1, 'last');
  indx3 = find(array>=val, 1, 'first');
  if abs(array(indx2)-val) <= abs(array(indx3)-val)
    indx = indx2;
  else
    indx = indx3;
  end
  if ~wassorted
    indx = xidx(indx);
  end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbreal(a)
if ~isreal(a)
  ft_error('Argument to mbreal must be real');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbvector(a)
if ndims(a) > 2 || (size(a, 1) > 1 && size(a, 2) > 1)
  ft_error('Argument to mbvector must be a vector');
end
