pro destre2,movin,movout,optio

; DESTRETCHING of a movie in a 3-D array MOVIN, result is a 3-D array MOVOUT.
; Main for DEFORM2 (procedures called by DEFORM2 are ALIGN_CR, FIVEPOIN,
; MAXLOC, NINT, MEAN (Oslo); COR_IMAG, COR_ANAL (astro/pro/image); WARP_TRI).
;
; Reference image: either the floating average of movie frames
; or preceeding destretched frame (recurrent definition).
; This is selected by "optio": optio=0, recurrent.
; optio=num>1, floating average, where num gives the number of frames
; to be averaged.

smov=size(movin)
if smov(0) ne 3 then begin
   print,'DESTRE2: Input must be a 3-D array!'
   stop
endif
nima=smov(3)
print,'number of frames:',nima
movout=movin*0

; reference selection switch
if optio eq 0 then goto,recur

; floating average reference

optio=optio>3
optio=optio<nima

for i=0,nima-1 do begin

   ll=i-fix(optio/2)>0
   ul=ll+fix(optio)-1
   if ul gt (nima-1) then begin
	ul=nima-1
	ll=ul-fix(optio)+1
   endif
   print,'reference',i,'  averaged from-to',ll,ul

   ref=total(movin(*,*,ll:ul),3)/nima    ; total returns float
   if smov(4) eq 1 then ref=bytscl(ref)  ; conversion to bytes
   if smov(4) eq 2 then ref=fix(ref)     ; conversion to integer

   print,'processing frame no.',i
   deform2,movin(*,*,i),ref,war
   movout(0,0,i)=war

endfor
goto,fin

; recurrent reference

recur:
ref=movin(*,*,0)
movout(0,0,0)=ref
for i=1,nima-1 do begin
   print,'processing frame no.',i
   deform2,movin(*,*,i),ref,war
   movout(0,0,i)=war
   ref=movout(*,*,i)
endfor

fin:
end