    PROGRAM g05refe

!      G05REF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g05kff, g05ref, nag_wp, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: lseed = 1, nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: theta
       INTEGER                         :: genid, ifail, ldx, lstate, n, sdx,   &
                                          sorder, subid
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: x(:,:)
       INTEGER                         :: seed(lseed)
       INTEGER, ALLOCATABLE            :: state(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G05REF 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 and order
       READ (nin,*) n, sorder

       IF (sorder==1) THEN
!         X(N,2)
          ldx = n
          sdx = 2
       ELSE
!         X(2,N)
          ldx = 2
          sdx = n
       END IF
       ALLOCATE (x(ldx,sdx))

!      Read in parameter
       READ (nin,*) theta

!      Generate variates
       ifail = 0
       CALL g05ref(n,theta,sorder,state,x,ldx,sdx,ifail)

!      Display the variates
       IF (sorder==1) THEN
!         X(N,2)
          ifail = 0
          CALL x04caf('General',' ',n,2,x,ldx, &
             'Uniform variates with copula joint distribution',ifail)
       ELSE
!         X(2,N)
          ifail = 0
          CALL x04caf('General',' ',2,n,x,ldx, &
             'Uniform variates with copula joint distribution',ifail)
       END IF

    END PROGRAM g05refe
