      pro read_coef, spec_lld
;+
;  Name:
;       READ_COEF
;c****************************************************************************
;c	      pro read_coef, spec_lld
;
;c     This subroutine reads in some of the necessary coefficients stored in 
;c     external data files. The coefficients are passed in common blocks 
;c     to the main routine.  In addition, the subroutine calculates the
;c     SLED correction appropriate to the detector's LLD setting.
;c
;c     The SLED correction is d* (1.-tanh(b*(x-c)) up to 'cut'.
;c     I assume that 1./b and c increase linearly with the LLD, while
;c     d should remain constant.
;c
;      The relevant data files are found on SSWDB_BATSE in ASCII
;      and XDR format save sets
;      
;c     Input:
;c        spec_lld--LLD setting of spectrum to be calibrated
;c     Output:
;c        sled_com--common block with sled correction coefficients
;c        fiducial_com--common block with calibration equation parameters
;c
;;c     written 12/6/91 LAF; last modifed 4/7/92 DLB
;c
;c****************************************************************************
;c
;               RAS, 7-Jul-1997, changed PERM_DATA to SSWDB_BATSE
;-
;c
      common sled_com,sb,sc,sd,scut
      common fiducial_com,af,bf,cf,xf
;
;c     Get SLED parameters
;c
;read in sled coefficients from ASCII file and save in XDR format
	read_seqfile, sleds, concat_dir(getenv('SSWDB_BATSE'),'sled.dat')
	id = where(strpos(sleds,'Detector') ne -1)
	form = "(1x,z2)"
	sled_dat = fltarr(5,3,8)
	for i=0,7 do begin 
        	for j=0,2 do begin
		line=sleds(id(i)+j+1) 
        	out0 = 0 
		out = fltarr(4)  
		if line ne '' then begin
			reads,line,out0,form=form 
			reads,strmid(line,3,80), out
		endif
                sled_dat(*,j,i)=[out0,out] 
		endfor
	endfor
  	
;     this assumes that there are sled coefficients for the SPEC_LLD setting
;     so that no interpolation of the coefficients is necessary
	sb = fltarr(8)
	sc = fltarr(8)
	sd = fltarr(8)
	scut = fltarr(8)

	for id = 0,7 do begin
		wlld = where( spec_lld(id) eq sled_dat(0,*,id), lld_count)
		if lld_count eq 0 then begin ;interpolate for missing
	wuse  = where( sled_dat(4,*,id) ne 0.0)
	sb(id)= interpol(sled_dat(1,wuse,id),sled_dat(0,wuse,id),spec_lld(id))
	sc(id)= interpol(sled_dat(2,wuse,id),sled_dat(0,wuse,id),spec_lld(id))
	sd(id)= sled_dat(3,0,id)
	scut(id) = interpol(sled_dat(4,wuse,id),sled_dat(0,wuse,id),spec_lld(id))
		endif else begin
		 sb(id)=sled_dat(1,wlld(0),id)
		 sc(id)=sled_dat(2,wlld(0),id)
		 sd(id)=sled_dat(3,wlld(0),id)
		 scut(id)=sled_dat(4,wlld(0),id)
		endelse
	endfor

;c
;c
;c     Get fiducial coefficients
;c
 
	openr,lu,/get,concat_dir(getenv('SSWDB_BATSE'),'fcoeff.dat')
	fcoeff = fltarr(4,8)
	readf,lu,fcoeff
	free_lun,lu
	fcoeff = transpose(fcoeff)
	af = fcoeff(*,0)
	bf = fcoeff(*,1)
	cf = fcoeff(*,2)
	xf = fcoeff(*,3)

      return
      end
