pro spali4,mov,out,mi=mi

;Spatial Limitation - AVERAGE value of max.4 pixels (absolute extremum
;       and max.3 nearest-intensity pixels from the 3x3 neighborhood).
;Absolute MINIMUM is searched if keyword /MI is set, else
;the absolute MAXIMUM is searched.
;INPUT:  3-D movie MOV of a box containing the feature.
;OUTPUT: 2-D array (table) OUT with average intensity in column 0
;        and with weighted average position of the extremum (x,y,
;        column 1 and 2 respectively).

on_error,1
si=size(mov)
if si(0) ne 3 then message,'ERROR - Input must be a 3-D array'
out=fltarr(3,si(3))
nel=si(1)*si(2)			;n_elements of a single frame
x=lonarr(nel)
y=lonarr(nel)
chmov=bytscl(mov)		;check movie

for j=0,si(3)-1 do begin	;loop over frames
  pos=sort(mov(*,*,j))		;vector of sorted positions in
				; ascending order of intensity
  for i=0,nel-1 do begin	;2-D sorted coordinates x,y
	x(i)=pos(i) mod si(1)
	y(i)=pos(i)/si(1)
  endfor

  count=0			;counter up to 4
  accint=0.			;accumulator of intensity
  wapos=[0.,0.]			;accumulator of weighted position

  if keyword_set(mi) then begin	;search around minimum [x(0),y(0)]

	for i=0,8 do begin
	  if abs(x(i)-x(0)) le 1 and abs(y(i)-y(0)) le 1 then begin
		accint=accint+mov(x(i),y(i),j)
		wapos(0)=wapos(0)+x(i)*mov(x(i),y(i),j)
		wapos(1)=wapos(1)+y(i)*mov(x(i),y(i),j)
		chmov(x(i),y(i),j)=255		;mark pixel
		count=count+1
	  endif
	  if count eq 4 then goto,la1
	endfor

  la1: out(0,j)=[accint/count,wapos/accint]

  endif else begin		;search around maximum [x(nel-1),y(nel-1)]

	for i=nel-1,nel-9,-1 do begin
	  if abs(x(i)-x(nel-1)) le 1 and abs(y(i)-y(nel-1)) le 1 then begin
		accint=accint+mov(x(i),y(i),j)
		wapos(0)=wapos(0)+x(i)*mov(x(i),y(i),j)
		wapos(1)=wapos(1)+y(i)*mov(x(i),y(i),j)
		chmov(x(i),y(i),j)=0		;mark pixel
		count=count+1
	  endif
	  if count eq 4 then goto,la2
	endfor

  la2: out(0,j)=[accint/count,wapos/accint]

  endelse

endfor
ANIMATE,rebin(chmov,si(1)*5,si(2)*5,si(3),/sample)	;show check movie

end