;+
; NAME:
;	GET_SPEC_GAIN
;
; PURPOSE:
;	Return the gain command value and date for the 8 BATSE detectors.
;       If error, gain and date are returned as 0.
;
; CALLING SEQUENCE:
;	get_spec_gain, intime, times, gain [, det=det ]
;
; RESTRICTIONS:
;	Reads an ASCII file created from data extracted from the MSFC
;	BATSE INGRES database.  The file
;	contains a command time and gain value for 8 detectors on
;	each line.  The file is created by Chip Meegan and the
;	information must be updated by hand to contain the latest information.
;	Each line containsinformation for only one detector. For each
;	detector, GET_SPEC_GAIN finds the closest time that is before the
;	requested time that contains information for that det.
;
; INPUTS:
;	INTIME - Time to retrieve 511 line channels for in string format or
;		seconds since 79/1/1.  GET_SPEC_GAIN will find the closest 
;		time in the file that is before INTIME.
;		If INTIME is before start of file, earliest data in file
;		will be returned.  If after last time of file, last data
;		will be returned.
;		if intime is a time interval, then "times" is returned
;		as the start of the interval, followed by the time of any gain changes,
;		and gain is given for each of "times" for the specified detector (def=0)
;       DET    - optional, if used then the outputs will be changed, and gain
;		is interpreted as an input value, intime is ignored.
;		returns the times for all intervals (2xn) for detector DET
;		for the specified gain value 
; OUTPUTS:
;	TIMES - 2x8 array of start/end times associated with the data returned
;	        if time is beyond last time in the data file of gains, last time
;		returned will be 1-jan-2010, beyond projected lifetime of BATSE mission
;	GAIN  - Hex gain value, e.g. 0.4, 1.0, 4.0, 5.0, 7.0, 8.0
;	
;
; SAMPLE CALL:  get_spec_gain, '92/4/5,1200', times, gain
;
; MODIFICATION HISTORY:
;	Written:  ras, 18-jan-94
;	Mod. AKT 1/25/94. Made output array TIMES 2x8 to return range of times,
;          also return 0 value if time not in range.
;	mod. ras, 21-feb-94, return values if after last entry in file, fixed bug
;	mod. ras, 11-jul-94, read new format of gain file
;	ras, 19 jun 1995, eliminated null lines
;	ras, 13 aug 1995, added capability to retrieve all gain intervals,X, for a detector I
;	ras, 14 aug 1995, added capability to retrieve all gain intervals within a time interval
;		for a particular detector
;	ras, 8 sep 1995, data file is parsed line by line using parse_comline
;		because of danger in str2arr
;	ras, 18-oct-1995, made the parsing more robust, can be blanks at start of line
;               RAS, 7-Jul-1997, changed PERM_DATA to SSWDB_BATSE
;----------------------------------------------------------------------

        
pro get_spec_gain, intime, outtimes, outgains, det=det

common spec_gain_lines, spec_times, spec_gains, id

; Read database file if haven't already.  

if n_elements(spec_times) eq 0 then begin
   read_seqfile, lines, CONCAT_DIR(getenv('SSWDB_BATSE'), 'spec_gain.dat')
   ; LINES will contain lines that look like:
;   TJD          Seconds   Name    Hex Value
;   8366               0   SGAIN3   0.4
;   8366               0   SGAIN4   0.4
;   8366               0   SGAIN2   1

   lines = strcompress(strtrim(lines(where(lines ne '', nlines))))	;kill null lines
;   s = str2arr(arr2str(strcompress(strtrim(lines(1:*))),delim= ' '),delim=' ')
   nlines = nlines -1  
   s = strarr(4,nlines)
   for i=0,nlines-1 do s(0,i) = parse_comline(strtrim( lines(1+i),2), delim=' ')

   id = strmid(s(2,*),5,1)
   spec_times = tjd2ymd( long( (s(0,*)))) + long((s(1,*)))
   spec_gains = fltarr(nlines)
   reads, (s(3,*))(*), spec_gains, form='(f3.1)'
endif

; User's time may be any format.  Convert to seconds.
usertime = anytim (fcheck(intime,0.0), /sec)

if n_elements(usertime) eq 2 then begin
	usertime = usertime(sort(usertime))
	wid = where( id eq fcheck(det,0) )	
	idtimes = spec_times(wid)
	idgains = spec_gains(wid)
;What is gain prior to usertime
	get_spec_gain, usertime(0), utimes, ugains
	wchng = where( idtimes gt usertime(0) and idtimes lt usertime(1), nchng)
	outgains=fltarr(nchng+1)
        outtimes=dblarr(nchng+1)
        outgains(0) = ugains(det) 
	outtimes(0) = usertime(0)
	if nchng ge 1 then $
		for i=0,nchng-1 do begin
		get_spec_gain, idtimes(wchng(i)), utimes, ugains
		outtimes(i+1) = idtimes(wchng(i))
		outgains(i+1) = ugains(det)
		endfor
return
endif

if n_elements(det) eq 0 then begin  

; For each detector, find closest time before USERTIME that contains non-zero
; data.
outtimes = dblarr(2,8)
outgains = fltarr(8)
for idet = 0,7 do begin
		
   q1 = where (usertime ge spec_times and idet eq id, count1)
   q2 = where (usertime lt spec_times and idet eq id, count2)
;   if count1 * count2 ne 0 then begin
;     index1 = q1(count1-1)  &  index2 = q2(0)
      if count1 ge 1 then begin
		index1 = q1(count1-1)  
		outtimes(0,idet) = spec_times(index1)
		outgains(idet) = spec_gains(index1)
      endif
      if count2 ge 1 then begin
	        index2 = q2(0)
		outtimes(1,idet) = spec_times(index2) 
      endif else outtimes(1,idet) = 9.7830720d8 ;1-jan-2010
		
endfor
endif else begin
;find all time intervals for this gain for this detector
  wid = where( id eq det, nid1)
  if nid1 ge 1 then begin
  idtimes = spec_times(wid)
  idgains = spec_gains(wid)
  wid = where( idgains eq fcheck(outgains,4.), nid)
  if nid ge 1 then begin
	outtimes = dblarr(2,nid)
	outtimes(0,*) = idtimes(wid)
	outtimes(1,*) = idtimes( (wid+1) < (n_elements(idtimes)-1) )
  endif
  endif
endelse
end
