;+
; NAME
;          EIS_AIA_OFFSET
;
; PURPOSE
;          This function gets the contents of John Mariska's
;          "eis_aia_avgoffsets.txt" file (as a structure array)
;          and returns the offset nearest the supplied date. If a date
;          isn't supplied, then use the current date.
;
; INPUTS
;          NONE
; KEYWORDS
;          date - date to
; CALLS
;          eis_aia_read_offset_file
; USE:
;          r = eis_aia_offset([date='1-Jul-2013'])
; WRITTEN
;          John A Rainnie, RAL, 16-Jul-2013
;
; HISTORY
;          v0.1 JAR 16-Jul-2013
;               Blah
;-
;______________________________________________________________________________
FUNCTION eis_aia_offset , date = date

; Was a date specified? If not then get and use todays date (TAI).
IF (N_ELEMENTS(date) NE 0) THEN BEGIN
   ; Better check the time and its format is valid
   IF (valid_time(date) NE 1) THEN BEGIN
      print," Input time is not valid. Bailing out!"
      RETURN , 0
   ENDIF
ENDIF ELSE BEGIN
   ; No date supplied. Use current time (UTC). Convert to TAI
   get_utc , date
ENDELSE

; OK, read file and get offsets
array = eis_aia_read_offset_file()
; Check returned array is a structure. If not, then we have failure.
IF (N_TAGS(array[0]) EQ 0) THEN BEGIN
   print," Couldn't get EIS-AIA offsets. Bailing out."
   RETURN , 0
ENDIF

; OK, convert date to TAI time format. Good for time maths!
date = anytim2tai(date)

; Nicely done. So now we want to ... go for coffee... back soon
; So we find the line from the averaged file which is nearest to our date
; Simples. We get a list of the (absolute, sign isn't important)
; differences between those times and our own (in seconds, since we're
; working in TAI time). Then, whichever is the smallest is our match.
delta = ABS(date - array[*].date)

; Get the minimum difference - and more importantly it's index (min_index)
min_delta = MIN(delta , min_index)
; Return this line (actually it's a structure, but you know what I mean)

RETURN , array[min_index]

END
