Program g02apfe

!     G02APF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyev, g02apf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, eigmin, eigtol, errtol, norm, &
                                          theta
      Integer                          :: i, ifail, iter, ldg, ldh, ldx,       &
                                          lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eig(:), g(:,:), h(:,:), work(:),     &
                                          x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02APF Example Program Results'
      Write (nout,*)
      Flush (nout)

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

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

      ldg = n
      ldh = n
      ldx = n
      lwork = 66*n
      Allocate (g(ldg,n),h(ldh,n),x(ldx,n),eig(n),work(lwork))

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

!     Read in the matrix H
      Read (nin,*)(h(i,1:n),i=1,n)

!     Use the defaults for EIGTOL and ERRTOL
      eigtol = -1.E0_nag_wp
      errtol = -1.E0_nag_wp

!     Calculate nearest correlation matrix using target matrix
      ifail = 0

      Call g02apf(g,ldg,n,theta,h,ldh,errtol,eigtol,x,ldx,alpha,iter,eigmin,   &
        norm,ifail)

      ifail = 0
!     Display the symmetrised input matrix
      Call x04caf('General',' ',n,n,g,ldg,'Symmetrised Input Matrix G',ifail)
      Write (nout,*)
      Flush (nout)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,n,x,ldx,'Nearest Correlation Matrix X',      &
        ifail)
      Write (nout,*)
      Write (nout,99999) 'Number of iterations taken:', iter
      Write (nout,*)
      Write (nout,99998) 'ALPHA:                        ', alpha
      Write (nout,*)
      Write (nout,99998) 'Norm value:                   ', norm
      Write (nout,*)
      Write (nout,99998) 'THETA:                        ', theta
      Write (nout,*)
      Write (nout,99998) 'Smallest eigenvalue of target:', eigmin

      ifail = 0
!     Compute the eigenvalues of X
      Call dsyev('N','U',n,x,ldx,eig,work,lwork,ifail)
      Write (nout,*)
      Flush (nout)
      Call x04caf('General',' ',1,n,eig,1,'Eigenvalues of X',ifail)

99999 Format (1X,A,I9)
99998 Format (1X,A,F11.4)

    End Program g02apfe