;+
;Procedure for determining photopeak response of SOXS si detector
;Based on discussions at PRL with R Jain and KJ Shah
;Old method based on efficiency and transmission file was flawed in
;interpretation by RA Schwartz because efficiency file was computed using
;the wrong cross-section for silicon, czt cross section was used instead.
;
; Now the response is computed from the exposed geometric area thru the
; collimator circle, the absorption from the Be, Al, and Kapton and then
; the prob of single pe detection in Si. A correction to the photopeak
; efficiency was obtained by a second order fit of the detector efficiency
; data which included the Be window of 1 mil.  We therefore group the be
; window with the detector and treat the Al and Kapton separately as absorbers

; 16-feb-2007 richard.schwartz@gsfc.nasa.gov
;	Modification - changed Al thickness to 70 micron suggested by R Jain
;-

function soxs_photopeak, ems, area=area, $
	old = old, transmission_file=transmission_file, $
	efficiency_file=efficiency_file, $
	error=error

error = 1

;Compute SOXS si transmission function
xalcm = xsec(ems,13,'pe')
xbecm = xsec(ems, 4, 'pe')

al = 70.e-4 ; 95 * 1e-4 ;70 microns from R Jain, 16-feb-2007
kp = 150 * 1e-4
;be = 25.4 * 1e-4 ;for Si
;compute kapton

tfile = obj_new('tfile')
tfile->Set, path = 'SSWDB_SOXS'
kapton = tfile->getdata(/auto,/convert, filename='kaptonxs.txt')
obj_destroy, tfile
test =  is_number(kapton[0])

if not test then begin
	message,/cont, 'Invalid kapton file'
	return, 0
	endif


;kapton = rd_tfile('kaptonxs.txt',/auto,/conv)
xkapton= interpol(kapton[1,*],kapton[0,*],ems) * 1.42 ;1.42gm/cm3 kapton
default, area, 0.091 ;cm2
;efficiency of detector + be window
xbecm = xsec(ems, 4, 'pe')
xsicm = xsec(ems, 14,'pe')
si = 300 * 1e-4
be = 25.4 * 1e-4 ;for Si

;best 2nd order poly fit to measured photopeak including beryllium
pcoeff = transpose([1.03225, -0.00144332, -0.000248940])
detection = (1-exp(-xsicm*si))*exp(-xbecm*be) / poly(ems, pcoeff)


out =exp(-xkapton*kp) * exp(-xalcm*al)  * area * detection

if keyword_set(old) then begin
;This method is incorrect, included for reference only
	default, efficiency_file, 'effi_si.txt'
	default, transmission_file, 'efsi80150.txt'

	default, area,.091 ; cm^2 - area of aperture, requires "perfect" pointing

	tfile = obj_new('tfile')
	tfile->Set, path = 'SSWDB_SOXS'
	efficiency = tfile->getdata(/auto, /convert, filename=efficiency_file)
	transmission = tfile->getdata(/auto,/convert, filename=transmission_file)


	transmission = interpol( transmission[1,*],transmission[0,*], ems, /quad)
	efficiency = interpol( efficiency[1,*],efficiency[0,*], ems, /quad)
	obj_destroy, tfile
	out = smooth(transmission * efficiency,9) >0

	endif
error = 0
return, out
end
