;+
; NAME:
;     GET_LUNEPH
; PURPOSE:
;     Return a three-day consecutive lunar ephemeris, given the
;     Julian date of the first day.
; CATEGORY:
;     OVRO APC EPHEMERIS
; CALLING SEQUENCE:
;     lunar = get_luneph(jd)
; INPUTS:
;     jd      Julian date of the first day for which the lunar
;               ephemeris data are wanted.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
; ROUTINES CALLED:
;     rd_luneph (internal routine), dayofyr, get_lun_struct
; OUTPUTS:
;     lunar   A lunar ephemeris structure of the form
;                 { RA:    LONARR(3),  ; Right ascension for each day [0.1 mdeg]
;                   DEC:   LONARR(3),  ; Declination for each day [0.1 mdeg]
;                   RAD:   INTARR(3),  ; Radius for each day      [0.1 mdeg]
;                   HP:    INTARR(3),  ; Horizontal parallax      [0.1 mdeg]
;                   REFT:  INTARR(3),  ; Reference time           [sec]
;                   DOY:   INTARR(3)}  ; Reference day of year
; COMMENTS:
;   Requires the file !DEFAULTS.EPHEMDIR+'LUNAREPH.DAT', which is the same file
;   used by the CPC (FASAR) to determine the lunar coordinates.
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 12-Jan-1999 by Dale E. Gary
;     30-Jan-1999  DG
;       Slight change to use GET_LUN_STRUCT() routine
;     11-Jan-2000  DG
;       ELiminated hardwired directory locations.
;-
function rd_luneph,jd
   openr,/get_lun,lun,!defaults.ephemdir+'lunareph.dat'
   line = ''
   lines = strarr(3)

   ON_IOERROR,bail

   ; Read a data line
   readf,lun,line
   srchstr = string(jd,format='(C("( ",CMOA,X,CDI2.2,") ",CYI))')

   ; Loop until Julian date is found
   while (strmid(line,26,14) ne srchstr) do begin
      readf,lun,line
   endwhile
   lines(0) = line
   readf,lun,line
   lines(1) = line
   readf,lun,line
   lines(2) = line
   free_lun,lun
   return,lines
bail:
   free_lun,lun
   return,-1
end

function get_luneph,jdin

   ; Convert Julian Date from current system time to JD of same date, but at 0 UT
   jd = double(long(jdin - 0.5))+0.5

   ; Open and read the lunar ephemeris lines for this date
   lines = rd_luneph(jd)

   ; Return -1 if an error
   if (n_elements(lines) eq 1) then return,-1

   ; Define LUNAR structure
   lunar = get_lun_struct()

   ; Fill in LUNAR structure using data from Ephemeris file
   for i = 0, 2 do begin
      reads,lines(i),ra,dec,hp

      ; Lunar radius (semi-diameter) in degrees
      semid = hp*1738./6378.

      ; Convert input variables to integers in units of 0.1 mdeg
      lunar.ra(i) = long((ra mod 360)*10000.D)
      lunar.dec(i) = long(dec*10000.D)
      lunar.rad(i) = fix(semid*10000.)
      lunar.hp(i) = fix(hp*10000.)

      ; Determine day of year from date string
      datstr = string(jd+i,format='(C(CYI,x,CMOA,x,CDI2.2))')
      doy = dayofyr(strmid(datstr,0,4),strmid(datstr,5,3),strmid(datstr,9,2))
      lunar.doy(i) = doy
   endfor
return,lunar
end
