    PROGRAM g02btfe

!      G02BTF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g02btf, nag_wp, x04ccf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       REAL (KIND=nag_wp), PARAMETER   :: one = 1.0_nag_wp
       REAL (KIND=nag_wp), PARAMETER   :: zero = 0.0_nag_wp
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: alpha, sw, wt
       INTEGER                         :: i, ifail, incx, lc, m, n, nprint
       CHARACTER (1)                   :: mean
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: c(:), v(:), x(:), xbar(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          mod
!      .. Executable Statements ..
       WRITE (nout,*) 'G02BTF Example Program Results'
       WRITE (nout,*)

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

!      Read in problem size
       READ (nin,*) mean, m, n, nprint

       lc = (m*m+m)/2
       ALLOCATE (x(m),xbar(m),c(lc),v(lc))

!      Elements of X are stored consecutively
       incx = 1

!      Loop over each observation individually, updating the sums of squares
!      and cross-product matrix at each iteration
       sw = zero
       i = 0
DATA_LP: DO
          READ (nin,*,IOSTAT=ifail) wt, x(1:m)
          IF (ifail/=0) THEN
!            Finished processing all the data
             EXIT DATA_LP
          END IF

          i = i + 1

!         Update the sums of squares and cross-products matrix
          ifail = 0
          CALL g02btf(mean,m,wt,x,incx,sw,xbar,c,ifail)

!         Display the results, either at the end or every NPRINT iterations
          IF (mod(i,nprint)==0 .OR. i==n) THEN
             WRITE (nout,*) '---------------------------------------------'
             WRITE (nout,99999) 'Observation: ', i, '      Weight = ', wt
             WRITE (nout,*) '---------------------------------------------'
             WRITE (nout,*)
             WRITE (nout,*) 'Means'
             WRITE (nout,99998) xbar(1:m)
             WRITE (nout,*)
             FLUSH (nout)
             ifail = 0
             CALL x04ccf('Upper','Non-unit',m,c, &
                'Sums of squares and cross-products',ifail)

!            Convert the sums of squares and cross-products to a variance matrix
             IF (sw>one) THEN
                alpha = one/(sw-one)
                v(1:lc) = alpha*c(1:lc)
                WRITE (nout,*)
                FLUSH (nout)
                ifail = 0
                CALL x04ccf('Upper','Non-unit',m,v,'Variance matrix',ifail)
             END IF
             WRITE (nout,*)
          END IF
       END DO DATA_LP

99999  FORMAT (1X,A,I4,A,F13.4)
99998  FORMAT (1X,4F14.4)
    END PROGRAM g02btfe
