    PROGRAM nag_tsa_kalman_ex02

      ! Example Program Text nag_tsa_kalman
      ! NAG fl90, Release 4. NAG Copyright 2000.

      ! .. Use Statements ..
      USE nag_tsa_kalman, ONLY : nag_kalman_sqrt_cov_invar, nag_kalman_init
      USE nag_tri_lin_sys, ONLY : nag_tri_lin_sol
      USE nag_examples_io, ONLY : nag_std_in, nag_std_out
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Intrinsic Functions ..
      INTRINSIC DOT_PRODUCT, KIND, LOG
      ! .. Parameters ..
      INTEGER, PARAMETER :: wp = KIND(1.0D0)
      REAL (wp), PARAMETER :: zero = 0.0_wp
      ! .. Local Scalars ..
      INTEGER :: i, l, m, n, ncall, step
      REAL (wp) :: dev
      ! .. Local Arrays ..
      REAL (wp), ALLOCATABLE :: a(:,:), b(:,:), c(:,:), h(:,:), p(:,:), &
       q(:,:), r(:,:), resid(:), s(:,:), x(:), xt(:), y(:)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_tsa_kalman_ex02'

      READ (nag_std_in,*)          ! Skip heading in data file
      READ (nag_std_in,*) ncall, n, m, l

      ALLOCATE (a(n,n),b(n,l),c(m,n),h(m,m),p(n,n),q(l,l),r(m,m),s(n,n),x(n), &
       xt(n),y(m),resid(m))        ! Allocate storage

      READ (nag_std_in,*) xt
      READ (nag_std_in,*) (a(i,:),i=1,n)
      READ (nag_std_in,*) (b(i,:),i=1,n)
      READ (nag_std_in,*) (c(i,:),i=1,m)
      READ (nag_std_in,*) (r(i,:),i=1,m)
      READ (nag_std_in,*) (q(i,:),i=1,l)
      s = zero

      CALL nag_kalman_init(a(1:n-m,1:n-m),b(1:n-m,1:l),s(1:n-m,1:n-m),q=q)

      dev = zero
      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) ' step        Residuals'

      ! Loop through data

      DO step = 1, ncall
        READ (nag_std_in,*) y

        ! Perform time and measurement update

        IF (step==1) THEN

          CALL nag_kalman_sqrt_cov_invar(s,a,b,c,r,q=q,h=h,resid=resid,y=y, &
           xt=xt)

        ELSE

          CALL nag_kalman_sqrt_cov_invar(s,a,b,c,r,q=q,h=h,resid=resid,y=y, &
           x=x,xt=xt,p=p)

        END IF
        WRITE (nag_std_out,'(i4,4f10.4)') step, resid

        ! Update loglikelihood

        CALL nag_tri_lin_sol('l',h,resid)

        dev = dev + DOT_PRODUCT(resid,resid)
        DO i = 1, m
          dev = dev + 2.0_wp*LOG(h(i,i))
        END DO
      END DO

      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) ' Final X(i+1|i) '
      WRITE (nag_std_out,'(10f10.4)') x
      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) ' Final Value of P'

      DO i = 1, n
        WRITE (nag_std_out,'(10f10.4)') p(i,1:i)
      END DO
      WRITE (nag_std_out,*)
      WRITE (nag_std_out,'(A,e10.4)') ' Deviance = ', dev

      DEALLOCATE (a,b,c,h,p,q,r,s,x,xt,y,resid) ! Deallocate storage

    END PROGRAM nag_tsa_kalman_ex02
