PROGRAM g05tffe

!      G05TFF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g05kff, g05tff, nag_wp, x02amf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: a
       INTEGER                         :: genid, ifail, lr, lstate, mode, n,   &
                                          subid
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: r(:)
       INTEGER                         :: seed(lseed)
       INTEGER, ALLOCATABLE            :: state(:), x(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          int
!      .. Executable Statements ..
       WRITE (nout,*) 'G05TFF 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,*) a

!      Use suggested value for LR
       IF (1.0E0_nag_wp-a<x02amf()) THEN
!         A is too close to 1.0 to calculate LR, so
!         set to MAXLR, which means we will use MODE = 3
          lr = maxlr
       ELSE
          lr = int(1.8E1_nag_wp+4.0E1_nag_wp/(1.0E0_nag_wp-a))
       END IF

       lr = maxlr
!      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 (x(n),r(lr))

!      Generate the variates
       ifail = 0
       CALL g05tff(mode,n,a,r,lr,state,x,ifail)

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

99999  FORMAT (1X,I12)
    END PROGRAM g05tffe