    PROGRAM g02aefe

!      G02AEF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgemm, g02aef, nag_wp, x04caf
!      .. 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)              :: errtol, nrmpgd
       INTEGER                         :: feval, i, ifail, iter, k, lda, ldg,  &
                                          ldx, maxit, n
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), g(:,:), x(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G02AEF Example Program Results'
       WRITE (nout,*)
       FLUSH (nout)

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

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

       lda = n
       ldg = n
       ldx = n
       ALLOCATE (a(lda,n),g(ldg,n),x(ldx,n))

!      Read in the matrix G
       READ (nin,*) (g(i,1:n),i=1,n)

!      Use the defaults for ERRTOL and MAXIT
       errtol = zero
       maxit = 0

!      Set k value
       k = 2

!      Calculate the nearest factor loading matrix
       ifail = 0

       CALL g02aef(g,ldg,n,k,errtol,maxit,x,ldx,iter,feval,nrmpgd,ifail)

!      Display results
       ifail = 0
       CALL x04caf('General',' ',n,k,x,ldx,'Factor Loading Matrix X',ifail)
       WRITE (nout,*)
       WRITE (nout,99999) 'Number of steps taken:', iter
       WRITE (nout,99998) 'Number of function evaluations:', feval

!      Generate Nearest k factor correlation matrix
!      The NAG name equivalent of dgemm is f06yaf
       CALL dgemm('N','T',n,n,k,one,x,n,x,n,zero,a,n)
       DO i = 1, n
          a(i,i) = one
       END DO
       WRITE (nout,*)
       FLUSH (nout)
       ifail = 0
       CALL x04caf('General',' ',n,n,a,lda,'Nearest Correlation Matrix',ifail)

99999  FORMAT (1X,A,I11)
99998  FORMAT (1X,A,I9)

    END PROGRAM g02aefe
