module walkutils
   implicit none
   integer,parameter::N=10000, M=100
   integer,dimension(N)::X,Y
   real,dimension(N)::R2
end module

program ranwalk
   use walkutils
   implicit none
   integer::i,j
   X=0; Y=0; R2=0;
   do i=1,M
      call walk()
   enddo
   open(10,file="ranwalk.dat")
   do j=100,N,100
      write(10,*) sqrt(real(j)),R2(j)
   enddo
   close(10)
   
end program

! This subroutine lets the random walker walk N steps
subroutine walk()
   use walkutils
   implicit none
   integer::j, Idir, dj
   real::r
   X=0; Y=0;
   X(1)=0; Y(1)=0;
   do j=2,N
      call random_seed
      call random_number(r)
      Idir=int(4.0*r)
      select case(Idir)
      case(0) ! move to E
         X(j)=X(j-1)+1
         Y(j)=Y(j-1)
      case(1) ! move to W
         X(j)=X(j-1)-1
         Y(j)=Y(j-1)
      case(2) ! move to N
         Y(j)=Y(j)+1
         X(j)=X(j-1)
      case(3) ! move to S
         Y(j)=Y(j)-1
         X(j)=X(j-1)
      end select
      dj=sqrt(real(X(j)**2+Y(j)**2))
      R2(j)=R2(j)+dj/real(M)
   enddo
end subroutine
