    Program g05phfe

!     G05PHF Example Program Text

!     Mark 24 Release. NAG Copyright 2012.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05phf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: avar, var, xmean
      Integer                          :: genid, ifail, ip, iq, lr, lstate,    &
                                          mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: phi(:), r(:), theta(:), x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G05PHF 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 number of coefficients
      Read (nin,*) ip, iq

      lr = ip + iq + 6 + max(ip,iq+1)
      Allocate (phi(ip),theta(iq),x(n),r(lr))

!     Read in mean
      Read (nin,*) xmean

!     Read in autoregressive coefficients
      If (ip>0) Then
        Read (nin,*) phi(1:ip)
      End If

!     Read in moving average coefficients
      If (iq>0) Then
        Read (nin,*) theta(1:iq)
      End If

!     Read in variance
      Read (nin,*) avar

!     Using a single call to G05PHF, so set up reference vector
!     and generate values in one go
      mode = 2

      ifail = 0
      Call g05phf(mode,n,xmean,ip,phi,iq,theta,avar,r,lr,state,var,x,ifail)

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

99999 Format (1X,F12.4)
    End Program g05phfe
