!      G02AAF simple timing program
!      NAG COPYRIGHT 2010.

!      G02AAF: Computes the nearest correlation matrix to a real square 
!              matrix, using the method of Qi and Sun

!      This program is adapted from the example given at:
!        http://www.nag.co.uk/numeric/FL/nagdoc_fl22/xhtml/G02/g02aaf.xml
!      with randomly generated input data based upon the program sizes
!      specified by the user.

!      The extra input argument "IO" is a Fortran logical value to specify
!      whether or not the numerical results should be printed to the screen.

!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: NOUT = 6
!      .. Local Scalars ..
       DOUBLE PRECISION                :: NRMGRD, T0, T1
       INTEGER                         :: FEVAL, I, IFAIL, IPTR, ITER, J, LDA, &
                                          LDX, N,NUMARGS
       LOGICAL                         :: IO
!      .. Local Arrays ..
       DOUBLE PRECISION, ALLOCATABLE   :: A(:,:), X(:,:)
       CHARACTER(LEN=10)               :: arg1,arg2
!      .. External Subroutines ..
       EXTERNAL                           G02AAF
!      .. Executable Statements ..
       CONTINUE
       NUMARGS=IARGC()
       IF(NUMARGS<2) THEN
          WRITE(*,'() ') "usage ./foo N IO"
       END IF 
       CALL GETARG(1,arg1)
       CALL GETARG(2,arg2)
       
       READ (arg1,*) N
       READ (arg2,*) IO
       
       WRITE(*,*) N
       WRITE(*,*) IO

       ALLOCATE (A(N,N),X(N,N),STAT=IPTR)
       IF (IPTR/=0) THEN
          WRITE (NOUT,FMT=*) 'Allocate FAILED, IPTR = ', IPTR
          STOP
       END IF
       LDA = N
       LDX = N

       DO J = 1, N
          DO I = 1, N
             A(I,J) = 0.0D0
          END DO
          A(J,J) = 2.0D0
       END DO
       DO J = 2, N
          A(J-1,J) = -1.1D0
          A(J,J-1) = -1.0D0
       END DO

       IFAIL = 0
       CALL G02AAF(A,LDA,N,1.0D-7,-10,-10,X,LDX,ITER,FEVAL,NRMGRD,IFAIL)

       IF ((IFAIL==0) .AND. (IO)) THEN
          WRITE (NOUT,99999) ((X(I,J),J=1,N),I=1,N)
       END IF
       WRITE (NOUT,*)

99999  FORMAT (2X,4F11.5)
    END PROGRAM
