!====================================================================
! 1. compile:
!> gfortran rw.f90 drandom.f90 -o rw
! 2. run and save standard output in a file
!> ./rw <Nwalk> <Nstep>
! where Nwalk the number of walks and Nstep the length N of the walk.
! 3. Output: 
! The first 50 configurations are explicitly printed in the file data order to 
! visualize them. The format is:
! <Nwalk>  <x> <y>
! so that the following command puts each configuration in a file 
! rwalk.<Nwalk>:
!> awk '{print $2,$3 > "rwalk." $1}' data
! The other data printed in dataR is the final position x,y, the distance 
! squared R^2 and the number of loops n in the format:
! <Nwalk> <R^2> <x> <y> <n>
! and the average <R^2> can be computed for example by the command:
!> awk '{print $2}' dataR| ./average
!====================================================================
program random_walks
 implicit none
 integer       :: Nwalk,Nstep
 real(8)       :: drandom
 integer       :: ir
 integer(8)    :: iwalk,istep,n
 integer(8)    :: x,y
 real(8)       :: xr,yr
!-------------------------------
 call init(Nwalk,Nstep)
 do iwalk = 1, Nwalk
  x=0;y=0;n=0
  do istep=1,Nstep
   ir = INT(drandom()*4)
   select case(ir)
    case(0)
     x = x + 1
    case(1)
     x = x - 1
    case(2)
     y = y + 1
    case(3)
     y = y - 1
    end select
    if(iwalk .le. 50) write(21,'(3I18)')iwalk,x,y
    if( x .eq. 0 .and. y .eq. 0) n = n + 1
  enddo !do istep=1,Nstep
  xr = DBLE(x); yr = DBLE(y)
  write(20,'(I12,G28.17,3I18)')iwalk,xr*xr+yr*yr,x,y,n
 enddo !do iwalk = 1, Nwalk
end program random_walks
!====================================================================
subroutine init(Nwalk,Nstep) 
 character(20) :: arg
 integer       :: seed
 common /randoms/ seed
!Read Nwalk and Nstep from command line arguments:
 if( iargc() .ne. 2)then
  print *,'Usage: rw  <Nwalk> <Nstep>'
  stop
 endif
 call getarg(1,arg); read(arg,*) Nwalk
 call getarg(2,arg); read(arg,*) Nstep
!Seed drandom from /dev/urandom
 open(unit=13, file='/dev/urandom', access='stream', & 
      form='unformatted')
 read (13) seed
 close(13)
 open(unit=20,file='dataR')
 open(unit=21,file='data')
end subroutine init
