! See copyright notice in the COPYRIGHT file.
program bin_search_test
  use env_module, only: long_k, rk
  use tem_timer_module, only: tem_addTimer, tem_startTimer, tem_stopTimer,     &
    &                         tem_labeledtimer_type, tem_getTimerVal
  use tem_dyn_array_module, only: dyn_longArray_type, init, append,            &
    &                             PositionOfVal
  use tem_general_module,    only: tem_general_type, tem_start, tem_finalize

  implicit none

  integer, parameter :: nVals = 1000000

  integer :: long_timing
  integer :: iVal
  integer :: pos(nVals)
  type(dyn_longArray_type) :: longArray
  type(tem_labeledtimer_type) :: timer
  type(tem_general_type) :: general
  real(kind=rk) :: timerVal

  write(*,*) 'Running binary search test...'
  write(*,*) 'on ', nVals, ' Values'

  ! Init the Treelm environment
  call tem_start('TREELM unit test', 'utest', general)

  call tem_addTimer( me          = timer,        &
    &                timerHandle = long_timing,  &
    &                timerName   = 'long_timing' )

  call init(me = longArray, length = nVals)

  call tem_startTimer( timer%timedat, long_timing )
  do iVal=1,nVals
    call append(me = longArray, val = int(iVal, kind=long_k), pos = pos(iVal))
  end do
  call tem_stopTimer( timer%timedat, long_timing )
  timerVal = tem_getTimerVal(timer%timedat, long_timing)
  write(*,'(a,f15.4,a)') ' Run-time long_timing:', timerVal, ' s'

  call tem_finalize(general)

  ! access an element from the pos array, to stop compiler from optimizing the
  ! loop away:
  write(*,*) 'last Value has position:', pos(nVals)

  write(*,*) 'PASSED'

end program bin_search_test
