! *****************************************************************
! *****************************************************************

program kssma

  implicit none

  ! LOCAL SCALARS
  integer :: allocerr,n,fcnt,gcnt,hcnt,inform,iter,lsyscnt,status
  real(kind=8) :: epsa,epsr,f,fmin,gsupn
  real(kind=4) :: time

  ! LOCAL ARRAYS
  character(len=10) :: pname
  character(len=10), allocatable :: xnames(:)
  real(kind=8), allocatable :: g(:),l(:),u(:),x(:)
  real(kind=4) :: tdum(2)

  ! COMMON BLOCK
  integer :: hnnzmax
  integer, pointer :: hcol(:),hrow(:)
  real(kind=8), pointer :: hval(:)
  common /sparsehess/ hcol,hrow,hval,hnnzmax

  ! DATA STATEMENTS
  data tdum/0.0,0.0/

  ! EXTERNAL FUNCTIONS
  real(kind=4) :: dtime

  open(10,file='OUTSDIF.d',form='formatted',status='old')

  rewind 10

  call cutest_udimen(status,10,n)
  if ( status .ne. 0 ) then
     write(*,*) 'cutest_udimen: status not equal to zero. status = ',status
     stop
  end if

  allocate(x(n),l(n),u(n),g(n),xnames(n),stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Allocation error.'
     stop
  end if

  call cutest_usetup(status,10,6,4,n,x,l,u)
  if ( status .ne. 0 ) then
     write(*,*) 'cutest_usetup: status not equal to zero. status = ',status
     stop
  end if

  if ( count( l(1:n) .gt. -1.0d+20 ) + count( u(1:n) .lt. 1.0d+20 ) .gt. 0 ) then
     write(*,*) 'The problem has bounds.'
     stop
  end if
  
  call cutest_unames(status,n,pname,xnames)

  call cutest_udimsh(status,hnnzmax)
  if ( status .ne. 0 ) then
     write(*,*) 'cutest_udimsh: status not equal to zero. status = ',status
     stop
  end if

  allocate(hrow(hnnzmax),hcol(hnnzmax),hval(hnnzmax),stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Allocation error.'
     stop
  end if

  fmin = - 1.0d+08
  epsa =   1.0d-06
  epsr =   1.0d-15
  
  time = dtime(tdum)

  call algorithm1(n,x,f,g,gsupn,fmin,epsa,epsr,iter,fcnt,gcnt,hcnt,lsyscnt,inform)

  time = dtime(tdum)
  time = tdum(1)

  write(*,*) 'Solution (first 5 components): ',x(1:min(5,n))

  write(*,*) 'Problem name                    = ',pname
  write(*,*) 'inform                          = ',inform
  write(*,*) 'Number of iterations            = ',iter
  write(*,*) 'Number of function evaluations  = ',fcnt
  write(*,*) 'Number of gradient evaluations  = ',gcnt
  write(*,*) 'Number of Hessian  evaluations  = ',hcnt
  write(*,*) 'Number of linear systems solved = ',lsyscnt
  write(*,*) 'CPU time in seconds             = ',time

  open(20,file='kss-tabline.txt')
  write(20,9000) n,inform,f,gsupn,iter,fcnt,gcnt,hcnt,lsyscnt,time
  close(20)

  deallocate(x,l,u,g,xnames,hrow,hcol,hval,stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Deallocation error.'
     stop
  end if

  stop

9000 format(1X,I6,1X,I2,1X,1P,D14.6,1X,1P,D7.1,5(1X,I6),0P,F8.2)

end program kssma

