    PROGRAM g05ndfe

!      G05NDF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g05kff, g05ndf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: lseed = 1, nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: genid, i, ifail, lstate, m, n, pm,   &
                                          subid
!      .. Local Arrays ..
       INTEGER, ALLOCATABLE            :: ipop(:), isampl(:), state(:)
       INTEGER                         :: seed(lseed)
!      .. Executable Statements ..
       WRITE (nout,*) 'G05NDF 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)

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

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

!      Initialize the generator to a repeatable sequence
       ifail = 0
       CALL g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!      Read in sample size
       READ (nin,*) n

       ALLOCATE (ipop(n))

!      Display title
       WRITE (nout,99999) ' Samples from the first ', n, ' integers'
       WRITE (nout,*)
       WRITE (nout,*) ' Sample size     Values'

!      Initialize the population
       DO i = 1, n
          ipop(i) = i
       END DO

!      Dummy allocation
       ALLOCATE (isampl(1))

!      Loop over different sample sizes
       pm = 0
D_LP:  DO
          READ (nin,*,IOSTAT=ifail) m
          IF (ifail/=0) THEN
             EXIT D_LP
          END IF

!         Reallocate ISAMPL
          IF (pm/=m) THEN
             DEALLOCATE (isampl)
             ALLOCATE (isampl(m))
             pm = m
          END IF

!         Generate sample
          ifail = 0
          CALL g05ndf(ipop,n,isampl,m,state,ifail)

!         Display the results
          WRITE (nout,99998) m, isampl(1:m)
       END DO D_LP

99999  FORMAT (1X,A,I0,A)
99998  FORMAT (1X,I6,9X,8(1X,I3))
    END PROGRAM g05ndfe
