;-------------------------------------------------------------
;+
; NAME:
;       NEAREST
; PURPOSE:
;       For a target value, return value nearest to a multiple of given step
; CATEGORY:
; CALLING SEQUENCE:
;       V = NEAREST( S, T, [ VLO, VHI ])
; INPUTS:
;       S = step size.                  in
;       T = target value.                       in
;       VLO = largest multiple of S <= T.       in (optional)
;       VHI = smallest multiple of S > T.       in (optional)
; KEYWORD PARAMETERS:
; OUTPUTS:
;       V = multiple of S nearest T.            out
; COMMON BLOCKS:
; NOTES:
; MODIFICATION HISTORY:
;       R. Sterner  10 Apr, 1986.
;       Johns Hopkins University Applied Physics Laboratory.
;
; Copyright (C) 1986, Johns Hopkins University/Applied Physics Laboratory
; This software may be used, copied, or redistributed as long as it is not
; sold and this copyright notice is reproduced on each copy made.  This
; routine is provided as is without any express or implied warranties
; whatsoever.  Other limitations apply as described in the file disclaimer.txt.
;-
;-------------------------------------------------------------

        FUNCTION NEAREST, S, T, VLO, VHI,help=h

        if keyword_set(h) then begin
          print,'For a target value, return value nearest to a multiple of given step'
          print,'V = NEAREST( S, T, [ VLO, VHI ])'
          print,'  S = step size.                       in'
          print,'  T = target value.                    in'
          print,'  VLO = largest multiple of S <= T.    in (optional)'
          print,'  VHI = smallest multiple of S > T.    in (optional)'
          print,'  V = multiple of S nearest T.         out'
          return,-1
        endif

        D = T MOD S

        V = T - D

        IF T < 0 THEN BEGIN
          VHI = V
          VLO = VHI - S
        ENDIF ELSE BEGIN
          VLO = V
          VHI = VLO + S
        ENDELSE

        IF (ABS(T-VLO) LT ABS(T-VHI)) THEN RETURN, VLO ELSE RETURN, VHI

        END
