Program g13bgfe

!     G13BGF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. 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 Procedures ..
      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