;+
;
; NAME: 
;	RD_HXRBS_FITS
;
; PURPOSE:
;	Read hxrbs fits files into idl
;
; CATEGORY:
;	HXRBS
;
; CALLING SEQUENCE:
;       RD_HXRBS_FITS, Filename, Ut, Counts, Livetime, Edges, Deltat 
;
; CALLS:
;	READFITS, FXPAR
;
; INPUTS:
;       Filename:	Hxrbs fits file name
;
; OUTPUTS:
;       Ut:		Time in seconds since 1-jan-1979, middle of datapoint, 
;			dblarr(nbin)
;	Counts:		Number of counts in each of 15 energy channels,    
;			fltarr(15,nbin)
;	Livetime:	Livetime in each sample, fltarr(nbin)
;	Edges:		Output energy loss bands in keV, fltarr(2,15)
;	Deltat:		Accumulation interval, scalar, in seconds
;
; OPTIONAL OUTPUTS:
;	H0:		Primary header (string array)
;	H1:	 	Header from first (time) extension (string array)
;	H2:		Header from second (energy edges) extension 
;			(string array)
;	Res_coef:	Hxrbs resolution coefficient, varied from .75 to 
;			1.3 over the mission
;	Error:		Returns 1 on problem.
;
; COMMON BLOCKS:
; 	HXRBS_RESPONSE
;
; PROCEDURE:
;	Calls readfits three times for the counts, times, and edges.
;	The resolution coefficient is passed through the common to 
;	hxrbs_response.pro. This is done in the background to serve the 
;	SPEX procedures, although it may also be done explicitly.
;
; MODIFICATION HISTORY:
; 	RAS, 08/26/94
;	Mod. 09/06/94 by RAS. Removed extra call to readfits for edges.
;	Mod. 09/07/94 by AKT. Added 3 keywords to return 3 headers
;			Also removed call to transpose edges and counts array -
;			fits files were changed to store in correct order
;	Mod. 08/04/95 by RAS. Added common hxrbs_response.
;	Mod. 05/08/96 by RCJ. Added documentation.
;	Mod. 19-Feb-2013. Kim Tolbert. Moved from $SSW/smm/hxrbs/idl to ospex dir
;-

pro rd_hxrbs_fits, filename, ut, counts, livetime, edges, deltat, error=error,$
   res_coef=res_coef, h0=header, h1=h1, h2=h2

common hxrbs_response, e_matrix_sav, inmatrix, res_coef_com

error = 0
filename= (findfile(filename(0),count=nfile))(0)
if nfile ne 1 then begin
	print,'Error reading ',filename
	error=1
	return
endif

counts=readfits(filename, header, /silent)
ut = readfits(filename, ext=1, h1, /silent) /1000.d0
edges = readfits(filename, ext=2, h2, /silent) 
deltat=fxpar(header,'CDELT1')
res_coef = fxpar(header,'RESOLUTN')
res_coef_com = res_coef

;PROCESS DATA
livetime = (counts(15,*) * deltat / 1000.)(*)
counts = temporary(float(counts(0:14,*)))
ut = ut + tjd2ymd(fxpar(header,'TIMEZERO'))

end
