    PROGRAM g03acfe

!      G03ACF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g03acf, nag_wp, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: tol
       INTEGER                         :: i, ifail, irankx, iwk, ldcvm, ldcvx, &
                                          lde, ldx, lwt, m, n, ncv, ng, nx
       CHARACTER (1)                   :: weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: cvm(:,:), cvx(:,:), e(:,:), wk(:),   &
                                          wt(:), x(:,:)
       INTEGER, ALLOCATABLE            :: ing(:), isx(:), nig(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          max, min
!      .. Executable Statements ..
       WRITE (nout,*) 'G03ACF Example Program Results'
       WRITE (nout,*)

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

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

       SELECT CASE (weight)
       CASE ('W','w','V','v')
          lwt = n
       CASE DEFAULT
          lwt = 0
       END SELECT
       ldx = n
       ldcvm = ng
       lde = min(nx,ng-1)
       ldcvx = nx
       IF (nx>=ng-1) THEN
          iwk = n*nx + max(5*(nx-1)+(nx+1)*nx,n) + 1
       ELSE
          iwk = n*nx + max(5*(nx-1)+(ng-1)*nx,n) + 1
       END IF
       ALLOCATE (x(ldx,m),isx(m),ing(n),wt(lwt),nig(ng),cvm(ldcvm,nx), &
          e(lde,6),cvx(ldcvx,nx),wk(iwk))

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

!      Read in variable inclusion flags
       READ (nin,*) isx(1:m)

!      Use default tolerance
       tol = 0.0E0_nag_wp

!      Perform canonical variate analysis
       ifail = 0
       CALL g03acf(weight,n,m,x,ldx,isx,nx,ing,ng,wt,nig,cvm,ldcvm,e,lde,ncv, &
          cvx,ldcvx,tol,irankx,wk,iwk,ifail)

!      Display results
       WRITE (nout,99999) 'Rank of X = ', irankx
       WRITE (nout,*)
       WRITE (nout,*) &
          'Canonical    Eigenvalues Percentage     CHISQ      DF     SIG'
       WRITE (nout,*) 'Correlations              Variation'
       WRITE (nout,99998) (e(i,1:6),i=1,ncv)
       WRITE (nout,*)
       FLUSH (nout)
       ifail = 0
       CALL x04caf('General',' ',nx,ncv,cvx,ldcvx, &
          'Canonical Coefficients for X',ifail)
       WRITE (nout,*)
       FLUSH (nout)
       ifail = 0
       CALL x04caf('General',' ',ng,ncv,cvm,ldcvm,'Canonical variate means', &
          ifail)

99999  FORMAT (1X,A,I0)
99998  FORMAT (1X,2F12.4,F11.4,F10.4,F8.1,F8.4)
    END PROGRAM g03acfe
