;+
; NAME
;	RD_TGRS_SPEC
; PURPOSE
; 	Read in spectral accumulation files produced by the 
;	TGRS Data Analysis Software (TDAAS).
;	Suitable for reading ANY TGRS data produced
;	by the routine COUNT in TDAS.
;
; INPUTS
;	Filename- fully file name including path
; OUTPUTS
;	FLUX  - count rate in counts/sec/cm2/keV
;	EFLUX - Poisson uncertainty on Flux
;	EDGES - energy edges 2xNumber_of_channels
;	UT    - Start and end time in seconds from 1 jan 1979
; KEYWORDS
;	ERROR- If spectrum is not read properly, error will be set to 1.
;	BTYPE- If set, then background is already subtracted, 'BSB' file
; CATEGORY
;	TGRS, SPEX
; RESTRICTIONS -
;	The file does encode the x-axis and y-axis types, but we are assuming
;	that everything is in energy units for the moment.
;	Only use on VMS.
; HISTORY
;	RAS, 23 - JULY - 1996, ADAPTED FROM RD_SPEC.PRO
;
;-
pro rd_tgrs_spec, filename, ut, edges, flux, eflux, error=error, btype=btype, $
	disc=disc

error = 0

f = findfile(filename,count=count)
if count eq 0 then goto, error_exit
openr,lu,/get,filename,/seg
disc_ch=0L
data_ch=0L
readu,lu,disc_ch,data_ch

data_row = fltarr(4)

spec = fltarr(4,data_ch+disc_ch)
for i=0,disc_ch-1 do begin
	readu,lu,data_row
        spec(0,i)=data_row
endfor

disc = spec(*,0:disc_ch-1)
;
;-- use x86 as source to suppress annoying message.
conv_unix_vax, disc,sourc='x86'

data_row = fltarr(3)

for i=disc_ch,data_ch-1+disc_ch do begin 
	readu,lu,data_row
        spec(0,i)=data_row(0)
	spec(2,i)=data_row(1:2)
endfor
dmin=0.0
readu,lu,dmin

free_lun,lu

spec(1,0:(disc_ch + data_ch - 2)) = spec(0,1:*) ;DMAX is DMIN shifted up by one
spec(1,(disc_ch + data_ch - 1)) = dmin ;MAX ENERGY OF LAST CHANNEL IS DMIN

;Convert from IEEE format
conv_unix_vax, spec ,sourc='x86'

temp_not_zero = where(spec ne 0.,not_zero_count)
if not_zero_count eq 0 then goto,error_exit

;Break into PHA and DISCRIMINATOR arrays

flux  = spec(2,disc_ch:*)
eflux  = spec(3,disc_ch:*)
edges = spec(0:1,disc_ch:*)

break_file, filename, disk, dir, fnam
btype = strpos(strupcase(fnam),'BSB') ne -1 
ut = dblarr(2,1) 
for i=0,1 do ut(i)= utime('31-dec-'+strtrim(fix(disc(0,2+i)-1),2))+disc(1,2+i)*86400.d0 $
	+ disc(2,2+i)/1000.d0


return

error_exit:
error = 1
print,'% RD_SPEC>> Error in reading ',filename


end
 
