    PROGRAM g05tgfe

!      G05TGF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g05kff, g05tgf, nag_wp, x04eaf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: pmax
       INTEGER                         :: genid, ifail, k, ldx, lr, lstate, m, &
                                          mode, n, subid
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: p(:), r(:)
       INTEGER                         :: seed(lseed)
       INTEGER, ALLOCATABLE            :: state(:), x(:,:)
!      .. Intrinsic Functions ..
       INTRINSIC                          int, maxval, real, sqrt
!      .. Executable Statements ..
       WRITE (nout,*) 'G05TGF Example Program Results'
       WRITE (nout,*)
       FLUSH (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,*) m, k

       ldx = n
       ALLOCATE (x(ldx,k),p(k))

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

!      Use suggested value for LR
       pmax = maxval(p(1:k))
       lr = int(3.0E1_nag_wp+2.0E1_nag_wp*sqrt(real(m, &
          kind=nag_wp)*pmax*(1.0E0_nag_wp-pmax)))

!      If R is a reasonable size use MODE = 2
!      else do not reference R and use MODE = 3
       IF (lr<maxlr) THEN
          mode = 2
       ELSE
          mode = 3
          lr = 0
       END IF

       ALLOCATE (r(lr))

!      Generate the variates
       ifail = 0
       CALL g05tgf(mode,n,m,k,p,r,lr,state,x,ldx,ifail)

!      Display the variates
       ifail = 0
       CALL x04eaf('General',' ',n,k,x,ldx,' ',ifail)

    END PROGRAM g05tgfe
