;integrates a set of tabulated values (given by t and x)
;using a midpoint method
;returns the integral along tgrid
function midpoint, t, x, tgrid
;x=dy/dt
n=n_elements(x)
n2=n_elements(tgrid)
y=fltarr(n2)
j=0
while tgrid[j] lt t[0] do j=j+1
y_curr=0.
for i=1, n-1 do begin
dy=(x[i-1]+x[i])/2.
while tgrid[j] lt t[i] and tgrid[j] ge t[i-1] do begin
y[j]=y_curr+dy*(tgrid[j]-t[i-1])
; print, j
j=j+1
if j ge n2 then break
endwhile
if j ge n2 then break
y_curr=y_curr+dy*(t[i]-t[i-1])
; print, y_curr
endfor
if tgrid[n2-1] eq t[n-1] then y[n2-1]=y_curr
; stop
return, y-y[0]
end
function bin_average, t, x, tgrid
ngrid=n_elements(tgrid)
bin_limits=[tgrid[0], (tgrid[0:ngrid-2]+tgrid[1:ngrid-1])/2, tgrid[ngrid-1]]
int=midpoint(t, x, bin_limits)
average=(int[1:ngrid]-int[0:ngrid-1])/(bin_limits[1:ngrid]-bin_limits[0:ngrid-1])
return, average
end