    PROGRAM e01safe

!      E01SAF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. 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 Functions ..
       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
