pro barrel_sp_collect_one_spectrum, payload, times, slow, spectrum, livetime, $
level=level,rawtime,version=version
if (not keyword_set(level)) then level = 'l2'
if slow then begin
datstr='SSPC'
dur=32.
endif else begin
datstr='MSPC'
dur=4.
endelse
ebins=barrel_make_standard_energies(slow=slow)
barrel_load_data, probe=payload, datatype=[datstr], level=level,$
version=version,/no_update
varname='brl'+payload+'_'+datstr
tplot_names,varname, NAMES=matches,/ASORT
if (n_elements(matches) EQ 1) then get_data, matches[0], data=spect $
else message, 'Bad number of variable name matches ('+datstr+'): '+ $
strtrim(n_elements(matches))
nspect = n_elements(spect.y[*,0])
spectots = total(spect.y,2)
goodspect = (spectots GE 0.1)
barrel_load_data, probe=payload, datatype=['RCNT'], level=level,$
/no_update,version=version
varname='brl'+payload+'_RCNT_Interrupt'
tplot_names,varname, NAMES=matches,/ASORT
if (n_elements(matches) EQ 1) then get_data, matches[0], data=irq $
else message, 'Bad number of variable name matches (RCNT): '+ $
strtrim(n_elements(matches))
badirq = (irq.y LT 0)
w=where((spect.x GE times[0]) and ((spect.x + dur) LE times[1]) $
and (goodspect EQ 1) ,nw)
spect_time=spect.x[w]
if nw EQ 0 then message,'no data in time range.'
wl=where((irq.x GE times[0]) and ((irq.x + dur) LE times[1]) $
and (badirq EQ 0),nwl)
rate_irq = irq.y[wl] / 4.
irq_time = irq.x[wl]
edge_products,ebins,mean=mean,width=width
rate_spect=fltarr(nw)
spectrum = fltarr(n_elements(width))
livetime = 0.
rawtime = 0.
for i=0,nw-1 do begin
if (level eq 'l2' or level eq 'L2') then rate_spect[i]= total(spect.y[w[i],*]*width) $
else rate_spect[i]= total(spect.y[w[i],*]/dur)
dts = abs(irq_time - spect_time[i])
nearest_irq = rate_irq[(where(dts eq min(dts)))[0]]
if (level eq 'l2' or level eq 'L2') then spectrum += dur*spect.y[w[i],*]/(1. - nearest_irq*8.0e-6) $
else spectrum += spect.y[w[i],*]/(1. - nearest_irq*8.0e-6)/width
livetime += dur*(1.- nearest_irq*8.0e-6)
rawtime += dur
endfor
end