c===========================================================
c     Demonstrates use of the real*8 (pseudo-)random number 
c     generator, 'drand48' available on the lnx machines via
c     the 'p410f' utility library.
c 
c     usage: tdrand48 <nrand> [<seed>]
c
c     where <nrand> is the number of random numbers on the 
c     interval (0..1) to be generated, and <seed> is the 
c     optional, integer-valued "seed" for the random number 
c     generator.  
c
c     The program outputs the random numbers generated to 
c     standard output (one per line), and their average to 
c     standard error.  In the limit of very large <nrand>, 
c     this average should approach 0.5 since 'drand48' 
c     generates numbers uniformly distributed on the unit 
c     interval.
c
c     Note carefully that for fixed seed, 'drand48' (and 
c     most other pseudo-random number generators) will 
c     ALWAYS RETURN THE SAME SEQUENCE OF NUMBERS!  In 
c     fact, the purpose of seeding the generator is precisely
c     to produce variation ("randomness") in the sequence
c     of iterates produced.  If 'drand48' is not explicitly 
c     seeded via 'srand48' a specific default seed value is 
c     used.   
c===========================================================
      program         tdrand48

      implicit        none

      integer         iargc,       i4arg
      real*8          drand48

      real*8          ranval,      sum
      integer         i,           nrand

      if( iargc() .lt. 1 ) go to 900
      nrand = i4arg(1,-1)
      if( nrand .le. 0 ) go to 900
      if( iargc() .gt. 1 ) then
         call srand48(i4arg(2,0))
      end if

      sum = 0.0d0
      do i = 1 , nrand
c-----------------------------------------------------------
c        Generate a random number
c-----------------------------------------------------------
         ranval = drand48()
         sum = sum + ranval
         write(*,*) ranval
      end do

      write(0,*) 
      write(0,*) 'Average: ', sum / nrand

      stop

 900  continue
         write(0,*) 'usage: tdrand48 <nrand> [<seed>]'
      stop
      end