;+
; NAME:
;     GETOFF
; PURPOSE:
;     From specified date, searches the !DEFAULTS.DBDIR directory
;     for the most appropriate *.OFF file, reads the most appropriate
;     entry, and returns the offsets.
; CATEGORY:
;     OVRO APC DATA ANALYSIS
; CALLING SEQUENCE:
;     off = getoff(yrday)
; INPUTS:
;     yrday    A string of the form in TLS.YRDAY giving the year and
;                day number of the data for which offsets are desired.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
; ROUTINES CALLED:
; OUTPUTS:
;     off      The offsets as read from the file.
; COMMENTS:
;     The offsets will ultimately be contained in a segment in the
;     data, so reading from a file on disk should not be necessary,
;     but for now...
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 31-Jul-1998 by Dale E. Gary
;-
function getoff,this_yrday

   ; Look for files with extension '.off' in !DEFAULTS.DBDIR
   f = findfile(!defaults.dbdir+'*.off',count=n)
   if (n le 0) then return,-1

   ; Strip out year and doy from yrday string, to use as arguments to
   ; CVDOY routine.  CVDOY returns a three element array with year, month,
   ; and day, all numeric.
   year = strmid(this_yrday,0,4)
   doy = strmid(this_yrday,5,3)
   out = cvdoy(year,doy)
   this_yrmo = string(out(0),out(1),format='(I4,I2.2)')

   ; Loop over filenames
   f = reverse(f(sort(f)))             ; Sort into newest first

   ; Declare some storage for use in loop below
   line = (yrday = (yrdaysav = (tstr = '')))
   off = (offsav = fltarr(25))

   FOR i = 0, n-1 DO BEGIN
      break_file,f(i),disk,direc,filnam,ext
      IF (filnam LE this_yrmo) THEN BEGIN
         ; This is a possible file to contain valid data.  Search is
         ; in order of newest first, so first agreement gives valid
         ; match.  Open file.
         openr,lun,/get_lun,f(i)

         ; Skip the three lines of header inforation
         hedlines = strarr(3)
         readf,lun,hedlines

         WHILE(NOT EOF(lun)) DO BEGIN
            readf,lun,line
            reads,line,yrday,tstr,off,format='(a8,1x,a8,25f5.1)'
            IF (yrday LE this_yrday) THEN BEGIN
               yrdaysav = yrday
               offsav = off
            ENDIF ELSE goto,out
         ENDWHILE
         IF (yrdaysav NE '') THEN goto,out
         free_lun,lun
      ENDIF
   ENDFOR

   IF (yrdaysav EQ '') THEN return,-1

out: free_lun,lun

return,offsav
end
