function av_dt_genx, dt, good=good, outfil=outfil
;+
;NAME:
;       av_dt_genx
;PURPOSE:
;       To average a set of detune GENX data results
;SAMPLE CALLING SEQUENCE:
;      dtav = av_dt_genx(dt)
;      dtav = av_dt_genx(dt, good=[0,1,3,4])
;INPUT:
;       dt = array of structures of GENX detune results
;OPTIONAL KEYWORD INPUT:
;       good = array of indices of good elements of dt
;	outfil = filename for saving the result
;OUTPUT:
;	A structure of the same form as dt containing the averages
;	Prints a short summary of the average detune
;HISTORY:
;       Written 30-Dec-97 by T. Tarbell
;	Ver 1.1  2-Jan-98 (TDT)	- Use weighted averages for results
;	Ver 1.11 27-Mar-00 (TDT)- added sum_dt_genx,dt for printed summary
;-

progver = 'AV_DT_GENX  Ver 1.11'
if (not keyword_set(good)) then good = indgen(n_elements(dt))
ng = n_elements(good)
dtsum = dt(good(0))
dtsum.label = strmid(dt(good(0)).label,0,24)+' - '+strmid(dt(good(ng-1)).label,4,20)
dtsum.label = dtsum.label+'    Average of '+string(ng,'(i3)')
dtsum.label = dtsum.label+'   '+progver
if (ng eq 1) then begin
	if (keyword_set(outfil)) then savegen,file=outfil,dtsum,progver
	return,dtsum
endif

dtsum.ftfit(*,*).a(*)=0.
dtsum.ftfit(*,*).siga(*)=0.
dtsum.ftfit(*,*).sig=0.

; Make weighted average of a's, using 1/sigma^2 as weight, avoiding 1/0
; Accumulate averages in dtsum.ftfit(*,*).a(*)
; Accumulate sum of weights in dtsum.ftfit(*,*).siga(*)
; See Bevington, 1st edition, P. 73

for i=0,ng-1 do begin 
    dtsum.ftfit(*,*).sig = dtsum.ftfit(*,*).sig + dt(good(i)).ftfit(*,*).sig
    for j=0,8 do begin 
        wts = dt(good(i)).ftfit(*,*).siga(j)^2
        w = where(wts le 1.e-12,count)
	if (count gt 0) then wts(w)=1.e12
	wts = 1./wts
        dtsum.ftfit(*,*).a(j) = dtsum.ftfit(*,*).a(j) + wts*dt(good(i)).ftfit(*,*).a(j)
	dtsum.ftfit(*,*).siga(j) = dtsum.ftfit(*,*).siga(j) + wts
    endfor
endfor

fac=1./float(ng)
dtsum.ftfit(*,*).sig = fac*dtsum.ftfit(*,*).sig
; Normalize weighted mean of a's
dtsum.ftfit(*,*).siga(*) = 1./dtsum.ftfit(*,*).siga(*)
dtsum.ftfit(*,*).a(*) = dtsum.ftfit(*,*).a(*)*dtsum.ftfit(*,*).siga(*)
; Standard deviation of weighted mean is sqrt(normalizing coefficient)
dtsum.ftfit(*,*).siga(*) = sqrt(dtsum.ftfit(*,*).siga(*))
if (keyword_set(outfil)) then savegen,file=outfil,dtsum,progver
sum_dt_genx,dtsum
return, dtsum
end
