program optvorma

  use iso_c_binding, only: c_ptr,c_loc,c_f_pointer
  use optvor, only: pdata_type,evalfg,proj,approxg,drawsol,InA,compscale,compvols
  
  implicit none
	
  ! LOCAL SCALARS
  integer :: allocerr,fcnt,i,inform,iprint,iter,itrial,maxfc,maxit,maxnv,n, &
       nsites,ntrials,spginfo
  real(kind=8) :: area,epsopt,f,fbest,finish,ftarget,gpsupn,marg,scale,seed,start
  type(pdata_type), target :: pdata

  ! LOCAL ARRAYS
  real(kind=8) :: p(2)
  real(kind=8), allocatable :: g(:),x(:),x0(:),vol(:)
  character(len=80) :: filename

  ! FUNCTIONS
  real(kind=8) :: drand
  
  ! Problem data
  
  ! Set sites

  write(*,*) 'Enter nsites>0: '
  read(*,*) nsites

  ! Set disjoint convex polygons Aj whose union define A 
  
  pdata%npols = 1

  allocate(pdata%nvpols(pdata%npols),stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Allocation error.'
     stop
  end if
    
  pdata%nvpols(1) = 7

  maxnv = maxval( pdata%nvpols(1:pdata%npols) )
  
  allocate(pdata%poledges(pdata%npols,maxnv),pdata%xpol(pdata%npols,maxnv), &
       pdata%ypol(pdata%npols,maxnv),stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Allocation error.'
     stop
  end if
  
  pdata%xpol(1,1:pdata%nvpols(1)) = (/ 0.65d0, -1.98d0, -3.35d0, -2.59d0, -0.22d0, 0.54d0, 0.65d0 /)
  pdata%ypol(1,1:pdata%nvpols(1)) = (/ 2.31d0,  2.71d0,  1.64d0, -0.34d0, -1.07d0, 0.72d0, 2.31d0 /)
    
  pdata%poledges(1,1:pdata%nvpols(1)-1) = (/ 0, 0, 0, 0, 0, 0 /)

  ! Scale A so cells have ideal area near unity
  
  call compscale(nsites,scale,area,c_loc(pdata))

  pdata%volA = area 
  pdata%xpol(1,1:pdata%nvpols(1)) = scale * pdata%xpol(1,1:pdata%nvpols(1))
  pdata%ypol(1,1:pdata%nvpols(1)) = scale * pdata%ypol(1,1:pdata%nvpols(1))
  
  pdata%xmin = minval( pdata%xpol(1,1:pdata%nvpols(1)) )
  pdata%xmax = maxval( pdata%xpol(1,1:pdata%nvpols(1)) )
  pdata%ymin = minval( pdata%ypol(1,1:pdata%nvpols(1)) )
  pdata%ymax = maxval( pdata%ypol(1,1:pdata%nvpols(1)) )
  
  marg = 0.1d0 * max( 1.0d0, abs( pdata%xmin ), abs( pdata%xmax ), abs( pdata%ymin), abs( pdata%ymax ) )

  pdata%xmin = pdata%xmin - marg
  pdata%xmax = pdata%xmax + marg
  pdata%ymin = pdata%ymin - marg
  pdata%ymax = pdata%ymax + marg
  
  pdata%c(1:2) = 0.5d0 * (/ pdata%xmax + pdata%xmin, pdata%ymax + pdata%ymin /)
  pdata%rmax = norm2(pdata%c - (/ pdata%xmin, pdata%ymin /))
  pdata%drawscale = 1.3d0 / scale

  if ( nsites .ge. 10000 ) then
     pdata%drawscale = 3.0d0 / scale
  end if

  ! Optimize
  
  write(*,*) 'Enter ntrials>0: '
  read(*,*) ntrials

  n = 2 * nsites
  
  allocate(x(n),x0(n),g(n),vol(nsites),stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Allocation error.'
     stop
  end if
        
  fbest = huge( 1.0d0 )
  
  do itrial = 1,ntrials
     seed = 123456.0d0 * itrial

     write(*,*) 'Processing trial itrial = ',itrial
     
     do i = 1,nsites
        p(1) = pdata%xmin + ( pdata%xmax - pdata%xmin ) * drand(seed)
        p(2) = pdata%ymin + ( pdata%ymax - pdata%ymin ) * drand(seed)

        do while ( .not. InA(p,c_loc(pdata)) )
           p(1) = pdata%xmin + ( pdata%xmax - pdata%xmin ) * drand(seed)
           p(2) = pdata%ymin + ( pdata%ymax - pdata%ymin ) * drand(seed)
        end do
       
        x(2*i-1) = p(1)
        x(2*i)   = p(2)
     end do

     x0(1:n) = x(1:n)
     
     epsopt  = 1.0d-08
     ftarget = 1.0d-08
     maxit = 10000
     maxfc = 10000
     iprint = 0
  
     call cpu_time(start)
  
     call spg(n,x,epsopt,ftarget,maxit,maxfc,iprint,f,gpsupn,iter,fcnt,spginfo,inform, &
          evalfg,proj,c_loc(pdata))
  
     call cpu_time(finish)

     write(*,*) 'Statistics: f = ',f,' gpsupn = ',gpsupn,' it = ',iter,' fcnt = ',fcnt, &
          ' spginfo = ',spginfo,' time = ',finish-start
     
     if ( f .lt. fbest ) then
        fbest = f

        write(*,*) 'Solution was improved. New best f = ',fbest

        write(filename,"(A13,I0,A3)") 'fig-test-ini-',nsites,'.mp'
        call drawsol(n,x0,filename,c_loc(pdata))
  
        write(filename,"(A13,I0,A3)") 'fig-test-end-',nsites,'.mp'
        call drawsol(n,x,filename,c_loc(pdata))

        call compvols(n,x,vol,c_loc(pdata))
        
        open(unit=10,file='tabline.txt')   
        write(10,1000) scale,pdata%volA,pdata%npols,nsites,itrial,f,gpsupn,iter,fcnt,spginfo,finish-start, &
             pdata%volA / nsites, &
             count( vol(1:nsites) .lt. sqrt( epsilon( 1.0d0 ) ) ), &
             maxval( abs( vol(1:nsites) * nsites / pdata%volA - 1.0d0 ), vol(1:nsites) .ge. sqrt( epsilon( 1.0d0 ) ) )
        close(10)
        
        if ( fbest .le. ftarget ) then
           write(*,*) 'A global minimizer has been found!'
           exit
        end if
     end if
  end do
  
  deallocate(x,x0,g,vol,stat=allocerr)
  if ( allocerr .ne. 0 ) then
     write(*,*) 'Deallocation error.'
     stop
  end if
  
  stop

1000 format(1P,E12.5,1X,1P,E12.5,1X,I3,1X,I6,1X,I6,1X,1P,E12.5,1X,1P,E7.1,2(1X,I6),1X,I2,0P,F14.6,1X,1P,E12.5,1X,I6,1X,1P,E12.5)
  
end program optvorma
