    Program g05tdfe

!     G05TDF Example Program Text

!     Mark 24 Release. NAG Copyright 2012.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, ip1, itype, lr,        &
                                          lstate, mode, n, np, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: ceiling, real
!     .. Executable Statements ..
      Write (nout,*) 'G05TDF 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

!     Read in the distribution parameters
      Read (nin,*) np, ip1, itype

!     Use suggested value for LR
      lr = 10 + ceiling(1.4E0_nag_wp*real(np,kind=nag_wp))

!     Generate and set up reference vector in one go
      mode = 2

      Allocate (p(np),x(n),r(lr))

!     Read in probabilities
      Read (nin,*) p(1:np)

!     Generate the variates
      ifail = 0
      Call g05tdf(mode,n,p,np,ip1,itype,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tdfe
