;
; merc_ephem returns values from the ephemeris file merc_snp_L_5s_V041503.txt
; in SOHO (X,Y) coordinates.


FUNCTION merc_ephem_data
  
;Reference = snp (With light time corrections)
;                    --------- Mercury --------    Sun/Merc
;   Time (UTC)       Long(deg)        Lat(deg)     Sep(deg)
; 20030507.060905   0.2620692614   0.2443589103   0.3583171199
; 20030507.060910   0.2619759246   0.2443418775   0.3582372428
; 20030507.060915   0.2618825878   0.2443248446   0.3581573729
; 20030507.060920   0.2617892516   0.2443078118   0.3580775109
; 20030507.060925   0.2616959148   0.2442907789   0.3579976557
; 20030507.060930   0.2616025779   0.2442737460   0.3579178077
; 20030507.060935   0.2615092416   0.2442567131   0.3578379676
  
  tx = rd_ascii('merc_snp_L_5s_V041503.txt')
  tx = tx[3:*]
  
  return,tx
END 

PRO merc_ephem,x,y,sep,delta_time,xcof,ycof,timestr=timestr
  COMMON merc_ephem,tx,c_time,c_timestr,c_d,c_i,c_x,c_y,c_min,c_sep
  
  IF n_elements(tx) EQ 0 THEN BEGIN
     tx = merc_ephem_data()
     tx = stregex(tx,'([^ ]*)   ?(-?[^ ]*)   ([^ ]*)   ([^ ]*)',/extract,/sub)
     tstr = reform(tx[1,*])
     hour = float(strmid(tstr,9,2))
     minute = float(strmid(tstr,11,2))
     second = float(strmid(tstr,13,2))
     c_time = minute + hour*60.0 + second/60.0
     c_timestr = $
        strmid(tstr,0,4)+"/"+strmid(tstr,4,2)+"/"+strmid(tstr,6,2)+" "+$
        strmid(tstr,9,2)+":"+strmid(tstr,11,2)+":"+strmid(tstr,13,2)
     c_x = reform(-3600*double(tx[2,*]))
     c_y = reform(3600*double(tx[3,*]))
     c_sep = reform(double(tx[4,*]))
     c_d = sqrt(c_x^2+c_y^2)
     c_min = min(c_d,c_i)
  END 
  
  delta_time = c_time-c_time[c_i]
  
  IF arg_present(timestr) THEN timestr = c_timestr
  
  x = c_x
  y = c_y
  sep = c_sep
  
  n = n_elements(x)
  
  ;; Fit only original points:

  IF arg_present(xcof) THEN xcof = poly_fit(delta_time,x,2,xfit,xband,/double)
  IF arg_present(ycof) THEN ycof = poly_fit(delta_time,y,2,yfit,yband,/double)
  
END
  
