;+
; PROJECT:
;	SDAC
; NAME: 
;	N511_VS_HVSPEC
;
; PURPOSE:
;	This procedure finds the coefficients of a crude 2nd order fit to the linear
;	channel number of the 511 line vs the reported high voltage in the BATSE SPEC detectors.
;
; CATEGORY:
;	BATSE
;
; CALLING SEQUENCE:
;	N511_vs_hvspec t
;
; CALLS:
;	RESISTANT_MEAN
;
; INPUTS:
;       none explicit, only through commons;
;
; OPTIONAL INPUTS:
;	none
;
; OUTPUTS:
;       none explicit, only through commons;
;
; OPTIONAL OUTPUTS:
;	none
;
; KEYWORDS:
;	none
; COMMON BLOCKS:
;	none
;
; SIDE EFFECTS:
;	none
;
; RESTRICTIONS:
;	Must be run on hxrbs.nascom.nasa.gov where it expects to find the database file,
;	~richard/../data/richard/batse/spec_gain_str.genx.  Otherwise, it must be edited accordingly.
;	The database file tag elements, see the code for a description, are obtained by using 
;	HKG_DBASE and GET_DISCSP511.  Only the HV and 511 lines are really used here.
; PROCEDURE:
;	none
;
; MODIFICATION HISTORY:
;	richard.schwartz@gsfc.nasa.gov, 27-mar-1998.
;-
pro n511_vs_hvspec

if n_elements(a) eq 0 then restgen,a,file=loc_file('~richard/../data/richard/batse/spec_gain_str.genx')
;IDL> help,a,/st
;** Structure MS_260217488003, 8 tags, length=212:
;   FLARE           INT              1
;   UT              STRUCT    -> MS_260217488002 Array[1]
;   HV              INT       Array[8]
;   SLLD            BYTE      Array[8]
;   EDGES           FLOAT     Array[3, 8]
;   GAIN            FLOAT     Array[8]
;   N511            FLOAT     Array[8]
;   BASETEMP        INT       Array[8]
!p.multi = [0,4,2]


coef_all1 = fltarr(2,8)
coef_all2 = fltarr(3,8)
wuse2     = fltarr(8)
wuse1     = fltarr(8)
for i=0,7 do begin
	;t0 = anytim(a(0).ut)
	hv= a.hv(i)
	n5= a.n511(i)
	w = where(hv gt 1000. and hv lt 10000.,nw)
	;ut = t(w)
	n5 = n5(w)
	hv = hv(w)
	hmin = 3.0
	checkvar,hbin, .02
	coef_all1(0:1,i) = polyfitw( alog(hv(w)), alog(n5(w)),1./alog(hv(w)), 1, yfit)
	resistant_mean, alog(n5(w))-yfit,1,wuse=wuse
	w1 = w(wuse)
	coef_all1(0:1,i) = polyfitw( alog(hv(w1)), alog(n5(w1)),1./alog(hv(w1)),1, yfit1)

	coef_all2(0:2,i) = polyfitw( alog(hv(w1)), alog(n5(w1)),1./alog(hv(w1)),2, yfit2)
	resistant_mean, alog(n5(w))-yfit1,1.5,wuse=wuse
	wuse1(i) = n_elements(wuse)
	resistant_mean, alog(n5(w))-yfit2,1.5,wuse=wuse
	wuse2(i) = n_elements(wuse)
	;w1 = w(wuse)
	plot, hv(w), n5(w), psy=1,/xlog,xrange=[1000,5000],/ylog
	
	oplot, hv(w), exp(poly(alog(hv(w)),coef_all1(0:1,i))), psy=2, col=5
	oplot, hv(w), exp(poly(alog(hv(w)),coef_all2(0:2,i))), psy=4, col=7
	

endfor
; The results are:
more,';'+string(/prin,coef_all2)
;      2.09169     -4.07810     0.567922
;    -0.125223     -4.10749     0.598442
;     -1.72157     -4.40386     0.665374
;      1.60833     -7.39385     0.992034
;     0.427124     -5.69597     0.795257
;     -1.05214     -4.32965     0.650771
;      1.15086     -3.71443     0.537004
;    -0.813373     -3.52385     0.540543

end
