program funsaintve32ma

  use bmsesem, only: sesem
  use bmproblem, only: pdata_type,iniprob,endprob,inip
  use iso_c_binding, only: c_ptr,c_loc

  implicit none

  ! LOCAL SCALARS
  integer :: accacc,allocstat,bobfai,fcnt,fcntbest,ndiis,istop,iter,iterbest,m,maxit,maxnprogr,n,nhlim,nred,redscheme
  real(kind=8) :: bdsvio,eps,ftarget,fbest,finish,rsqnrm,rsqnrmrel,seed,start
  type(pdata_type), target :: pdata

  ! LOCAL ARRAYS
  real(kind=8), allocatable :: l(:),u(:),r(:),x(:)

  write(*,*) 'Enter eps: '
  read(*,*) eps

  write(*,*) 'Enter ndiis, nhlim, nred, redscheme, and seed: '
  read(*,*) ndiis,nhlim,nred,redscheme,seed

  call iniprob(n,m,c_loc(pdata))

  allocate(l(n),u(n),x(n),r(m),stat=allocstat)
  if ( allocstat .ne. 0 ) then
     write(*,*) 'Error in allocate.'
     stop
  end if

  call inip(n,x,l,u,c_loc(pdata))

  nred = min( nred, n )

  ftarget = eps * sum( pdata%yobs(1:pdata%nobs) ** 2, .not. pdata%lostobs(1:pdata%nobs)  )
  write(*,*) 'ftarget = ',ftarget
  
  maxit = huge( 1 )
  maxnprogr = 100

  call cpu_time(start)

  call sesem(n,x,l,u,m,r,ftarget,maxit,maxnprogr,nred,redscheme,seed, &
       ndiis,nhlim,iter,fcnt,fbest,iterbest,fcntbest,accacc,bobfai, &
       istop,c_loc(pdata))
  
  call cpu_time(finish)

  write(*,*) 'Satisfied stopping criterion = ',istop

  rsqnrm = sum( r(1:m) ** 2 )
  rsqnrmrel = rsqnrm / sum( pdata%yobs(1:pdata%nobs) ** 2, .not. pdata%lostobs(1:pdata%nobs) )
  bdsvio = max( 0.0d0, maxval( l(1:n) - x(1:n) ), maxval( x(1:n) - u(1:n) ) )
  
  write(*,*) 'Residual squared Euclidian norm = ',rsqnrm
  write(*,*) 'Box-violation sup-norm = ',bdsvio
  write(*,*) 'Number of iterations = ',iter
  write(*,*) 'Number of functional evaluations = ',fcnt
  write(*,*) 'CPU time in seconds = ',finish - start
        
  deallocate(l,u,x,r,stat=allocstat)
  if ( allocstat .ne. 0 ) then
     write(*,*) 'Error in deallocate.'
     stop
  end if

  call endprob(c_loc(pdata))
  
  open(10,file='tabline.txt')
  write(10,9000) n,m,istop,rsqnrm,bdsvio,rsqnrmrel,iter,fcnt,real(accacc)/iter, &
       real(bobfai)/iter,fbest,iterbest,fcntbest,finish-start
  close(10)

  stop

9000 format(1X,I7,1X,I8,1X,I1,3(1X,1P,D12.6),2(1X,I10),2(1X,0P,F5.2), &
            1X,1P,D12.6,2(1X,I10),0P,F12.6)

contains

end program funsaintve32ma
