! subroutine for the evaluation of the relation between precision and
! spatial resolution

         module m_optsc

contains
         subroutine opt_scale(x,y,vx,vy,dv,n,nc,bin_spt)

         use param_run

         implicit none

         real, dimension (:), intent(in) :: vx,vy,dv,x,y
         integer, intent(in) :: n,nc
         integer, intent(out) :: bin_spt

         real, dimension (:), allocatable :: dvrel,xa,ya,vector
         integer i,ii,j,na,np_vnull
         real dmoy,dmax,d_i,d



         allocate(dvrel(n),xa(n),ya(n),vector(n))
         dvrel=0.; xa=0.; ya=0.; vector=0.

! Calcul du pourcentage d'erreur en chaque point de mesure de v
         where (vx(1:n)**2+vy(1:n)**2 /=0.) &
              dvrel(1:n)=dv(1:n)/sqrt(vx(1:n)**2+vy(1:n)**2)

         np_vnull=count(vx(1:n)**2+vy(1:n)**2 ==0.)
         if (np_vnull /= 0) print*,'nb of pts with v=0   ',np_vnull

! Calcul de la distance moyenne entre plus proches voisins pour une
! precision donnee par l'utilisateur

         open(unit=1,file='precision',position='append')
         if (nc == 1) write(1,*) prec,timestep*n_ech

! selection des points a precision donnee
          where(dvrel <= prec .and. dvrel /= 0.)
             xa=x; ya=y
          endwhere

          xa=pack(xa, xa /= 0., vector)
          ya=pack(ya, ya /= 0., vector)
          na=count(xa /=0.)

! On laisse de coté l'effet de la precision 14/11/2006
          dmoy=0.
          dmax=abs(maxval(x)-minval(x))+abs(maxval(y)-minval(y))
          na=count(x /=0.)
          do i=1,na
           d_i=dmax
           do j=i+1,na
            d=sqrt((x(i)-x(j))**2+(y(i)-y(j))**2)
            d_i = min(d_i,d)
           enddo
           dmoy=dmoy+d_i/na
          enddo
         
         write(1,100) nc,prec,na,dmoy
         bin_spt=nint(dmoy)

         close(1)
100          format(i3,1x,0pf6.3,1x,i6,1pd12.5)
         end subroutine

         end module
