    PROGRAM g03adfe

!      G03ADF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g03adf, 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, iwk, ldcvx, ldcvy, lde,    &
                                          ldz, lwt, m, mcv, n, ncv, nx, ny
       CHARACTER (1)                   :: weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: cvx(:,:), cvy(:,:), e(:,:), wk(:),   &
                                          wt(:), z(:,:)
       INTEGER, ALLOCATABLE            :: isz(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          max
!      .. Executable Statements ..
       WRITE (nout,*) 'G03ADF Example Program Results'
       WRITE (nout,*)

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

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

       IF (weight=='W' .OR. weight=='w') THEN
          lwt = n
       ELSE
          lwt = 0
       END IF
       IF (nx>=ny) THEN
          iwk = n*nx + nx*ny + max(5*(nx-1)+nx*nx,n*ny) + 1
          lde = ny
          mcv = ny
       ELSE
          iwk = n*ny + nx*ny + max(5*(ny-1)+ny*ny,n*nx) + 1
          lde = nx
          mcv = nx
       END IF
       ldz = n
       ldcvx = nx
       ldcvy = ny
       ALLOCATE (z(ldz,m),isz(m),wt(lwt),e(lde,6),cvx(ldcvx,mcv), &
          cvy(ldcvy,mcv),wk(iwk))

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

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

!      Use default tolerance
       tol = 0.0E0_nag_wp

!      Perform canonical correlation analysis
       ifail = 0
       CALL g03adf(weight,n,m,z,ldz,isz,nx,ny,wt,e,lde,ncv,cvx,ldcvx,mcv,cvy, &
          ldcvy,tol,wk,iwk,ifail)

!      Display results
       WRITE (nout,99999) 'Rank of X = ', nx, ' Rank of Y = ', ny
       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',' ',ny,ncv,cvy,ldcvy, &
          'Canonical Coefficients for Y',ifail)

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