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

program kssma

  implicit none

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

  ! LOCAL ARRAYS
  real(kind=8), allocatable :: g(:),x(:)
  real(kind=4) :: tdum(2)

  ! DATA STATEMENTS
  data tdum/0.0,0.0/

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

  call getn(n)

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

  call setx0(n,x)
  
  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(*,*) '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,g,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

