
FUNCTION spacecraft_pointing, fname, t

;+
; NAME
;
;     SPACECRAFT_POINTING()
;
; PROJECT
;
;     SOLAR-B
;
; EXPLANATION
;
;     Given a Solar-B instrument pointing file and a reference time, this
;     routine will calculate the heliocentric coordinates in arcseconds.
;
; INPUTS
;
;     FNAME  The name of a Solar-B pointing file.
;
;     T      The reference time in a standard format accepted by ANYTIM.PRO.
;
; OUTPUTS
;
;     A 2 element array, giving the (X,Y) heliocentric coordinates in
;     arcseconds.
;
; CALLING SEQUENCE
;
;     IDL> xy=spacecraft_pointing(filename,t)
;
; EXAMPLE
;
;     IDL> xy=spacecraft_pointing(filename,'2006/10/11 20:00')
;
; CALLS
;
;     READ_REPOINT, LONLAT2XY, ANYTIM
;
; HISTORY
;
;     Ver.1, 22-Jun-2006, Peter Young
;-

read_repoint, fname, repoint

timeline=repoint.timeline
curves=repoint.curves

t_tai=anytim(t,/tai)
start_tai=anytim(repoint.tstart,/tai)
end_tai=anytim(repoint.tend,/tai)

IF t_tai LT start_tai OR t_tai GT end_tai THEN BEGIN
  print,'%SPACECRAFT_POINTING: input time lies outside the time period covered by the'
  print,'                      input file. Returning...'
  return,-1.
ENDIF

;
; Find which set of tracking curves to use
; 
i=where(strmid(timeline.activity,0,15) EQ 'AOCS Mem-Upload',nt)
nt=nt+1    ; add 1 for the initial starting curves
IF nt EQ 1 THEN BEGIN
  i_tc=0
ENDIF ELSE BEGIN
  tc_times_tai=[start_tai,timeline[i].tai]
 ;
 ; i_tc is the index of the set of tracking curves corresponding to the
 ; input time, i.e., repoint.curves[i_tc]
 ;
  i_tc=where(max(tc_times_tai[where(tc_times_tai LE t_tai)]) EQ tc_times_tai)
ENDELSE


;
; Find the tracking curve that corresponds to the input time
;
j=where(strmid(repoint.timeline.activity,0,6) EQ 'Latest',nj)
IF nj GT 1 THEN print,'** Error in input file!'
;
i=where(strmid(repoint.timeline.activity,1,8) EQ 'Re-point',ni)
;
IF ni eq 0 THEN BEGIN
  tc=timeline[j].tc
ENDIF ELSE BEGIN
  rep_times_tai=[timeline[j].tai,timeline[i].tai]
  k=[j,i]   ; indices of the pointing entries
  i_rep=where(max(rep_times_tai[where(rep_times_tai LT t_tai)]) EQ rep_times_tai)
  i_rep=k[i_rep]   ; index within timeline
  tc=timeline[i_rep].tc
ENDELSE

;print,'TC set: ',i_tc+1
;print,'TC:     ',tc

IF tc EQ 0 THEN BEGIN
  xoff=timeline[i_rep].xoff
  yoff=timeline[i_rep].yoff
 ;
  x=-xoff*60.*60.
  y=-yoff*60.*60.
  return,[x,y]
ENDIF ELSE BEGIN
  curves=curves[i_tc]
  tracks=curves.tracks
  i=where(tracks.n EQ tc)
  track=tracks[i]
 ;
  long=track.long
  lat=track.lat
  rot_rate=track.rot_rate
  ref_tai=track.tai
 ;
  new_long=long+rot_rate*(t_tai-ref_tai)
  xy=lonlat2xy([new_long,lat],t)
  return,xy
ENDELSE


END
