function tim2tfss, times, night=night, day=day, loud=lout, x=x, y=y, $
   		plotit=plotit, logit=logit, femdelta=femdelta, debug=debug
;+
;   Name: tim2tfss
;
;   Purpose: find time of tfss night or day; optionally display timeline
;
;   Input Parameters:
;      times - time or time array (any Yohkoh format) -  for example, SFT
;              roadmap records...
;
;   Optional Keyword Parameters:
;      plotit   - if set, display timeline
;      logit    - if set, log results
;      loud     - if set, echo results to terminal
;      femdelta - (output) predicted deltaT from FEM files
;
;   Calling Sequence:
;      delta=tim2tfss(times [,/plotit, /logit, femdelta=femdelta] )	
;
;   History:
;      12-dec-1994 (SLF) written to filter SFT (terminators)
;      13-dec-1994 (SLF) protect when no ATR data in window, added level check
;      14-dec-1994 (SLF) add LOUD keyword / add X and Y keywords
;
;   Method:
;      look at atr files for window around times - determine where
;         state change occurs (via max derivitive)
;
;   Restrictions:
;      night detection for now (some hooks for day, but not implemented yet)
;      no checks for missing ATR data in region of 'real' night
;      Currently time window is set up for sxt terminators, but should be
;      made more generic.
;-

y=keyword_set(y)			; y
x=keyword_set(x) or (1-y)		; default X only

debug=keyword_set(debug)
loud=keyword_set(loud)
plotit=keyword_set(plotit)		; display results?
ntimes=n_elements(times)		; number of input times
odelta=fltarr(ntimes)			; return value    (tfss deltas)
femdelta=fltarr(ntimes)			; optional output (fem deltas)

if str_is(times) then otext=get_info(times,/non) else otext=times 

;  ------------ log results on request -------------
logging=keyword_set(logit)
if logging then begin
   logfile=concat_dir(get_logenv('HOME'),'tim2fss.log')
   message,/info,"Logging info to: " + logfile(0)
   file_append,logfile,'; ' + ["","TIM2TFSS run at: " + !stime,""]
endif
; -------------------------------------------------------

day=keyword_set(day)
night=keyword_set(night) or (1- keyword_set(day))	; default

; ----------------- loop through times ---------------------
for i=0, ntimes-1  do begin
;  get ephemeris times to make a reasonable time window for atr read
   tim2orbit,times(i),tim2fms=tim2fms, tim2night=tim2night
   case 1 of
;     establish reasonable windows around desired data... (for atr read)
      night: begin
         sttime=timegrid(times(i),min=-2)
         entime=timegrid(times(i),min=tim2night+1.)
         femdelta(i) = round(tim2night*60)
      endcase
      day: begin
         sttime=timegrid(times(i),min=tim2fms)
         entime=timegrid(times(i),min=2.)
         femdelta(i) = tim2fms*60.
      endcase
      else:         
   endcase

   delta=999999					; invalid data (no atr)
;  read the atr data for the desired window
   rd_atr, sttime, entime, atrrecs 
   if str_is(atrrecs) then begin
;     identify transition via derivitive
;     add level check and second deriv
      secs=int2secarr(atrrecs,times(i))
;     ... ugly code follows....	(my plane leaves soon...)
;     wired for terminator use (assume night)
      tlevss=tim2dset(atrrecs,times(i))		; level at term time
      tlev=float(atrrecs(tlevss).tfss(0))
      xlev=float(atrrecs(tlevss).tfss(0)) * x   ; xlevel at term time
      ylev=float(atrrecs(tlevss).tfss(1)) * y   ; ylevel at term time
      tx=atrrecs.tfss(0) * x			; zero if no X
      ty=atrrecs.tfss(1) * y			; zero if no Y
      upturn=where(tx + ty gt ((xlev+ylev) + (xlev+ylev)*.2) and $
         [0,deriv_arr(tx + ty)] gt 0 and (secs gt 0),ucnt)

if debug then stop
;      upturn=where(atrrecs.tfss(0) gt (tlev + tlev*.2) and $
;         [0,deriv_arr(atrrecs.tfss(0))] gt 0 and (secs gt 0),ucnt)
      if ucnt le 1 then begin
         rev=0
         rcnt= 0
      endif else  rev=where(deriv_arr(upturn) ne 1,rcnt)
      if rcnt eq 0 then ss=upturn(n_elements(upturn)-1) else ss=upturn(rev(0))
      if ss(0) eq -1 then ss = n_elements(atrrecs)-1 else $
         ss= ss  < (n_elements(atrrecs)-1)
;     .... end of ugly code 
      delta=addtime(diff=times(i),atrrecs(ss(0)))*60.
      odelta(i)=delta
      if loud then message,/info,"Seconds between Terminator and TFSS NIGHT: " + strtrim(delta,2)

;     ------------ show the results if /plotit set --------------------
      if plotit then begin
         linecolors		
         if x and y then ttype = 'X + Y' else ttype = (['X','Y'])(y)
         ttype='(' + ttype + ')'            
;        ---------- plot the data used for determination (x,y,or x+y) -------
         utplot,atrrecs,tx + ty, $
            title='Terminator Time / TFSS Relation ' + ttype, $
            ytitle='TFSS Level (ATR)'
;        if both x and y selected, overplot individual curves         
         ypos=[xlev,ylev] + [200,-400]
         if x and y then begin
            for t=0,1 do begin
            outplot,atrrecs,atrrecs.tfss(t),psym=([1,4])(t),color=([4,9])(t)
            xyouts,.15, (convert_coord([0,ypos(t)],/data,/to_norm))(1), $
               (['X','Y'])(t),  color=([4,9])(t),/norm,size=1.5
            endfor
         endif
;        ---------------- label some events via evt_grid -------------
         evt_grid,atrrecs(ss),label='TFSS NIGHT: ' + gt_time(atrrecs(ss),/string), $
            align=1, linestyle=0 , color=7,thick=2,labpos=.2
         evt_grid,times(i), label='TERM TIME: ' + gt_time(times(i),/string), $
            /align, labpos=.75,linestyle=0,color=2, thick=2
         evt_grid,times(i),ticklen=.1,tickpos=.89, label='DELTA: ' + strtrim(delta,2) + 'S', $
            color=5, /align, thick=2
         evt_grid,atrrecs(ss),ticklen=.1,tickpos=.89,color=5, label='-', $
             align=0, thick=2
         if i lt ntimes-1 then begin
            input,"<CR> to continue, anything else to quit: ",a,''
            if a ne '' then i=ntimes-2		; *** force unstructured exit
         endif
;        ------------------------------------------------------------------
      endif
   endif else begin
      prstr,["WARNING: NO ATR data for record...", otext(i)]
      odelta(i)=delta
   endelse

   if logging then file_append,logfile, $
      [otext(i),"Delta Seconds: TFSS Night: " + strtrim(delta,2) + $
                             " FEM Night: " + strtrim(tim2night*60,2)] 
endfor

if debug then stop
return, odelta

end
