    PROGRAM g13adfe

!      G13ADF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g13adf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: rv, xv
       INTEGER                         :: ifail, nk, npar, nwa, pp, qp
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: par(:), r(:), wa(:)
       INTEGER                         :: isf(4), mr(7)
!      .. Intrinsic Functions ..
       INTRINSIC                          max
!      .. Executable Statements ..
       WRITE (nout,*) 'G13ADF Example Program Results'
       WRITE (nout,*)

!      Skip heading in data file
       READ (nin,*)

!      Read in problem size and variance
       READ (nin,*) nk
       READ (nin,*) xv

       ALLOCATE (r(nk))

!      Read in data
       READ (nin,*) r(1:nk)

!      Read in the orders
       READ (nin,*) mr(1:7)

!      Calculate NPAR
       npar = mr(1) + mr(3) + mr(4) + mr(6)

       pp = max(mr(1),mr(4))
       qp = max(mr(3),mr(6))
       nwa = max(pp**2+pp,4*(qp+1))
       ALLOCATE (par(npar),wa(nwa))

!      Calculate preliminary estimates
       ifail = -1
       CALL g13adf(mr,r,nk,xv,npar,wa,nwa,par,rv,isf,ifail)
       IF (ifail/=0) THEN
          IF (ifail<7) THEN
             GO TO 20
          END IF
       END IF

!      Display results
       WRITE (nout,99999) 'Parameter estimation success/failure indicator', &
          isf(1:4)
       WRITE (nout,*)
       WRITE (nout,99998) 'ARIMA model parameter values ', par(1:npar)
       WRITE (nout,*)
       WRITE (nout,99998) 'Residual variance', rv

20     CONTINUE

99999  FORMAT (1X,A,4I4)
99998  FORMAT (1X,A,5F10.5)
    END PROGRAM g13adfe
