program andmixma

  use bmandmix, only: andmix
  use bmproblem, only: pdata_type,iniprob,endprob
  use iso_c_binding, only: c_ptr,c_loc

  implicit none

  ! LOCAL SCALARS
  integer :: allocstat,fcnt,istop,iter,maxit,n,nhlim
  real(kind=8) :: epsf,finish,start
  type(pdata_type), target :: pdata

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

  call iniprob(n,c_loc(pdata))

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

  x(1:n) = pdata%x0(1:n)

  epsf = 1.0d-06 * sqrt( real( n ) )
  maxit = huge( 1 ) ! A CPU time limit is imposed

  write(*,*) 'Enter nhlim: '
  read(*,*) nhlim
  
  call cpu_time(start)

  call andmix(n,x,r,epsf,maxit,nhlim,iter,fcnt,istop,c_loc(pdata))
  
  call cpu_time(finish)

  write(*,*) 'Satisfied stopping criterion = ',istop
  write(*,*) 'Residual Euclidian norm = ',norm2( r(1:n) )
  write(*,*) 'Number of iterations = ',iter
  write(*,*) 'Number of functional evaluations = ',fcnt
  write(*,*) 'CPU time in seconds = ',finish - start
  
  open(10,file='tabline.txt')
  write(10,9000) pdata%nprob,n,istop,norm2(r(1:n)),iter,fcnt,finish-start
  close(10)
    
  deallocate(x,r,stat=allocstat)
  if ( allocstat .ne. 0 ) then
     write(*,*) 'Error in deallocate.'
     stop
  end if

  call endprob(c_loc(pdata))

  stop
  
9000 format(1X,I2,1X,I7,1X,I1,1X,1P,D7.1,2(1X,I10),0P,F12.6)

end program andmixma

