pro aia_mag_loop_test,il,xl,yl,zl,nseg,hmax,imid_,xf1,yf1,field_,curr_,xr_,rad_,dev_r,f_,c_,fov,dev,a_mis_s,test

dim	=size(xr_)
nr	=dim[1]
ns	=n_elements(xl)

if (il eq 0) then begin
 window,1,xsize=750,ysize=1500
 loadct,5
 clearplot
endif
blue    =50
red     =110
orange  =160
yellow  =200
dlat	=1.
clearplot

!p.title='Loop #'+string(il,'(I4)')
!p.position=[0.1,0.05,0.9,0.35]
;!x.range=[fov[0],fov[2]]	;minmax(xl)+[-0.02,0.02]
;!y.range=[fov[1],fov[3]]	;minmax(yl)+[-0.02,0.02]
!x.range=minmax(xl)+[-0.02,0.02]
!y.range=minmax(yl)+[-0.02,0.02]
plot,[0,0],[0,0]
for ir=0,nr-1 do begin
 col	=50+200.*float(ir)/float(nr-1)
 indf	=where(field_(*,ir,0) ne 0,nf)
 indc	=where(curr_(*,ir,0) ne 0,nc)
 if (nf ge 1) then oplot,field_(indf,ir,0),field_(indf,ir,1),color=col
 if (nc ge 1) and (test eq 2) then oplot,curr_(indc,ir,0),curr_(indc,ir,1),linestyle=2,color=orange
endfor
oplot,xl,yl,psym=-1,color=blue,thick=6
indf	=where(f_(*,il,0) ne 0,nf)	&print,nf
if (nf ge 1) then oplot,f_(indf,il,0),f_(indf,il,1),color=red,thick=6
indr	=where(xr_(*,0) ne 0,nr)
if (nr ge 1) then oplot,xr_[indr,0],xr_[indr,1],color=orange,psym=-1
coordsphere,1,0,0,0,0,dlat
!noeras=1

!p.position=[0.1,0.40,0.9,0.70]
!y.range=0.99+(!x.range-!x.range(0))
plot,[0,0],[0,0]
for ir=0,nr-1 do begin
 col	=50+200.*float(ir)/float(nr-1)
 indf	=where(field_(*,ir,0) ne 0,nf)
 indc	=where(curr_(*,ir,0) ne 0,nc)
 if (nf ge 1) then rf=sqrt(field_(indf,ir,0)^2+field_(indf,ir,1)^2+field_(indf,ir,2)^2)
 if (nc ge 1) then rc=sqrt(curr_(indc,ir,0)^2+curr_(indc,ir,1)^2+curr_(indc,ir,2)^2)
 if (nf ge 1) then oplot,field_(indf,ir,0),rf,color=col
 if (nc ge 1) and (test eq 2) then oplot,curr_(indc,ir,0),rc,linestyle=2,color=orange
endfor
rl      =sqrt(xl^2+yl^2+zl^2)
oplot,xl,rl,psym=-1,color=blue,thick=6
indf	=where(f_(*,il,0) ne 0,nf)
if (nf ge 1) then begin
 rf	=sqrt(f_(indf,il,0)^2+f_(indf,il,1)^2+f_(indf,il,2)^2)
 oplot,f_(indf,il,0),rf,color=red,thick=6
endif
indr	=where(xr_(*,0) ne 0,nr)
if (nr ge 1) then begin
 rr=sqrt(xr_(indr,0)^2+xr_(indr,1)^2+xr_(indr,2)^2)
 oplot,xr_[indr,0],rr,color=orange,psym=-1
endif
oplot,!x.crange,[1,1]
oplot,!x.crange,[1,1]+hmax,linestyle=2

!p.position=[0.1,0.75,0.45,0.95]
!y.range=[-90,90]
!x.range=minmax(rad_)
!y.title='Misalignment a(r)'
plot,[0,0],!y.crange,linestyle=2
if (nr ge 1) then $
oplot,rad_(indr),dev_r(indr),color=orange,psym=-1
oplot,!x.crange,[1,1],linestyle=2
xyouts_norm,0.1,0.9,'!9a!3!Dmis!N='+string(dev,'(f5.1)')+' deg',1.5

!p.position=[0.55,0.75,0.90,0.95]
!y.range=[-90,90]
!x.range=[0,ns]
a_deg	=a_mis_s*180./!pi
plot,findgen(ns-1),a_deg,ytitle='Misaligment angle along loop'
oplot,!x.crange,[1,1],linestyle=2
statistic,a_deg,a_avg,a_sig
xyouts_norm,0.1,0.9,'!9a!3!Dloop!N='+string(a_avg,'(f5.1)')+' deg',1.5
xyouts_norm,0.1,0.8,'!9a!3!Dsigm!N='+string(a_sig,'(f5.1)')+' deg',1.5

 read,'continue?',yes
 if (yes eq 0) then stop
end
