    PROGRAM g02bwfe

!      G02BWF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g02buf, g02bwf, nag_wp, x04ccf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: sw
       INTEGER                         :: i, ifail, ldx, lr, lwt, m, n
       LOGICAL                         :: zero_var
       CHARACTER (1)                   :: mean, weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: r(:), wmean(:), wt(:), x(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G02BWF Example Program Results'
       WRITE (nout,*)
       FLUSH (nout)

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

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

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

!      Read in data
       READ (nin,*) wt(1:n)
       READ (nin,*) (x(i,1:m),i=1,n)

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

!      Calculate the correlation matrix
       ifail = -1
       CALL g02bwf(m,r,ifail)
       IF (ifail/=0) THEN
          IF (ifail==2) THEN
             zero_var = .TRUE.
          ELSE
             GO TO 20
          END IF
       ELSE
          zero_var = .FALSE.
       END IF

!      Display the results
       ifail = 0
       CALL x04ccf('Upper','Non-unit',m,r,'Correlation matrix',ifail)
       IF (zero_var) THEN
          WRITE (nout,*) ' NOTE: some variances are zero'
       END IF

20     CONTINUE

    END PROGRAM g02bwfe
