;+
; NAME:
;       FIND_CLOSE
;
;
; PURPOSE:
;       Find the the index of an input array where the array is closest to
;       a specified value
;
;
; CATEGORY:
;       Array utility
;
;
; CALLING SEQUENCE:
;       ix = find_close(array, value)
;
;
; INPUTS:
;       ARRAY: an array of arbitrary number of elements and of basic type (excluding string)
;       VALUE: a single value 
;
;
; OPTIONAL INPUTS:
;       None
;
;
;
; KEYWORD PARAMETERS: 
;       DIFF: returns the minimum difference between ARRAY and VALUE if set to
;             a named variable
;       LATER: if set, ensure that the returned index correspond to the ARRAY
;              value that is closest to VALUE, but greater
;       EARLIER: if set, ensure that the returned index correspond to the ARRAY
;              value that is closest to VALUE, but smaller
;
; OUTPUTS:
;       An integer corresponding to the index of the ARRAY element closest to VALUE.
;
;
; OPTIONAL OUTPUTS:
;       None
;
;
; COMMON BLOCKS:
;       None
;
;
; SIDE EFFECTS:
;       None
;
;
; RESTRICTIONS:
;       ARRAY must be of basic type and not a string array
;
;
; EXAMPLE:
;       IDL> a=findgen(10)
;       IDL> print,find_close(a, 3.1)
;                  3
;       IDL> print,find_close(a, 3.1,/later,diff=diff)
;                  4
;       IDL> print,diff
;            0.900000
;
;
;
; MODIFICATION HISTORY:
;       xx-xx-2009: Suguro Kamio
;       08-06-2010: Terje Fredvik - Doc header
;
;-

function find_close,array,value,diff=diff,later=later,earlier=earlier
d = array - value
r = min(abs(d), pos)
diff = d[pos]
if keyword_set(later) and (diff lt 0) and (pos lt n_elements(array)-1) then pos++
if keyword_set(earlier) and (diff gt 0) and (pos gt 0) then pos--

diff = d[pos]
return,pos

end
