PRO stabili,from,to,shfts,offs,mov
;
;CORRECTION OF GLOBAL SHIFTS of IR frames of 23 or 25 June 1997.
;INPUTS:  from = seq. of the first image in the subseries.
;	  to = seq. of the last image in the subseries.
;	  shfts = array of big image shifts measured manually
;	  by IBIGSHIFT.
;	  Derotated files XXjun/idXX.seq, where XX is the date.
;OUTPUTS: offs = 2-column (x,y) array of cumulative shifts with
;	  respect to the 1st frame of the subseries, which,
;	  applied to frames, move them to the reference position
;	  of the 1st frame - only for check.
;	  Stabilized files XXjun/isXX.seq, where XX is the date.
;METHOD:  Cross correlation (ALIGN_C2 or COR_IMAG/COR_ANAL) -
;	  - derived from GSSTAB. If necessary, correction for
;	  "big shifts" is applied before the correlation.
; Procedures called: ALIGN_C2, FIVEPOIN, MAXLOC, MEAN, NINT,
;	  COR_IMAG, COR_ANAL.

siz=size(shfts)
nima=siz(2)
offs=shfts*0

;............PARAMETERS....................................

if nima eq 321 then begin
  dat='23' 
  x1=46			;coords of correlation box for 23 June
  x2=117		; 72x72
  y1=59
  y2=130
  wx=58			;this allows the shifts up to +/- 6 pixels
  wy=58
endif else begin
  dat='25'
  x1=120		;coords of correlation box for 25 June
  x2=191		; 72x72
  y1=55
  y2=126
  wx=58			;this allows the shifts up to +/- 6 pixels
  wy=58
endelse

im=intarr(224,224)		;image array
nami=dat+'jun/id'+dat+'.'	;I/O filenames
namo=dat+'jun/is'+dat+'.'
	mov=intarr(224,224,to-from+1)
	window,2,xsiz=144,ysiz=72

;..........................................................


;1st frame - nothing to be done

  openr,1,nami+strtrim(from,2)
  readu,1,im
  close,1
ref=float(im(x1:x2,y1:y2))
  openw,1,namo+strtrim(from,2)
  writeu,1,im
  close,1
	mov(0,0,0)=im

;loop over frames ........................................

for i=from+1,to do begin

  openr,1,nami+strtrim(i,2)
  readu,1,im
  close,1

  im1=shift(im,total(shfts(0,from:i)),total(shfts(1,from:i)))
	;putting the field into the right position if necessary,
	; using cumulative big shifts
  ima=float(im1(x1:x2,y1:y2))

	tvscl,ref,0
	tvscl,ima,1

  offset=nint(align_c2(ref,ima,flg,wx,wy))

;  when align_c2 fails (flg=1) we call cor_imag, cor_anal...
   if (flg eq 1) then begin
	   print,i,'   ...cor_imag called...'
	   corrmat=cor_imag(ref,ima)		 ; correl_images
	   cor_anal,corrmat,xof,yof   		 ; corrmat_analyze
	   offset=nint([xof,yof])
   endif

  offset=offset+shfts(*,i)

  ref=ima				;reference for the next frame

  offs(*,i)=offs(*,i-1)+offset		;cumulative shifts
  print,i,'   rel.shift:',offset(0),offset(1),'   cumul.:',offs(0,i),offs(1,i)

  im=shift(im,offs(0,i),offs(1,i))	;correction for shifts

  openw,1,namo+strtrim(i,2)
  writeu,1,im
  close,1
	mov(0,0,i-from)=im

endfor

END