    PROGRAM g02bufe

!      G02BUF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dscal, g02buf, nag_wp, x04ccf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       REAL (KIND=nag_wp), PARAMETER   :: one = 1.0_nag_wp
       INTEGER, PARAMETER              :: inc1 = 1, nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: alpha, sw
       INTEGER                         :: i, ifail, lc, ldx, lwt, m, n
       CHARACTER (1)                   :: mean, weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: c(:), wmean(:), wt(:), x(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G02BUF Example Program Results'
       WRITE (nout,*)
       FLUSH (nout)

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

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

       IF (weight=='W' .OR. weight=='w') THEN
          lwt = n
       ELSE
          lwt = 0
       END IF
       ldx = n
       lc = (m*m+m)/2
       ALLOCATE (wt(lwt),x(ldx,m),wmean(m),c(lc))

!      Read in data
       IF (lwt>0) THEN
          READ (nin,*) wt(1:n)
       END IF
       READ (nin,*) (x(i,1:m),i=1,n)

!      Calculate sums of squares and cross-products matrix
       ifail = 0
       CALL g02buf(mean,weight,n,m,x,ldx,wt,sw,wmean,c,ifail)

!      Display results
       WRITE (nout,*) 'Means'
       WRITE (nout,99999) wmean(1:m)
       WRITE (nout,*)
       WRITE (nout,*) 'Weights'
       WRITE (nout,99999) wt(1:n)
       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)
!         The NAG name equivalent of dscal is f06edf
          CALL dscal(lc,alpha,c,inc1)
          WRITE (nout,*)
          FLUSH (nout)
          ifail = 0
          CALL x04ccf('Upper','Non-unit',m,c,'Variance matrix',ifail)
       END IF

99999  FORMAT (1X,6F14.4)
    END PROGRAM g02bufe
