;+
;
; NAME:  Accum
;
;
; PURPOSE: Accumulate average spectra over a series of time intervals
;
;
; CATEGORY: Spectral analysis
;
;
; CALLING SEQUENCE: 
;	accum, select = iselect, ltime=ltime, in_obs=obs, in_eobs=eobs, in_back=back, in_eback=eback, $	;inputs
;	live=live, obsi=obsi, eobsi=eobsi, backi=backi, ebacki=ebacki, convi=convi	
;
; INPUTS:
;       in_obs - series of spectra, nchan x nbin
;	in_eobs- gaussian uncertainties on obs
;	ltime- livetime of each interval
;	in_back- background spectrum for each interval, also, nchanxnbin (optional)
;	in_eback - uncertainties on back (optional)
;	select - 2 x nsel pairs of indices referenced to obs for summing spectra
;
; OUTPUTS:
;	obsi - time averaged spectra - float(nchan x n_elements(iselect(0,*)))
;	eobsi- uncertainties on obsi
;	backi- time averaged background spectra
;	ebacki
;	live - summed livetime for each new interval - float( nchan x n_elements(iselect(0,*)))
;	convi- conversion factors - count-rate flux / photon flux  - float(nchan x n_elements(iselect(0,*)))

;
; PROCEDURE: spectra are live time averaged and uncertainties are sqrt of sum of squared
;	     uncertainties, background uncertainty is invariant with summing
;
; MODIFICATION HISTORY: ras, 12-feb-94
; 		ras, 24-oct-94, 
;		ras, 9-dec-1996, reconciled with change in iselect
;-



pro accum, select = iselect, ltime=ltime, in_obs=obs, in_eobs=eobs, in_back=back, in_eback=eback, $	;inputs
	live=live, obsi=obsi, eobsi=eobsi, backi=backi, ebacki=ebacki, convi=convi		
    
;Done automatically after select!
;Sum the intervals selected together
	nsel = n_elements(iselect(0,*))
	if n_elements(back) ne 0 then nbck = 1 else nbck=0 	;has background been passed?
	nchan = n_elements(obs(*,0))
	live = fltarr( nchan, nsel )
	obsi = fltarr( nchan, nsel)
	convi = obsi
	eobsi = obsi
	if nbck then begin
		backi= obsi
		ebacki= obsi
	endif

	for i=0, nsel-1 do begin
		wsel = indgen( iselect(1,i)-iselect(0,i)+1>1)+iselect(0,i)
		msel = n_elements(wsel)
		if msel gt 1 then begin
		  live(*,i) = total( ltime(*,wsel),2)
		  obsi(*,i) = f_div( total(  obs(*,wsel)*ltime(*,wsel),2) , live(*,i))
		  eobsi(*,i) = f_div( total((eobs(*,wsel)*ltime(*,wsel))^2.,2)^0.5 , live(*,i) )
                  if nbck then begin
			backi(*,i) = f_div( total(  back(*,wsel)*ltime(*,wsel),2) , live(*,i) )
                  	ebacki(*,i) = rebin(eback(*, wsel),nchan,1)
		  endif

		endif else begin
		  live(*,i) = ltime(*,wsel)
		  obsi(*,i) = obs(*,wsel)
		  eobsi(*,i)= eobs(*,wsel)
		  if nbck then begin
			backi(*,i)= back(*,wsel)
  		  	ebacki(*,i)=eback(*,wsel)
		  endif
		endelse
        endfor

end
