    Program e01safe

!     E01SAF Example Program Text

!     Mark 24 Release. NAG Copyright 2012.

!     .. Use Statements ..
      Use nag_library, Only: e01saf, e01sbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hx, hy, xhi, xlo, yhi, ylo
      Integer                          :: i, ifail, j, m, nx, ny
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), grads(:,:), pf(:), px(:),      &
                                          py(:), x(:), y(:)
      Integer, Allocatable             :: triang(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E01SAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Allocate (x(m),y(m),f(m),grads(2,m),triang(7*m))

      Do i = 1, m
        Read (nin,*) x(i), y(i), f(i)
      End Do

!     Generate the triangulation and gradients.

      ifail = 0
      Call e01saf(m,x,y,f,triang,grads,ifail)

!     Evaluate the interpolant on a rectangular grid at NX*NY
!     points over the domain (XLO to XHI) x (YLO to YHI).

      Read (nin,*) nx, xlo, xhi
      Read (nin,*) ny, ylo, yhi
      Allocate (px(nx),py(ny),pf(nx))

      hx = (xhi-xlo)/real(nx-1,kind=nag_wp)
      px(1) = xlo

      Do i = 2, nx
        px(i) = px(i-1) + hx
      End Do

      hy = (yhi-ylo)/real(ny-1,kind=nag_wp)
      py(1) = ylo

      Do i = 2, ny
        py(i) = py(i-1) + hy
      End Do

      Write (nout,*)
      Write (nout,99999) '          X', (px(i),i=1,nx)
      Write (nout,*) '     Y'

      Do i = ny, 1, -1

        Do j = 1, nx

          ifail = 0
          Call e01sbf(m,x,y,f,triang,grads,px(j),py(i),pf(j),ifail)

        End Do

        Write (nout,99998) py(i), (pf(j),j=1,nx)
      End Do

99999 Format (1X,A,7F8.2)
99998 Format (1X,F8.2,3X,7F8.2)
    End Program e01safe
