    PROGRAM g05khfe

!      G05KHF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g05kff, g05khf, g05saf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: lseed = 1, nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: genid, i, ifail, lstate, n, nv, subid
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: x(:,:)
       INTEGER                         :: seed(lseed)
       INTEGER, ALLOCATABLE            :: state(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G05KHF Example Program Results'
       WRITE (nout,*)

!      Skip heading in data file
       READ (nin,*)

!      Read in the base generator information and seed
       READ (nin,*) genid, subid, seed(1)

!      Read in number of streams and sample size for each stream
       READ (nin,*) n, nv

!      Initial call to initialiser to get size of STATE array
       lstate = 0
       ALLOCATE (state(lstate,1))
       ifail = 0
       CALL g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!      Reallocate STATE
       DEALLOCATE (state)
       ALLOCATE (state(lstate,n))

       ALLOCATE (x(nv,n))

!      Prepare N streams
       DO i = 1, n
!         Initialize each stream to a repeatable sequence
          ifail = 0
          CALL g05kff(genid,subid,seed,lseed,state(1,i),lstate,ifail)

!         Prepare the I'th out of N streams
          ifail = 0
          CALL g05khf(n,i,state(1,i),ifail)
       END DO

!      Generate a NV variates, from a uniform distribution, from each stream
       DO i = 1, n
          ifail = 0
          CALL g05saf(nv,state(1,i),x(1,i),ifail)
       END DO

!      Display results
       DO i = 1, n
          WRITE (nout,99998) 'Stream ', i
          WRITE (nout,99999) x(1:nv,i)
          WRITE (nout,*)
       END DO

99999  FORMAT (1X,F10.4)
99998  FORMAT (1X,A,I16)
    END PROGRAM g05khfe
