    PROGRAM g01nbfe

!      G01NBF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g01nbf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: abserr, beta, eps, y0
       INTEGER                         :: i, ifail, j, l1, l2, lda, ldb, ldc,  &
                                          ldsig, lmax, lwk, n
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:,:), c(:,:), ela(:),      &
                                          emu(:), rmom(:), sigma(:,:), wk(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G01NBF Example Program Results'
       WRITE (nout,*)

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

!      Read in the problem size
       READ (nin,*) beta, y0
       READ (nin,*) n, l1, l2

       lda = n
       ldb = n
       ldc = n
       ldsig = n
       lwk = 3*n*n + (8+l2)*n
       ALLOCATE (a(lda,n),b(ldb,n),c(ldc,n),ela(n),emu(n),sigma(ldsig,n), &
          wk(lwk),rmom(l2-l1+1))

!      Compute A, EMU, and SIGMA for simple autoregression
       DO i = 1, n
          DO j = i, n
             a(j,i) = 0.0E0_nag_wp
             b(j,i) = 0.0E0_nag_wp
          END DO
       END DO
       DO i = 1, n - 1
          a(i+1,i) = 0.5E0_nag_wp
          b(i,i) = 1.0E0_nag_wp
       END DO
       emu(1) = y0*beta
       DO i = 1, n - 1
          emu(i+1) = beta*emu(i)
       END DO
       sigma(1,1) = 1.0E0_nag_wp
       DO i = 2, n
          sigma(i,i) = beta*beta*sigma(i-1,i-1) + 1.0E0_nag_wp
       END DO
       DO i = 1, n
          DO j = i + 1, n
             sigma(j,i) = beta*sigma(j-1,i)
          END DO
       END DO

!      Use default accuracy
       eps = 0.0E0_nag_wp

!      Compute moments
       ifail = -1
       CALL g01nbf('Ratio','Mean',n,a,lda,b,ldb,c,ldc,ela,emu,sigma,ldsig,l1, &
          l2,lmax,rmom,abserr,eps,wk,ifail)
       IF (ifail/=0) THEN
          IF (ifail<6) THEN
             GO TO 20
          END IF
       END IF

!      Display results
       WRITE (nout,99999) ' N = ', n, ' BETA = ', beta, ' Y0 = ', y0
       WRITE (nout,*)
       WRITE (nout,*) '      Moments'
       WRITE (nout,*)
       j = 0
       DO i = l1, lmax
          j = j + 1
          WRITE (nout,99998) i, rmom(j)
       END DO

20     CONTINUE

99999  FORMAT (A,I3,2(A,F6.3))
99998  FORMAT (I3,E12.3)
    END PROGRAM g01nbfe
