pro tracing_step,residual_image,istart,jstart,nlen,ang0,thresh0,qfill0,test,xloop,yloop,zloop,wid0,count

;	This procedure is called by TRACING_AUTO.PRO

step	=((wid0*2) < (nlen/3)) > 1
nw	=wid0*2+1
dim	=size(residual_image)
nx	=dim(1)
ny	=dim(2)
for idir=0,1 do begin
 i0     =istart
 j0     =jstart
 flux0	=residual_image(i0,j0)
 xl	=fltarr(nx)
 yl	=fltarr(nx)
 zl	=fltarr(nx)
 ang	=0.
 alpha	=9999.
 alpha0	=9999.
 for k=0,nx/2 do begin          ;maximum loop length
  xl(k) =i0
  yl(k) =j0
  zl(k) =flux0
  i1    =long(i0-nlen/2)
  j1    =long(j0-nlen/2)
  i2    =(i1+nlen-1)>(i1+1)
  j2    =(j1+nlen-1)>(j1+1)
  if (i1 lt 0) or (i2 gt nx-1) or (j1 lt 0) or (j2 gt ny-1) then goto,endloop
  subimage=residual_image(i1:i2,j1:j2)
  if (idir eq 1) and (k eq 0) then alpha=alpha1		;first angle
  tracing_direction,subimage,nlen,step,idir,k,i1,j1,i0,j0,alpha,ifit,jfit,ang0,a1,a2,alpha00,qfill
  r	=findgen(nlen)
  nfit	=n_elements(ifit)
  xfit	=i1+ifit
  yfit	=j1+jfit
  i0    =i0+step*cos(alpha+!pi*idir)         	  ;new position
  j0    =j0+step*sin(alpha+!pi*idir)
  ax_	=(nlen/2)*cos([a1,a2])	         	  ;angle range
  ay_   =(nlen/2)*sin([a1,a2])         	  
  ind	=nfit/2+findgen(nfit-1-nfit/2)
  flux  =median(subimage(long(ifit(ind)+0.5),long(jfit(ind)+0.5)))
  zl(k) =flux
  if (k ge 1) then ang=abs(alpha-alpha0)*180./!pi ;angular change
  alpha0 =alpha					  ;old value
  alpha00=alpha0
  if (idir eq 0) and (k eq 0) then alpha1=alpha   ;first angle
;________________________test display__________________________________
  if (count ge test) then begin
   print,'x,y,a,da,flux=',i0,j0,alpha*180./!pi,ang,flux,format='(a,4f8.1,f8.2)'
   window,3,xsize=512,ysize=512
   erase
   clearplot
   !x.range=[0,nlen-1]+i1
   !y.range=[0,nlen-1]+j1
   !x.style=1
   !y.style=1
   plot,[i0,i0],[j0,j0],psym=1,symsize=5
   x	=findgen(nlen)+i1
   y	=findgen(nlen)+j1
   zmax	=max(subimage)>(thresh0*2.)
   contour,subimage,x,y,level=thresh0+(zmax-thresh0)*(findgen(11)/10.)
   oplot,xfit,yfit,color=200,thick=3
   oplot,xl(k)*[1,1],[0,nlen-1]+j1,linestyle=2
   oplot,[0,nlen-1]+i1,yl(k)*[1,1],linestyle=2
   oplot,i0*[1,1],[0,nlen-1]+j1,linestyle=1
   oplot,[0,nlen-1]+i1,j0*[1,1],linestyle=1
   oplot,[-1,+1]*ax_(0)+xl(k),[-1,+1]*ay_(0)+yl(k),color=200
   oplot,[-1,+1]*ax_(1)+xl(k),[-1,+1]*ay_(1)+yl(k),color=200
   read,'continue ? [0,1] ',yes
   if (yes eq 0) then stop
  endif
;________________________storing two loop halfs________________________
  if (ang   gt ang0)   then goto,endloop	;angular change criterion
  if (qfill lt qfill0) then goto,endloop
 endfor		;for k=0,n/2
 endloop:
 if (idir eq 0) then begin			;first half of loop
  xloop	=reverse(xl(0:k))
  yloop	=reverse(yl(0:k))
  zloop	=reverse(zl(0:k))
 endif
 if (idir eq 1) and (k ge 1) then begin		;second half of loop 
  xloop	=[xloop,xl(1:k)]
  yloop	=[yloop,yl(1:k)]
  zloop	=[zloop,zl(1:k)]
 endif
 if (count ge test) then print,'Loop direction reversal idir=',idir
endfor
end
