      PROGRAM random_walk2
*     random walk in two dimensions
      IMPLICIT NONE
      CHARACTER*80 Stmp1_
      REAL*8 x(500), y(500)
      REAL X1, Y1, X2, Y2
      INTEGER IR_, N, nwalkers, im, step
      CALL GWopen(IR_, 0)
      CALL initial(x,y,N,nwalkers,im)
      CALL GWgetwn(IR_, X1, Y1, X2, Y2)
      X1 = X1+(X2-X1)/80
      Y1 = Y2-(Y2-Y1)/24
      DO step = 1, N
         CALL GWsetogn(IR_, 0, -2)
         WRITE(Stmp1_,*) step
         CALL GWputtxt(IR_, X1, Y1, Stmp1_)
         CALL move(x,y,N,nwalkers,im)
         CALL GWflush(IR_, -2)
      END DO
      CALL GWquit(IR_)
      END
C
      SUBROUTINE initial(x,y,N,nwalkers,im)
      IMPLICIT NONE
      REAL*8 x(500), y(500)
      REAL r, xwin, ywin
      REAL dmy, rnd
      INTEGER IR_, N, nwalkers, im, i
      dmy = rnd(-1)
      WRITE(*,'(A,$)') 'number of walkers = '
      READ(*,*) nwalkers
      WRITE(*,'(A,$)') 'total number of steps = '
      READ(*,*) N
      CALL GWclear(IR_, -1)
      CALL compute_aspect_ratio(2*SQRT(REAL(N)),xwin,ywin)
      CALL GWindow(IR_, -xwin, -ywin, xwin, ywin)
*     place N particles at origin
      r = 0.5
      CALL GWcmbmrk(im, 0, 1, 2*r, 13, -1, -1)
      DO i = 1, nwalkers
         x(i) = 0
         y(i) = 0
      END DO
      END
C
      SUBROUTINE move(x,y,N,nwalkers,im)
      IMPLICIT NONE
      REAL*8 x(500), y(500)
      INTEGER IR_, N, nwalkers, im, i
      DO i = 1, nwalkers
         CALL choice(x,y,i)
         CALL GWputcmb(IR_, im, REAL(x(i)), REAL(y(i)), 0.0, 0.0, 0)
      END DO
      END
C
      SUBROUTINE choice(x,y,i)
      IMPLICIT NONE
      REAL*8 p, x(500), y(500)
      REAL rnd
      INTEGER i
      p = rnd(0)
      IF(p .LE. 0.25D0) THEN
         x(i) = x(i) + 1
      ELSE IF(p .LE. 0.5D0) THEN
         x(i) = x(i) - 1
      ELSE IF(p .LE. 0.75D0) THEN
         y(i) = y(i) - 1
      ELSE
         y(i) = y(i) + 1
      END IF
      END
