! Code to perform trivial benchmark
! of a collection of sort algorithms
!
! MJR Oct 2019

program b
  use sorts

  write(*,*)'Smooth sort'
  call bench(smoothsort,1000000)
  write(*,*)
    
  contains

subroutine bench(sort,big)
  use sorts
  procedure(smoothsort) :: sort
  real(prec), allocatable :: array(:),old(:)
  integer, intent(in) :: big
  integer i,off,t1,t2,rate
  real(prec):: check
  
  allocate(array(big),old(big))
  i=10
  ! find rate
  call system_clock(t1,rate)
  write(*,*)'      Size      time/element'
  do while(i<=big)
     call random_number(array)
     old=array
     check=sum(array(1:i))
     off=1
     call system_clock(t1)
     do while(off+i-1<=big)
     call sort(array(off:off+i-1))
        off=off+i
     enddo
     call system_clock(t2)
! Check result is ordered
     do j=2,i
        if (array(j)<array(j-1)) then
           write(*,*)'Sort error at ',j,' value ',array(j)
           if (i.le.100) then
              write(*,*)array(1:i)
              write(*,*)'Original array'
              write(*,10)(k,old(k),k=1,i)
              10 format ('a(',i2,')=',f10.7)
           else
              write(*,*)array(j-3:j+3)
           endif
           stop
        endif
     enddo
! Check sum of result is approximately the same as it was
     check=check-sum(array(1:i))
     if (check.gt.1e-15*i*sqrt(real(i))) then
        write(*,*)'Large difference in sums before and after',check
        if (i.le.20) then
           write(*,*)'Before'
           write(*,*)old(1:i)
           write(*,*)'After'
           write(*,*)array(1:i)
           stop
        endif
     endif
     
     write(*,*)i,real(t2-t1)/(real(rate)*i*(big/i))
     i=10*i
  enddo
  deallocate(array)
end subroutine bench

end program b
