

FUNCTION gt_closest_index, singlevalue, arrayofvalues, lessthan, greaterthan, $
                           all=all, noprint=noprint, $
                           mindiff=mindiff
;
;+
;
; Returns the index of element in the float/integer array ARRAYOFVALUES that is 
; closest to SINGLEVALUE.
; If set to named parameters lessthan/greaterthan will return the index of
; the element of arrayofvalues that is closest to singlevalue but smaller/greater.  
; 
; Keywords:
;          noprint: do not print result of search to screen
;          
;
;
;-
;

  diffarr = singlevalue - arrayofvalues
  absmindiff = min(abs(diffarr), closest_index)
  
  IF keyword_set(all) THEN $
     closest_index = where(abs(diffarr) EQ min(abs(diffarr)))
  
  IF n_params() GE 3 THEN BEGIN
     lessthanix = where(diffarr GT 0)
     IF lessthanix[0] NE -1 THEN $
        lessthan = where(diffarr EQ min(diffarr[lessthanix])) ELSE BEGIN 
        message, 'No values in input array less than '+trim(singlevalue),$
                 /info
        lessthan = closest_index
     ENDELSE
  ENDIF
  
  IF n_params() EQ 4 THEN BEGIN
     greaterthanix = where(diffarr LT 0)
     IF greaterthanix[0] NE -1 THEN $
        greaterthan = where(diffarr EQ max(diffarr[greaterthanix])) ELSE BEGIN 
        message, 'No values in input array greater than '+trim(singlevalue),$
                 /info
        greaterthan = closest_index
     ENDELSE
  ENDIF
   
  mindiff = singlevalue - arrayofvalues[closest_index]
  
  IF NOT keyword_set(noprint) THEN   PRINT,'Closest index '+ $
           trim(closest_index) + ', diff='+trim(mindiff)
  
  RETURN,closest_index
  
END
