    PROGRAM g13bgfe

!      G13BGF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g13bgf, nag_wp, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: i, ifail, iwa, kzef, ldxxyn, ncc,    &
                                          nis, nnv, npara, nser, nsttf
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: para(:), res(:), sttf(:), wa(:),     &
                                          xxyn(:,:)
       INTEGER                         :: mr(7)
       INTEGER, ALLOCATABLE            :: mt(:,:)
!      .. Intrinsic Functions ..
       INTRINSIC                          max
!      .. Executable Statements ..
       WRITE (nout,*) 'G13BGF Example Program Results'
       WRITE (nout,*)

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

!      Read in the problem size
       READ (nin,*) nsttf, nser, nnv, kzef

!      Number of input series
       nis = nser - 1

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

       ldxxyn = nnv
       ALLOCATE (mt(4,nser))

!      Read in transfer function
       DO i = 1, nis
          READ (nin,*) mt(1:4,i)
       END DO

!      Calculate NPARA
       npara = 0
       DO i = 1, nis
          npara = npara + mt(2,i) + mt(3,i)
       END DO
       npara = npara + mr(1) + mr(3) + mr(4) + mr(6) + nser

       ldxxyn = nnv
       ncc = 4*(mr(1)+mr(3)+mr(4)+mr(6))
       iwa = nnv + 2*nsttf + max(nnv,nsttf) + max(nnv,ncc)
       ALLOCATE (sttf(nsttf),xxyn(ldxxyn,nser),res(nnv),para(npara),wa(iwa))

!      Read in state set
       READ (nin,*) sttf(1:nsttf)

!      Read in parameters
       READ (nin,*) para(1:npara)

!      Read in new observations
       READ (nin,*) (xxyn(i,1:nser),i=1,nnv)

       ifail = 0
       CALL g13bgf(sttf,nsttf,mr,nser,mt,para,npara,nnv,xxyn,ldxxyn,kzef,res, &
          wa,iwa,ifail)

!      Display results
       WRITE (nout,*) 'The updated state set'
       WRITE (nout,99999) sttf(1:nsttf)
       WRITE (nout,*)
       WRITE (nout,*) 'The residuals (after differencing)'
       WRITE (nout,99998) (i,res(i),i=1,nnv)
       WRITE (nout,*)
       FLUSH (nout)
       ifail = 0
       CALL x04caf('General',' ',nnv,nser,xxyn,ldxxyn, &
          'The values of z(t) and n(t)',ifail)
       WRITE (nout,99997) 'The first ', nis, &
          ' columns hold the z(t) and the last column the n(t)'

99999  FORMAT (1X,6F10.4)
99998  FORMAT (1X,I4,F10.4)
99997  FORMAT (1X,A,I0,A)
    END PROGRAM g13bgfe
