# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
module lagrange
  implicit none
  contains
  logical function find_nearest(x_pt,x_in,z_in,x_out,z_out)
    real :: x_pt,x_in(:),z_in(:),x_out(:),z_out(:)
    real :: dist(size(x_in))
    real :: max_dist
    integer :: i1,iloc(1)
    dist=abs(x_in-x_pt)
    max_dist=maxval(dist)
    do i1=1,size(x_out)
      iloc=minloc(dist)
      x_out(i1)=x_in(iloc(1))
      z_out(i1)=z_in(iloc(1))
      dist(iloc(1))=max_dist*2.
    end do
    find_nearest=.true.
  end function
  logical function find_lagrange_coefs(x_out,x_in,wts)
    real :: x_out
    real :: x_in(:)
    real :: wts(:)
    integer n1,i,j
    if (size(x_in)/=size(wts)) then
      write(0,*) "input coef size and wt size not same"
      find_lagrange_coefs=.false.
      return
    end if
    find_lagrange_coefs=.true.
    n1=size(wts)
    do i=1,n1
      wts(i)=1
      do j=1,n1
        if (i/=j) then
          wts(i)=wts(i)*(x_out-x_in(j))/(x_in(i)-x_in(j))
        end if
      end do
    end do
  end function
end module
