;+
; PROJECT:
;	SDAC
; NAME:
;	DISCSP_READ
; PURPOSE:
; 	Procedure to read BATSE DISCSP files and return time, DISCSP, and angle
; 	information.  The DISCSP data has been corrected for overflow and 
;	divided by livetime.
;
; 	You must supply the file name explicitly, the time you want, or the 
;	flare number in order for discsp_read to find the correct input file.  
;	If you specify a file name or flare number, you may also specify 
;	time start and end to restrict the amount of data returned.  If 
;	you don't specify any times, discsp_read will return all data in the 
; 	fdb file. 
; 	UTPLOT package times are set as follows:  base time is set to start 
;	of day of the current data, start and end times are set to 0 for 
;	autoscaling.
; CATEGORY
;	BATSE
; CALLING SEQUENCE:
;	discsp_read, t, y, cosines	
;
; OUTPUTS:
;   t - (output)   array of times at middle of accumulation interval in 
;                  seconds since start of day.  
;                  Base time for UTPLOT routines will be set to 0h 0m
;                  on day of data. (Function GETUTBASE(0) will return base 
;                  time in seconds since 79/1/1.) 
;   y - (output)   (i,j,n) floating point array of discsp data where
;                  i=4 - channels 0-3 
;                  j=8 - LADs 0 through 7
;                  n - number of data intervals 
;   cosines - (output) floating point array of cosine of angles between 8 LADs
;                  and Sun (cosines(j) corresponds to y(*,j,*)
;
; OPTIONAL KEYWORD INPUTS:
;   filename -  string DISCSP file name
;   starttime - start time of data to accumulate in r*8 seconds 
;               since 79/1/1,0 or as ASCII string 'YY/MM//DD,HHMM:SS'.
;   endtime -   end time of data to accumulate. See starttime above for format.
;   flare -     BATSE flare number to accumulate data for
;   verbose -   0/1 means don't/do print accumulation times message
;   msfc   -    if set then it is a msfc discsp file w/o housekeeping
;		and the cosines will be set those during the closest
;		flare to the middle of the time interval.
; OPTIONAL KEYWORD OUTPUTS:
;   livetime -  (8,n) floating point array of live time in seconds for 
;               each LAD for each data interval 
;   error -     (keyword output) =0/1 means no error / error
; 
; Common Blocks
;	flare_catalog,  fscom, fs_saveaccum 
; MODIFICATION HISTORY:
; Amy Skowronek 94/8/24  (adapted from fdbread)
; Richard Schwartz, 95/09/08, added msfc keyword and cosines option 
;	for msfc
; ras, 27-mar-1996 removed setup_arrays, fs_read_dd does it.
; Version 4, fixed overflow time selection, richard.schwartz@gsfc.nasa.gov, 24-feb-1998.
;-
; *******************************************************************
;
pro discsp_read, t, y, cosines, livetime=live_time, filename=filename, $
             starttime=st_input, endtime=en_input, msfc=msfc, $
             flare=flare, verbose=verbose, error=error
;
; *******************************************************************
!quiet=1
;
@fscom
@fs_saveaccum
@flare_catalog

checkvar, verbose, 1   ; set verbose to true if not passed as keyword.

error = 0

;print,'st_input,en_input = ',st_input,en_input
if keyword_set(st_input) then begin
   s = size(st_input)
   nel = n_elements(s)
   if s(nel-2) eq 7 then sec_st_input = utime(st_input) $
                     else sec_st_input = st_input
endif

if keyword_set(en_input) then begin
   s = size(en_input)
   nel = n_elements(s)
   if s(nel-2) eq 7 then sec_en_input = utime(en_input) $
                     else sec_en_input = en_input
endif

; find and open requested input file
if not keyword_set(msfc) then $
	 fs_open, file=filename, flare=flare, time=st_input, dd_type=3, $
  	 dd_open=dd_open, verbose=verbose, error=error else $
	 fs_open, file=filename, flare=flare, time=st_input, dd_type=13,  $
  	 dd_open=dd_open, verbose=verbose, error=error 
	
if error then begin
   print, 'Can''t find input file.'
   print, 'Must provide file name, flare number, or a time ' + $
          'interval in calling arguments.'
   goto, errorexit
endif


; If user supplied start or end time, set sec_st and sec_en in common fscom
; to those values.  Otherwise use start and end of file.
if keyword_set(st_input) then sec_st=sec_st_input else sec_st=dd_open.startsec
if keyword_set(en_input) then sec_en=sec_en_input else sec_en=dd_open.endsec
sec_st = sec_st > dd_open.startsec
sec_en = sec_en < dd_open.endsec

; See if any overflow intervals overlap with requested time interval.  If so,
; expand time interval to accumulate to include the 1 minute before the overflow
; started.
new_sec_st = sec_st
check_overflow, sec_st, sec_en, nfound, ovr_sec_st, ovr_sec_en
if nfound gt 0 then begin
   print, 'Correcting ', nfound, ' overflow intervals.'
   new_sec_st = min ([sec_st, ovr_sec_st-60.])
   xmin = sec_st
endif


; set up arrays to read data into
;setup_arrays, redundant, ras 27 mar 1996

; read all requested data into the above arrays
;print,atime(sec_en)
fs_read_dd, dd_open=dd_open, startt=new_sec_st, endt=sec_en, $
   verbose=verbose, error=error
free_lun, dd_open.lun
if error then goto,errorexit
                                                       
; initialized the time array to 0, then filled in the time and data arrays 
; using time as an index into the array).
gaps = where (spseconds(0:maxspindex) eq 0.d0, count)
if count ne 0 then spseconds(gaps) = spseconds(0) + 2.048*gaps
gaps = where (pseconds(0:maxposindex) eq 0.d0, count)
if count ne 0 then pseconds(gaps) = pseconds(0) + 2.048*gaps


if not keyword_set(msfc) then begin
; Get day/night transition times, if any.

getdn:
  dn_trans, pseconds(0:maxposindex), xpos(0:maxposindex), $
   ypos(0:maxposindex), zpos(0:maxposindex), d_mark, n_mark, ntrans=ntrans,$
   bad_data=bad_data
  if bad_data then begin
   print,'No valid position data in requested time interval.'
   goto,errorexit
  endif

; Generate day/night times from day/night index arrays.

; Call det_cosines to generate array of cosines for each detector.

; First need to fill in gaps in pointing data during omni periods if any.
  radec_fill, pseconds, xra, xdec, zra, zdec, maxposindex, $
   error=error
  if error then begin
   print,'Error.  No good pointing data found yet.  Select a longer ' + $
      'time interval.'
   goto,errorexit
  endif

  det_cosines, flare=file2flare(dd_open.filename),cos_spec=sp_cos8
endif else begin
	batse_read_cat
	min_time = min( abs( (sec_st + sec_en)/2. - fldata.start_secs), imin)
	flare_num = fldata(imin).flare_num
	det_cosines, flare=flare_num, cos_spec=sp_cos8
	print, 'Using Marshall DISCSP file without housekeeping data.'
	print, 'Pointing is obtained from closest flare in time, #',flare_num
endelse


; Save just one set of cosines for 8 detectors

fix_discsp,splivet,error=error

; just return the data that was requested (we might have started at
; an earlier time to include a complete overflow interval.
early = where (spseconds(0:maxspindex) lt sec_st, kearly)
minindex = 0
if kearly gt 0 then minindex = early(kearly-1) + 1
t = spseconds(kearly:maxspindex)
y = discsp(*,*,kearly:maxspindex)
cosines = sp_cos8
live_time = splivet(*,kearly:maxspindex)

; Set base time for utplot package to start of day.  Subtract start of day
; from time array so it will be seconds relative to start of day.
; Also set start and end time for utplot package to 0 - find_dbfile sets
; these to start and end of the discsp file, which may not be correct here.
setutbase, anytim(t(0),/sec,/date)
setutstart, 0
setutend, 0
t = t - getutbase(0)

goto,getout

errorexit:
error = 1
goto,getout


getout:

return&end
