! See copyright notice in the COPYRIGHT file.
! This unit test check
program mus_biquadratic_test
  use env_module,                       only: rk, eps
  use tem_general_module, only: tem_start, tem_finalize, tem_general_type
  use mus_interpolate_quadratic_module, only: biquadratic_interpolate

  implicit none

  logical :: error
  real(kind=rk) :: tolerance

  type( tem_general_type ) :: general
  integer :: iVal, jVal
  real(kind=rk) :: f(9), x, y

  call tem_start( 'Biquadratic interpolation test', 'utest', general )
  error = .false.
  tolerance = eps * 2500._rk
  write(*,"(A,F20.14)") 'tolerance = ', tolerance

  do iVal = 1, 9
    f( iVal ) = 0.1_rk * iVal
  end do

  x = 0.0_rk
  y = 0.0_rk
  do jVal = 1, 3
    do iVal = 1, 3
      x = (iVal - 1) * 0.5_rk
      y = (jVal - 1) * 0.5_rk
      error = test_interpolation( f, x, y, f( (jVal-1)*3+iVal ) )
      if ( error ) exit
    end do
    if ( error ) exit
  end do

  call tem_finalize(general)
  if (error) then
    write(*,"(A)") 'FAILED'
  else
    write(*,'(A)') 'PASSED'
  end if

contains

  function test_interpolation( f, x, y, expect ) result ( error )
    real(kind=rk), intent(in) :: f(9), x, y, expect
    real(kind=rk)             :: res
    logical                   :: error

    res = biquadratic_interpolate( f, x, y )
    if ( abs(res-expect) > tolerance ) then
      write(*,*) " Discrepency exceeds tolerance!"
      write(*,*) "   x = ", x
      write(*,*) "   y = ", y
      write(*,*) "   res = ", res
      write(*,*) "   exp = ", expect
      write(*,*) "   Discrepency = ", abs(res-expect)
      write(*,*) "   tolerance   = ", tolerance
      error = .true.
    else
      error = .false.
    end if

  end function test_interpolation


end program mus_biquadratic_test
