PRO AVGCURV,ino,lif,outcurv,beg=beg

;Evaluation of the results of OTRACK2 (should be revised by
;OTRIM and RECUR) to get average light curves of tracked objects.
;
;INPUT:  INO - 3-D array, result of tracking.
;	 LF  - 1 or 2-D array with lifetimes
;OUTPUT: OUTCURV - 1-D array with averaged light curve


si=size(ino)
if (si(0) ne 3) or (si(1) ne 3) then goto,wrong
sl=size(lif)
if sl(0) gt 2 then goto,wrong
if sl(0) eq 2 then lf=lif(0,*) else lf=lif

window,2,xsiz=400,ysiz=300,title='Histogram of lifetimes'
HISTO,lf,bin=1,/abs	;lifetimes in frame lags

new:
read,'Select lifetime range (from,to): ',lf1,lf2
w=where((lf ge lf1) and (lf le lf2),c)  ;subscripts also valid for ino
curvs=float(reform(ino(0,*,w)))		;set of light curves
centr=si(2)/2				;middle point of time
print,'Number of objects in the range',c

for i=0,c-1 do begin		;loop over objects
	we=fix(where(curvs(*,i)))
	ma=max(curvs(*,i),pos)
	curvs(*,i)=curvs(*,i)/ma	;normalization to max.
	curvs(0:we(0),i)=curvs(we(0),i) ;replicate first/last value
	curvs(max(we):si(2)-1,i)=curvs(max(we),i)
	if keyword_set(beg) then pos=we(0)
	shf=centr-pos			;shift max (begin) to center
	curvs(*,i)=shift(curvs(*,i),shf)	
endfor

window,0
if keyword_set(beg) then plot,curvs(*,0),xra=[centr,centr+lf2],/xst,yst=16 $
  else plot,curvs(*,0),xra=[centr-lf2,centr+lf2],/xst,yst=16
for i=1,c-1 do oplot,curvs(*,i)
outcurv=total(curvs,2)/c
oplot,outcurv,thick=2,col=150
goto,fin

wrong:
  print,'ERROR: Wrong input array. Program terminated.'
fin:
END