C$Procedure ZZINPDT0 ( DSK, in planetodetic element, w/o margin? )

      SUBROUTINE ZZINPDT0 ( P, LON, BOUNDS, CORPAR, EXCLUD, INSIDE )

C$ Abstract
C
C     SPICE Private routine intended solely for the support of SPICE
C     routines. Users should not call this routine directly due to the
C     volatile nature of this routine.
C
C     Test a point represented by a set of planetodetic coordinates for
C     inclusion in a specified planetodetic volume element. Ellipsoidal
C     surfaces are used in place of surfaces of constant altitude. The
C     test is performed without using the "greedy" margins for the
C     element. The built-in angular rounding tolerance is still used
C     for the longitude comparison.
C
C$ Disclaimer
C
C     THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C     CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C     GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C     ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C     PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C     TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C     WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C     PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C     SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C     SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C     IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C     BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C     LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C     INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C     REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C     REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C     RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C     THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C     CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C     ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C     DSK
C
C$ Keywords
C
C     DSK
C     GEOMETRY
C     INTERSECTION
C     SURFACE
C     TOPOGRAPHY
C
C$ Declarations

      IMPLICIT NONE

      INCLUDE 'dsktol.inc'

      DOUBLE PRECISION      P      ( 3 )
      DOUBLE PRECISION      LON
      DOUBLE PRECISION      BOUNDS ( 2, 3 )
      DOUBLE PRECISION      CORPAR ( * )
      INTEGER               EXCLUD
      LOGICAL               INSIDE

      INTEGER               NONE
      PARAMETER           ( NONE   = 0 )

      INTEGER               LONIDX
      PARAMETER           ( LONIDX = 1 )

      INTEGER               LATIDX
      PARAMETER           ( LATIDX = 2 )

      INTEGER               ALTIDX
      PARAMETER           ( ALTIDX = 3 )

C$ Brief_I/O
C
C     VARIABLE  I/O  DESCRIPTION
C     --------  ---  --------------------------------------------------
C     P          I   Cartesian coordinates of point.
C     LON        I   Planetocentric longitude of point.
C     BOUNDS     I   Coordinate bounds of element.
C     CORPAR     I   Coordinate parameters.
C     EXCLUD     I   Index of coordinate to exclude from test.
C     INSIDE     O   Flag indicating whether point is in element.
C     ANGMRG     P   Angular rounding margin.
C     LONALI     P   Longitude alias margin.
C     NONE       P   Meaning: exclude nothing.
C     LONIDX     P   Longitude index. Also used for exclusion.
C     LATIDX     P   Latitude index. Also used for exclusion.
C     ALTIDX     P   Altitude index. Also used for exclusion.
C
C$ Detailed_Input
C
C     P          is a point expressed in Cartesian coordinates. The
C                reference frame is that of the segment of interest.
C                The point is to be checked to determine whether it is
C                inside the volume element specified by BOUNDS.
C
C
C     LON        is the planetocentric longitude of the point P.
C
C
C     BOUNDS     is an 2x3 array containing the bounds of a volume
C                element expressed in planetodetic coordinates. BOUNDS
C                defines the volume element used in the comparison. In
C                the element
C
C                   BOUNDS(I,J)
C
C                J is the coordinate index. J is one of
C
C                   { LONIDX, LATIDX, ALTIDX }
C
C                I is the bound index.
C
C                   I = 1   ->   lower bound
C                   I = 2   ->   upper bound
C
C                If necessary, the longitude bounds are normalized
C                for the comparison. The normalized bounds differ
C                by no more than 2*pi and are in increasing order.
C                See ZZNRMLON for details.
C
C                The aliasing margin LONALI and the angular rounding
C                margin ANGMRG are used for longitude comparisons.
C                However, the greedy margin is not used. See the
C                Parameters section below for further information.
C
C
C     CORPAR     is an array of coordinate parameters; normally these
C                are obtained from a DSK descriptor. The first element
C                is the equatorial radius of the reference spheroid.
C                The second element is the flattening coefficient.
C                Any other elements are ignored by this routine.
C
C
C     EXCLUD     is either a coordinate index or the parameter NONE.
C
C                If EXCLUD is set to one of
C
C                   { LONIDX, LATIDX, ALTIDX }
C
C                then the indicated coordinate is excluded from
C                comparison with the corresponding volume element
C                boundaries.
C
C                If EXCLUD is set to NONE, all coordinates are
C                compared.
C
C                Exclusion of coordinates is used in cases where a
C                point is known to be on a level surface of a given
C                coordinate. For example, if a point is on the surface
C                of altitude equal to the upper altitude bound,
C                altitude need not be used in the comparison and in
C                fact can't be meaningfully compared, due to round-off
C                errors.
C
C$ Detailed_Output
C
C     INSIDE     is a logical flag that is set to .TRUE. if and
C                only if the input coordinates represent a
C                point inside or on the surface of the volume
C                element, according to the comparisons that are
C                performed.
C
C                The value of INSIDE is not affected by the value
C                of any excluded coordinate.
C
C$ Parameters
C
C     LONALI     is a longitude shift margin. If the input longitude
C                coordinate LON is less than the longitude lower bound
C                by more than this amount, the value LON + 2*pi is used
C                in the longitude comparison. If the input longitude
C                exceeds the upper longitude bound by this amount, the
C                value LON - 2*pi is used in the comparison.
C
C     ANGMRG     is an angular rounding margin. If the input longitude
C                is outside of the longitude bounds by less than this
C                amount, the longitude is considered to be within the
C                bounds. The margin is used analogously for latitude.
C
C                This margin is distinct from the "greedy" segment
C                selection margin, which is used to expand a volume
C                element for the purpose of determining whether a given
C                point lies in that element.
C
C                See dsktol.inc for details.
C
C     NONE       when used as a value of the input argument EXCLUD,
C                indicates that no coordinates should be excluded from
C                comparison.
C
C     LONIDX     is the index of longitude in the second dimension of
C                BOUNDS. When used as a value of the input argument
C                EXCLUD, indicates that longitude should be excluded
C                from comparison.
C
C     LATIDX     is the index of latitude in the second dimension of
C                BOUNDS. When used as a value of the input argument
C                EXCLUD, indicates that latitude should be excluded
C                from comparison.
C
C
C     ALTIDX     is the index of altitude in the second dimension of
C                BOUNDS. When used as a value of the input argument
C                EXCLUD, indicates that altitude should be excluded
C                from comparison.
C
C$ Exceptions
C
C     Error free.
C
C$ Files
C
C     None.
C
C$ Particulars
C
C     This routine uses ellipsoidal bounding surfaces, in place of
C     surfaces of constant altitude, to represent the "outer" and
C     "inner" segment boundaries. These surfaces must be consistent
C     with those used by the ray-planetodetic volume element intercept
C     routine ZZRYTPDT.
C
C     The radii of these ellipsoidal surfaces are those produced by
C     the routine ZZELLBDS.
C
C     Note that a margin is used for longitude shifting, although
C     none is used to expand the volume element.
C
C$ Examples
C
C     See usage in ZZINPDT.
C
C$ Restrictions
C
C     1)  Validity of the ellipsoid shape parameters must be ensured by
C         the caller.
C
C     2)  This is a private routine. It is meant to be used only by the
C         DSK subsystem.
C
C$ Literature_References
C
C     None.
C
C$ Author_and_Institution
C
C     N.J. Bachman    (JPL)
C
C$ Version
C
C-    SPICELIB Version 1.0.0, 16-AUG-2016 (NJB)
C
C        Now uses ANGMRG for latitude comparisons.
C
C        25-MAY-2016 (NJB)
C
C           Original version.
C
C-&

C$ Index_Entries
C
C     test point against planetodetic element without margin
C
C-&

C
C     SPICELIB functions
C
      DOUBLE PRECISION      HALFPI
      DOUBLE PRECISION      TWOPI

      LOGICAL               FAILED
      LOGICAL               RETURN

C
C     Local parameters
C
      INTEGER               LOWER
      PARAMETER           ( LOWER = 1 )

      INTEGER               UPPER
      PARAMETER           ( UPPER = 2 )

C
C     Numeric relation codes returned by ZZPDCMPL:
C
      INTEGER               LT
      PARAMETER           ( LT = -1 )

      INTEGER               EQ
      PARAMETER           ( EQ =  0 )

      INTEGER               GT
      PARAMETER           ( GT =  1 )

C
C     Local variables
C
      DOUBLE PRECISION      EMAX
      DOUBLE PRECISION      EMIN
      DOUBLE PRECISION      F
      DOUBLE PRECISION      LEVEL
      DOUBLE PRECISION      LOCLON
      DOUBLE PRECISION      MAXLAT
      DOUBLE PRECISION      MAXLON
      DOUBLE PRECISION      MAXALT
      DOUBLE PRECISION      MINLAT
      DOUBLE PRECISION      MINLON
      DOUBLE PRECISION      MINALT
      DOUBLE PRECISION      PI2
      DOUBLE PRECISION      PMAX
      DOUBLE PRECISION      PMIN
      DOUBLE PRECISION      RE
      DOUBLE PRECISION      RP

      INTEGER               MAXREL
      INTEGER               MINREL

      LOGICAL               FIRST

C
C     Saved variables
C
      SAVE                  FIRST
      SAVE                  PI2

C
C     Initial values
C
      DATA                  FIRST / .TRUE. /
      DATA                  PI2   / -1.D0  /

      IF ( RETURN() ) THEN
         RETURN
      END IF

      CALL CHKIN ( 'ZZINPDT0' )

      IF ( FIRST ) THEN

         PI2   = TWOPI()
         FIRST = .FALSE.

      END IF

C
C     Unpack the shape parameters. Set the polar axis length for
C     later use.
C
      RE = CORPAR(1)
      F  = CORPAR(2)
      RP = RE * ( 1.D0 - F )

C
C     Assume the point is outside to start. This allows us
C     to skip setting INSIDE when we find a boundary test
C     failure.
C
      INSIDE = .FALSE.
C
C     Compare coordinates of the input point and the segment
C     bounds. Deal with altitude last, since it involves the
C     most work. We may be able to exit before performing the
C     altitude tests.
C
      IF ( EXCLUD .NE. LATIDX ) THEN
C
C        Compare the point's latitude to the segment's latitude bounds.
C
         MINLAT = MAX( BOUNDS(LOWER, LATIDX) - ANGMRG, -HALFPI() )
         MAXLAT = MIN( BOUNDS(UPPER, LATIDX) + ANGMRG,  HALFPI() )

         CALL ZZPDCMPL ( RE, F, P, MINLAT, MINREL )
         CALL ZZPDCMPL ( RE, F, P, MAXLAT, MAXREL )

         IF ( FAILED() ) THEN
            CALL CHKOUT ( 'ZZINPDT0' )
            RETURN
         END IF

         IF (      ( MINREL .EQ. LT )
     .        .OR. ( MAXREL .EQ. GT )  ) THEN
C
C           The point's latitude is outside of the segment's range.
C
            CALL CHKOUT ( 'ZZINPDT0' )
            RETURN

         END IF

      END IF

C
C     Move the longitude of the input point into the interval
C
C        [ MINLON, MAXLON ]
C
C     if necessary and if possible.
C
      IF ( EXCLUD .NE. LONIDX ) THEN
C
C        Put the local longitude bounds in order, if necessary.
C
         CALL ZZNRMLON ( BOUNDS(LOWER,LONIDX),  BOUNDS(UPPER,LONIDX),
     .                   ANGMRG,       MINLON,  MAXLON               )
C
C        Compare the point's longitude to the segment's longitude
C        bounds.
C
         LOCLON = LON

         IF ( LON .LT. ( MINLON - LONALI ) ) THEN
C
C           If the point's longitude is less than the segment's
C           longitude by more than a small margin, shift the longitude
C           right by 2*pi.

            LOCLON = LON + PI2

         ELSE IF ( LON .GT. ( MAXLON + LONALI ) ) THEN
C
C           If the point's longitude is greater than the segment's
C           longitude by more than a small margin, shift the longitude
C           left by 2*pi.

            LOCLON = LON - PI2

         END IF

         IF (        ( LOCLON .LT. (MINLON-ANGMRG) )
     .          .OR. ( LOCLON .GT. (MAXLON+ANGMRG) )  ) THEN
C
C           The point's longitude, adjusted if necessary for
C           comparison, is outside of the segment's range.
C
            CALL CHKOUT ( 'ZZINPDT0' )
            RETURN

         END IF

      END IF

      IF ( EXCLUD .NE. ALTIDX ) THEN
C
C        Extract altitude bounds from the segment descriptor.
C
         MINALT = BOUNDS(LOWER, ALTIDX)
         MAXALT = BOUNDS(UPPER, ALTIDX)
C
C        Find the semi-axes of the bounding spheroids.
C
         IF ( F .GE. 0.D0 ) THEN
C
C           This is the oblate case. Get the semi-axis lengths
C           for the inner and outer bounding spheroids.
C
            CALL ZZELLBDS ( RE,   RP,   MAXALT, MINALT,
     .                      EMAX, PMAX, EMIN,   PMIN   )

         ELSE
C
C           This is the prolate case. RP is the longer axis. Get the
C           semi-axis lengths for the inner and outer bounding
C           spheroids.
C
C           In this call, we'll store the radii associated with
C           the longer axis in PMAX and PMIN.
C
            CALL ZZELLBDS ( RP,   RE,   MAXALT, MINALT,
     .                      PMAX, EMAX, PMIN,   EMIN   )

         END IF

C
C        Compute the input point's level surface parameters
C        for the inner and outer bounding ellipsoids. Do these
C        computations one at a time, so the second one can be
C        skipped if the first one shows the point is outside
C        the outer ellipsoid.
C
         LEVEL = ( P(1)/EMAX )**2 + ( P(2)/EMAX )**2 + ( P(3)/PMAX )**2

         IF ( LEVEL .GT. 1.D0 ) THEN
C
C           The point is outside of the outer bounding ellipsoid.
C
            CALL CHKOUT ( 'ZZINPDT0' )
            RETURN

         END IF

         LEVEL = ( P(1)/EMIN )**2 + ( P(2)/EMIN )**2 + ( P(3)/PMIN )**2

         IF ( LEVEL .LT. 1.D0 ) THEN
C
C           The point is inside the inner bounding ellipsoid, which
C           implies it is outside of the segment's boundaries.
C
            CALL CHKOUT ( 'ZZINPDT0' )
            RETURN

         END IF

      END IF

C
C     Getting to this point means the input point is inside
C     the segment. Being on the boundary counts as inside.
C
      INSIDE = .TRUE.

      CALL CHKOUT ( 'ZZINPDT0' )
      RETURN
      END


! HJ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
! HJ X
! HJ X   libAtoms+QUIP: atomistic simulation library
! HJ X
! HJ X   Portions of this code were written by
! HJ X     Albert Bartok-Partay, Silvia Cereda, Gabor Csanyi, James Kermode,
! HJ X     Ivan Solt, Wojciech Szlachta, Csilla Varnai, Steven Winfield.
! HJ X
! HJ X   Copyright 2006-2010.
! HJ X
! HJ X   These portions of the source code are released under the GNU General
! HJ X   Public License, version 2, http://www.gnu.org/copyleft/gpl.html
! HJ X
! HJ X   If you would like to license the source code under different terms,
! HJ X   please contact Gabor Csanyi, gabor@csanyi.net
! HJ X
! HJ X   Portions of this code were written by Noam Bernstein as part of
! HJ X   his employment for the U.S. Government, and are not subject
! HJ X   to copyright in the USA.
! HJ X
! HJ X
! HJ X   When using this software, please cite the following reference:
! HJ X
! HJ X   http://www.libatoms.org
! HJ X
! HJ X  Additional contributions by
! HJ X    Alessio Comisso, Chiara Gattinoni, and Gianpietro Moras
! HJ X
! HJ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

program lotf_metapot

  use libAtoms_module
  use QUIP_Module

  implicit None

  type(Atoms) :: dia, at
  type(InOutput) :: xml
  type(Potential) :: pot1, pot2
  real(dp), allocatable :: f(:,:), f_hyb(:,:)
  integer, pointer :: hybrid(:)
  integer :: i, j, n_cycle, n_extrap
  type(Table) :: embedlist
  type(MetaPotential) :: lotf, forcemix
  type(DynamicalSystem) :: ds, ds_saved

  call system_initialise(PRINT_NORMAL,seed=2)
  call initialise(xml, 'lotf_params.xml')
  call initialise(pot1, 'IP SW label="PRB_31_plus_H"', xml)
  call rewind(xml)
  call initialise(pot2, 'IP SW label="eps_2.3"', xml)

  call diamond(dia, 5.44_dp, (/14/))
  call supercell(at, dia, 2, 2, 2)
  call randomise(at%pos, 0.1_dp)

  n_cycle = 1
  n_extrap = 10

  allocate(f(3,at%N),f_hyb(3,at%N))

  call set_cutoff(at, cutoff(pot1)+2.0_dp)
  call calc_connect(at)

  ! Mark QM region
  call add_property(at, 'hybrid', 0)
  if (.not. assign_pointer(at, 'hybrid', hybrid)) &
       call system_abort('Cannot assign hybrid pointer')

  call append(embedlist, (/1,0,0,0/))
  call bfs_grow(at, embedlist, 2, nneighb_only=.true.)

  hybrid(int_part(embedlist,1)) = 1

  call print('embed list')
  call print(embedlist)

  ! Set up metapotentials for LOTF and for force mixing with the same buffer size
  call initialise(lotf, 'ForceMixing method=lotf_adj_pot_svd fit_hops=3 buffer_hops=3 '//&
       'randomise_buffer=T qm_args_str={single_cluster=T cluster_calc_connect=T}', pot1, pot2, dia)
  call initialise(forcemix, 'ForceMixing method=force_mixing buffer_hops=3 '//&
       'qm_args_str={single_cluster=T cluster_calc_connect=T}', pot1, pot2)

  call initialise(ds, at)

  call print_title('LOTF Metapotential')
  call print(lotf)

  call print_title('Force Mixing Metapotential')
  call print(forcemix)

  ! Predictor-corrector dynamics
  call Print_Title('Bootstrap')
  call calc(lotf, ds%atoms, f=f) ! bootstrap the adjustable potential
  do i=1,n_cycle

     ! Update QM region
     call print_title('Quantum Selection')
     ! ...

     ! Extrapolation
     call print_title('Extrapolation')
     call ds_save_state(ds_saved, ds)

     do j=1,n_extrap
        if (j == 1) then
           call calc(lotf, ds%atoms, f=f, args_str="lotf_do_qm=F lotf_do_init=T lotf_do_map=T")
        else
           call calc(lotf, ds%atoms, f=f, args_str="lotf_do_qm=F lotf_do_init=F")
        end if
        call calc(forcemix, ds%atoms, f=f_hyb)
        call advance_verlet(ds, 1.0_dp, f)
        call ds_print_status(ds, 'E', instantaneous=.true.)
        call print('E err '//ds%t//' '//rms_diff(f_hyb, f)//' '//maxval(abs(f_hyb-f)))
     end do

     call print_title('QM Force Evaluation')
     ! QM force calculation and optimisation of adj pot
     call calc(lotf, ds%atoms, f=f, args_str="lotf_do_qm=T lotf_do_init=F lotf_do_fit=T")

     ! Interpolation
     call print_title('Interpolation')
     call ds_restore_state(ds, ds_saved)
     do j=1,n_extrap
        call calc(lotf, ds%atoms, f=f, args_str="lotf_do_qm=F lotf_do_init=F lotf_do_interp=T lotf_interp="&
             //(real(j-1,dp)/real(n_extrap,dp)))
        call calc(forcemix, ds%atoms, f=f_hyb)
        call advance_verlet(ds, 1.0_dp, f)
        call ds_print_status(ds, 'I', instantaneous=.true.)
        call print('I err '//ds%t//' '//rms_diff(f_hyb, f)//' '//maxval(abs(f_hyb-f)))
     end do

     call print_title('Connectivity update')
     call calc_connect(ds%atoms)

  end do

  deallocate(f, f_hyb)
  call finalise(xml)
  call finalise(pot1)
  call finalise(pot2)
  call finalise(at)
  call finalise(ds)
  call finalise(dia)
  call system_finalise

end program lotf_metapot


!======================================================================!
  subroutine UserCutLines_BUOY(grid, y)
!----------------------------------------------------------------------!
! This program reads name.1D file created by NEU or GEN and averages
! the results in the homogeneous directions.
! The results are writen in files name_buoy_res.dat and name_buoy_res_plus.dat
!----------------------------------------------------------------------!
    use all_mod
    use allp_mod
    use les_mod
    use pro_mod
    use par_mod
    use rans_mod
!----------------------------------------------------------------------!
    implicit none
!-----------------------------[Arguments]------------------------------!
    real :: y(-NbC:NC)
    real :: Ufric, Wall_near
!------------------------------[Calling]-------------------------------!
    interface
      logical function Approx(A,B,tol)
        real           :: A,B
        real, optional :: tol
      end function Approx
    end interface
!-------------------------------[Locals]-------------------------------!
    integer             :: Nprob, pl, c, i, count, s, c1, c2
    character           :: namCoo*80, namPro*80, answer*80, namRes*80
    character           :: namRes_plus*80
    real,allocatable    :: z_p(:), Ump(:), Vmp(:), Wmp(:), &
                                 uup(:), vvp(:), wwp(:), &
                                 uvp(:), uwp(:), vwp(:), &
                                 uupR(:), vvpR(:), wwpR(:), &
                                 uvpR(:), uwpR(:), vwpR(:), &
                                 Tmp(:), TTmp(:),         &
                                 uTp(:), vTp(:), wTp(:), &
                                 uTpR(:), vTpR(:), wTpR(:), &
                                 Ksgsp(:), ind(:),       &
                                 VIStp(:), var_2(:), var_3(:), &
                                 Wall_p(:), Ufric_p(:), Kinp(:), Epsp(:), &
                                 v2p(:), fp(:)
    integer,allocatable :: Np(:), Ncount(:)
    real                :: R, Urad_mean, Utan_mean, dummy, Lscale, Twall
!======================================================================!

    namPro = name

    namRes = name
    namRes(len_trim(name)+1:len_trim(name)+13) = '_buoy_res.dat'
    namRes_plus = name
    namRes_plus(len_trim(name)+1:len_trim(name)+18) = '_buoy_res_plus.dat'
!>>>>>>>>>>>>>>>>>>>>>>!
!     read 1D file     !
!>>>>>>>>>>>>>>>>>>>>>>!
    namCoo = name
    namCoo(len_trim(name)+1:len_trim(name)+3) = '.1D'
    if(this < 2)  write(6, *) '# Now reading the file:', namCoo
    open(9, file=namCoo)

!---- write the number of searching intervals
    read(9,*) Nprob
    allocate(z_p(Nprob*2))
    allocate(ind(Nprob*2))

!---- read the intervals positions
    do pl=1,Nprob
      read(9,*) ind(pl), z_p(pl)
    end do
    close(9)

    call GraPhi(U % n, 1, Ux,.TRUE.)    ! dU/dx
    call GraPhi(U % n, 2, Uy,.TRUE.)    ! dU/dy
    call GraPhi(U % n, 3, Uz,.TRUE.)    ! dU/dz
    call GraPhi(V % n, 1, Vx,.TRUE.)    ! dV/dx
    call GraPhi(V % n, 2, Vy,.TRUE.)    ! dV/dy
    call GraPhi(V % n, 3, Vz,.TRUE.)    ! dV/dz
    call GraPhi(W % n, 1, Wx,.TRUE.)    ! dW/dx
    call GraPhi(W % n, 2, Wy,.TRUE.)    ! dW/dy
    call GraPhi(W % n, 3, Wz,.TRUE.)    ! dW/dz

    call GraPhi(T % n,1,PHIx,.TRUE.)
    call GraPhi(T % n,2,PHIy,.TRUE.)
    call GraPhi(T % n,3,PHIz,.TRUE.)

    call SSORT (z_p, ind, Nprob, 0)
    write(*,*) Nprob

    call CalcShear(U % n, V % n, W % n, Shear)

    if(SIMULA==EBM.and.MODE/=HYB) then
      do c=1,NC
        VAR1x(c) = 0.22*Tsc(c) *&
                   (uu%n(c)*PHIx(c)+uv%n(c)*PHIy(c)+uw%n(c)*PHIz(c))

        VAR1y(c) = 0.22*Tsc(c)*&
                   (uv%n(c)*PHIx(c)+vv%n(c)*PHIy(c)+vw%n(c)*PHIz(c))

        VAR1z(c) = 0.22*Tsc(c)*&
                   (uw%n(c)*PHIx(c)+vw%n(c)*PHIy(c)+ww%n(c)*PHIz(c))
      end do

      call GraPhi(VAR1x,1,VAR2x,.TRUE.)
      call GraPhi(VAR1y,2,VAR2y,.TRUE.)
      call GraPhi(VAR1z,3,VAR2z,.TRUE.)
    end if

    allocate(Np(Nprob));      Np=0
    allocate(Wall_p(Nprob));  Wall_p=0.0
    allocate(Ump(Nprob));     Ump=0.0
    allocate(Vmp(Nprob));     Vmp=0.0
    allocate(Wmp(Nprob));     Wmp=0.0
    allocate(uup(Nprob));     uup=0.0
    allocate(vvp(Nprob));     vvp=0.0
    allocate(wwp(Nprob));     wwp=0.0
    allocate(uvp(Nprob));     uvp=0.0
    allocate(uwp(Nprob));     uwp=0.0
    allocate(vwp(Nprob));     vwp=0.0
    allocate(uupR(Nprob)); uup=0.0
    allocate(vvpR(Nprob)); vvp=0.0
    allocate(wwpR(Nprob)); wwp=0.0
    allocate(uvpR(Nprob)); uvp=0.0
    allocate(uwpR(Nprob)); uwp=0.0
    allocate(vwpR(Nprob)); vwp=0.0
    allocate(Kinp(Nprob));    Kinp=0.0
    allocate(Epsp(Nprob));    Epsp=0.0
    allocate(v2p(Nprob));     v2p=0.0
    allocate(fp(Nprob));      fp=0.0
    allocate(Ksgsp(Nprob));   Ksgsp=0.0
    allocate(VIStp(Nprob));   VIStp=0.0
    allocate(Ufric_p(Nprob)); Ufric_p = 0.0
    allocate(Ncount(Nprob));  Ncount=0
    allocate(Tmp(Nprob));     Tmp=0.0
    allocate(TTmp(Nprob));     TTmp=0.0
    allocate(uTp(Nprob));     uTp=0.0
    allocate(vTp(Nprob));     vTp=0.0
    allocate(wTp(Nprob));     wTp=0.0
    allocate(uTpR(Nprob)); uTpR=0.0
    allocate(vTpR(Nprob)); vTpR=0.0
    allocate(wTpR(Nprob)); wTpR=0.0

    count = 0
    Lscale = 0.0
!+++++++++++++++++++++++++++++!
!     average the results     !
!+++++++++++++++++++++++++++++!
    do i = 1, Nprob-1
      do c=1, NC
        Lscale = max(Lscale,WallDs(c))
        if(y(c) > (z_p(i+1)) .and. y(c) < (z_p(i))) then
          Wall_p(i) = Wall_p(i) + WallDs(c)
          Ump(i)   = Ump(i) + U % n(c)
          Vmp(i)   = Vmp(i) + V % n(c)
          Wmp(i)   = Wmp(i) + W % n(c)
          Kinp(i)  = Kinp(i) + Kin % n(c)
          Epsp(i)  = Epsp(i) + Eps % n(c)
          v2p(i)   = v2p(i)  + v_2 %n(c) !- CONc(material(c))*PHIz(c)  !v_2 % n(c)
          fp(i)    = fp(i)  + f22%n(c)   !tt % n(c) ! - VISt(c)*PHIz(c)
!          v2p(i)   = v2p(i) + v_2 % n(c)
!          fp(i)    = fp(i) + VISt(c)/VISc !f22 % n(c)
          uup(i)   = uup(i) + 2.0*VISt(c)*Ux(c)
          vvp(i)   = vvp(i) + 2.0*VISt(c)*Vy(c)
          wwp(i)   = wwp(i) + 2.0*VISt(c)*Wz(c)
          uvp(i)   = uvp(i) + VISt(c)*(Uy(c) + Vx(c))
          uwp(i)   = uwp(i) + VISt(c)*(Uz(c) + Wx(c))
          vwp(i)   = vwp(i) + VISt(c)*(Vz(c) + Wy(c))
          uupR(i)  = uupR(i) + uu_res(c)
          vvpR(i)  = vvpR(i) + vv_res(c)
          wwpR(i)  = wwpR(i) + ww_res(c)
          uvpR(i)  = uvpR(i) + uv_res(c)
          uwpR(i)  = uwpR(i) + uw_res(c)
          vwpR(i)  = vwpR(i) + vw_res(c)
          VIStp(i) = VIStp(i) + VISt(c)/VISc
          if(IsNearWall(c)) then
            if(Ynd(c)>5.0) then
              Ufric_p(i) = Ufric_p(i) + sqrt(TauWall(c))
            else
              Ufric_p(i) = Ufric_p(i) + (VISc * (U % n(c)**2 + V % n(c)**2 + &
              W% n(c)**2)**0.5/WallDs(c))**0.5
            end if
          end if
          Tmp(i)   = Tmp(i) + T % n(c)
          TTmp(i)   = TTmp(i) + TT % n(c)
          uTp(i)   = uTp(i) + uT % n(c)
          vTp(i)   = vTp(i) + vT % n(c)
          wTp(i)   = wTp(i) + wT % n(c)
          uTpR(i)   = uTpR(i) + uT_res(c)
          vTpR(i)   = vTpR(i) + vT_res(c)
          wTpR(i)   = wTpR(i) + wT_res(c)
          Ncount(i) = Ncount(i) + 1
        end if
      end do
    end do
    do s=1,NS
      c1=SideC(1,s)
      c2=SideC(2,s)
      if(c2  < 0) then
        if( TypeBC(c2) ==  WALL.or. TypeBC(c2) ==  WALLFL) then
          Twall = T % n(c2)
        end if
      end if
    end do

!---- average over all processors
    do pl=1, Nprob-1
      call IGlSum(Ncount(pl))

      call GloSum(Wall_p(pl))

      call GloSum(Ump(pl))
      call GloSum(Vmp(pl))
      call GloSum(Wmp(pl))

      call GloSum(Kinp(pl))
      call GloSum(Epsp(pl))
      call GloSum(fp(pl))
      call GloSum(v2p(pl))

      call GloSum(uup(pl))
      call GloSum(vvp(pl))
      call GloSum(wwp(pl))
      call GloSum(uvp(pl))
      call GloSum(uwp(pl))
      call GloSum(vwp(pl))

      call GloSum(uupR(pl))
      call GloSum(vvpR(pl))
      call GloSum(wwpR(pl))
      call GloSum(uvpR(pl))
      call GloSum(uwpR(pl))
      call GloSum(vwpR(pl))

      call GloSum(VIStp(pl))
      call GloSum(Ufric_p(pl))

      call GloSum(Tmp(pl))
      call GloSum(TTmp(pl))
      call GloSum(uTp(pl))
      call GloSum(vTp(pl))
      call GloSum(wTp(pl))
      call GloSum(uTpR(pl))
      call GloSum(vTpR(pl))
      call GloSum(wTpR(pl))

      count =  count + Ncount(pl)
    end do

    call wait

    do i = 1, Nprob-1
      if(Ncount(i) /= 0) then
        Wall_p(i) =  Wall_p(i)/Ncount(i)
        Ump(i)    =  Ump(i)/Ncount(i)
        Vmp(i)    =  Vmp(i)/Ncount(i)
        Wmp(i)    =  Wmp(i)/Ncount(i)
        uup(i)    =  uup(i)/Ncount(i)
        vvp(i)    =  vvp(i)/Ncount(i)
        wwp(i)    =  wwp(i)/Ncount(i)
        uvp(i)    =  uvp(i)/Ncount(i)
        uwp(i)    =  uwp(i)/Ncount(i)
        vwp(i)    =  vwp(i)/Ncount(i)
        uupR(i)   =  uupR(i)/Ncount(i)
        vvpR(i)   =  vvpR(i)/Ncount(i)
        wwpR(i)   =  wwpR(i)/Ncount(i)
        uvpR(i)   =  uvpR(i)/Ncount(i)
        uwpR(i)   =  uwpR(i)/Ncount(i)
        vwpR(i)   =  vwpR(i)/Ncount(i)
        Kinp(i)   =  Kinp(i)/Ncount(i)
        Epsp(i)   =  Epsp(i)/Ncount(i)
        v2p(i)    =  v2p(i)/Ncount(i)
        fp(i)     =  fp(i)/Ncount(i)
        VIStp(i)  =  VIStp(i)/Ncount(i)
        Ufric_p(i)=  Ufric_p(i)/Ncount(i)
        Tmp(i)    =  Tmp(i)/Ncount(i)
        TTmp(i)   =  TTmp(i)/Ncount(i)
        uTp(i)    =  uTp(i)/Ncount(i)
        vTp(i)    =  vTp(i)/Ncount(i)
        wTp(i)    =  wTp(i)/Ncount(i)
        uTpR(i)   =  uTpR(i)/Ncount(i)
        vTpR(i)   =  vTpR(i)/Ncount(i)
        wTpR(i)   =  wTpR(i)/Ncount(i)
      end if
    end do

    Ufric = 0.0
    do i = 1, Nprob
      Ufric = max(Ufric_p(i),Ufric)
    end do
10  continue

    if(Ufric == 0.0) then
      if(this < 2) write(*,*) 'Friction velocity is zero in UserCutLines_BUOY.f90 !'
      return
    end if

    open(3,file=namRes)
    write(3,'(A1,2(A10, F13.5))') '#', 'Utau = ', Ufric, 'Re_tau = ', Ufric/VISc
    write(3,'(A1,1X,A140)') '#', 'Xrad U V W T (-5) TT uu vv ww uv (-10) &
                             uw vw uuR vvR wwR (-15) uvR uwR vwR Kin Eps (-20) &
                             v2 f22 VISratio uT vT (-25) wT uTR vTR wTR (-29)'
    do i = Nprob, 1, -1
      if(Ncount(i) /= 0) then
        write(3,'(29E16.7)') Wall_p(i), Ump(i), Vmp(i), Wmp(i), Tmp(i), TTmp(i), &
        uup(i), vvp(i), wwp(i), uvp(i), uwp(i), vwp(i), uupR(i), vvpR(i), wwpR(i), &
        uvpR(i), uwpR(i), vwpR(i), Kinp(i), Epsp(i), v2p(i), fp(i), VIStp(i), uTp(i), &
        vTp(i), wTp(i), uTpR(i), vTpR(i), wTpR(i)
      end if
    end do
    close(3)

    open(3,file=namRes_plus)
    write(3,'(A1,2(A10, F13.5))') '#', 'Utau = ', Ufric, 'Re_tau = ', Ufric/VISc
    write(3,'(A1,2(A10, F14.8))') '#', 'Tflux = ', Tflux, ' K+ =', Tflux/Ufric * (VISc/CONc(material(1)))**ONE_THIRD
    write(3,'(A1,1X,A130)') '#', 'Xrad U V W T (-5) uu vv ww uv uw (-10) &
                             vw Kin Eps v2 f22 (-15) VISratio uT vT wT uTR (-20) &
                             vTR wTR Tnorm sqr(TT)norm (-25)'
    do i = Nprob, 1, -1
      if(Ncount(i) /= 0) then
        write(3,'(25E16.7)') Wall_p(i)*Ufric/VISc, Ump(i)/Ufric, Vmp(i)/Ufric, Wmp(i)/Ufric, (Twall - Tmp(i))*Ufric/Tflux, &
        uup(i)/Ufric**2, vvp(i)/Ufric**2, wwp(i)/Ufric**2, uvp(i)/Ufric**2, uwp(i)/Ufric**2, vwp(i)/Ufric**2, &
        uupR(i)/Ufric**2, vvpR(i)/Ufric**2, wwpR(i)/Ufric**2, uvpR(i)/Ufric**2, uwpR(i)/Ufric**2, vwpR(i)/Ufric**2, &
        Kinp(i)/Ufric**2, Epsp(i)*VISc/Ufric**4.0, v2p(i), Ufric*fp(i)/Tflux, VIStp(i), &
        uTp(i)/Tflux, vTp(i)/Tflux, wTp(i)/Tflux, uTpR(i)/Tflux, vTpR(i)/Tflux, wTpR(i)/Tflux, &
        (Tmp(i)-95.0)/10.0, sqrt(TTmp(i))/5.0
      end if
    end do

    close(3)

    deallocate(Ufric_p);
    deallocate(Ncount);
    deallocate(Wall_p);
    deallocate(ind)
    deallocate(Np)
    deallocate(z_p)
    deallocate(Ump)
    deallocate(Vmp)
    deallocate(Wmp)
    deallocate(uup)
    deallocate(vvp)
    deallocate(wwp)
    deallocate(uvp)
    deallocate(uwp)
    deallocate(vwp)
    deallocate(uupR)
    deallocate(vvpR)
    deallocate(wwpR)
    deallocate(uvpR)
    deallocate(uwpR)
    deallocate(vwpR)
    deallocate(Kinp)
    deallocate(Epsp)
    deallocate(v2p)
    deallocate(fp)
    deallocate(VIStp)
    deallocate(Ksgsp)
    deallocate(Tmp)
    deallocate(TTmp)
    deallocate(uTp)
    deallocate(vTp)
    deallocate(wTp)
    deallocate(uTpR)
    deallocate(vTpR)
    deallocate(wTpR)

  end subroutine UserCutLines_BUOY


C$Procedure ZZINLAT0 ( DSK, in latitudinal element, w/o margin? )

      SUBROUTINE ZZINLAT0 ( R, LON, LAT, BOUNDS, EXCLUD, INSIDE )

C$ Abstract
C
C     SPICE Private routine intended solely for the support of SPICE
C     routines. Users should not call this routine directly due to the
C     volatile nature of this routine.
C
C     Test a point represented by a set of latitudinal coordinates for
C     inclusion in a specified latitudinal volume element. The test is
C     performed without using the "greedy" margins for the element.
C     The built-in angular rounding tolerance is still used for the
C     longitude comparison.
C
C$ Disclaimer
C
C     THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C     CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C     GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C     ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C     PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C     TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C     WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C     PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C     SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C     SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C     IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C     BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C     LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C     INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C     REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C     REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C     RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C     THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C     CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C     ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C     DSK
C
C$ Keywords
C
C     DSK
C     GEOMETRY
C     INTERSECTION
C     SURFACE
C     TOPOGRAPHY
C
C$ Declarations

      IMPLICIT NONE

      INCLUDE 'dsktol.inc'

      DOUBLE PRECISION      R
      DOUBLE PRECISION      LON
      DOUBLE PRECISION      LAT
      DOUBLE PRECISION      BOUNDS ( 2, 3 )
      INTEGER               EXCLUD
      LOGICAL               INSIDE

      INTEGER               NONE
      PARAMETER           ( NONE   = 0 )

      INTEGER               LONIDX
      PARAMETER           ( LONIDX = 1 )

      INTEGER               LATIDX
      PARAMETER           ( LATIDX = 2 )

      INTEGER               RADIDX
      PARAMETER           ( RADIDX = 3 )

C$ Brief_I/O
C
C     VARIABLE  I/O  DESCRIPTION
C     --------  ---  --------------------------------------------------
C     R          I   Radius of point.
C     LON        I   Planetocentric longitude of point.
C     LAT        I   Planetocentric latitude of point.
C     BOUNDS     I   Coordinate bounds of element.
C     EXCLUD     I   Index of coordinate to exclude from test.
C     INSIDE     O   Flag indicating whether point is in element.
C     ANGMRG     P   Angular rounding margin.
C     LONALI     P   Longitude shift margin.
C     NONE       P   Meaning: exclude nothing.
C     LONIDX     P   Longitude index. Also used for exclusion.
C     LATIDX     P   Latitude index. Also used for exclusion.
C     RADIDX     P   Radius index. Also used for exclusion.
C
C$ Detailed_Input
C
C     R,
C     LON,
C     LAT        are, respectively, the radius, longitude, and
C                latitude of a point. The point is to be checked
C                to determine whether it is inside the volume
C                element specified by BOUNDS.
C
C     BOUNDS     is an 2x3 array containing the bounds of a volume
C                element expressed in latitudinal coordinates. BOUNDS
C                defines the volume element used in the comparison. In
C                the element
C
C                   BOUNDS(I,J)
C
C                J is the coordinate index. J is one of
C
C                   { LONIDX, LATIDX, RADIDX }
C
C                I is the bound index.
C
C                   I = 1   ->   lower bound
C                   I = 2   ->   upper bound
C
C                If necessary, the longitude bounds are normalized
C                for the comparison. The normalized bounds differ
C                by no more than 2*pi and are in increasing order.
C                See ZZNRMLON for details.
C
C                The aliasing margin LONALI and the angular rounding
C                margin ANGMRG are used for longitude comparisons.
C                However, the greedy margin is not used. See the
C                Parameters section below for further information.
C
C
C     EXCLUD     is either a coordinate index or the parameter NONE.
C
C                If EXCLUD is set to one of
C
C                   { LONIDX, LATIDX, RADIDX }
C
C                then the indicated coordinate is excluded from
C                comparison with the corresponding volume element
C                boundaries.
C
C                If EXCLUD is set to NONE, all coordinates are
C                compared.
C
C                Exclusion of coordinates is used in cases where a
C                point is known to be on a level surface of a given
C                coordinate. For example, if a point is on the sphere
C                of radius equal to the upper radius bound, radius need
C                not be used in the comparison and in fact can't be
C                meaningfully compared, due to round-off errors.
C
C$ Detailed_Output
C
C     INSIDE     is a logical flag that is set to .TRUE. if and only if
C                the input coordinates represent a point inside or on
C                the surface of the volume element, according to the
C                comparisons that are performed.
C
C                The value of INSIDE is not affected by the value
C                of any excluded coordinate.
C
C$ Parameters
C
C     LONALI     is a longitude shift margin. If the input longitude
C                coordinate LON is less than the longitude lower bound
C                by more than this amount, the value LON + 2*pi is used
C                in the longitude comparison. If the input longitude
C                exceeds the upper longitude bound by this amount, the
C                value LON - 2*pi is used in the comparison.
C
C                See dsktol.inc for details.
C
C     ANGMRG     is an angular rounding margin. If the input longitude
C                is outside of the longitude bounds by less than this
C                amount, the longitude is considered to be within the
C                bounds.
C
C                This margin is distinct from the "greedy" segment
C                selection margin, which is used to expand a volume
C                element for the purpose of determining whether a given
C                point lies in that element.
C
C                See dsktol.inc for details.
C
C     NONE       when used as a value of the input argument EXCLUD,
C                indicates that no coordinates should be excluded from
C                comparison.
C
C     LONIDX     is the index of longitude in the second dimension of
C                BOUNDS. When used as a value of the input argument
C                EXCLUD, indicates that longitude should be excluded
C                from comparison.
C
C     LATIDX     is the index of latitude in the second dimension of
C                BOUNDS. When used as a value of the input argument
C                EXCLUD, indicates that latitude should be excluded
C                from comparison.
C
C
C     RADIDX     is the index of radius in the second dimension of
C                BOUNDS. When used as a value of the input argument
C                EXCLUD, indicates that radius should be excluded
C                from comparison.
C
C$ Exceptions
C
C     Error free.
C
C$ Files
C
C     None.
C
C$ Particulars
C
C     Note that a margin is used for longitude shifting, although
C     none is used to expand the volume element.
C
C$ Examples
C
C     See usage in ZZINLAT.
C
C$ Restrictions
C
C     This is a private routine. It is meant to be used only by the DSK
C     subsystem.
C
C$ Literature_References
C
C     None.
C
C$ Author_and_Institution
C
C     N.J. Bachman    (JPL)
C
C$ Version
C
C-    SPICELIB Version 1.0.0, 07-AUG-2016 (NJB)
C
C-&

C$ Index_Entries
C
C     test point against latitudinal element without margin
C
C-&

C
C     SPICELIB functions
C
      DOUBLE PRECISION      TWOPI

C
C     Local parameters
C
      INTEGER               LOWER
      PARAMETER           ( LOWER = 1 )

      INTEGER               UPPER
      PARAMETER           ( UPPER = 2 )

C
C     Local variables
C
      DOUBLE PRECISION      LOCLON
      DOUBLE PRECISION      MAXLAT
      DOUBLE PRECISION      MAXLON
      DOUBLE PRECISION      MAXR
      DOUBLE PRECISION      MINLAT
      DOUBLE PRECISION      MINLON
      DOUBLE PRECISION      MINR
      DOUBLE PRECISION      PI2

      LOGICAL               FIRST

C
C     Saved variables
C
      SAVE                  FIRST
      SAVE                  PI2

C
C     Initial values
C
      DATA                  FIRST / .TRUE. /
      DATA                  PI2   / -1.D0  /

      IF ( FIRST ) THEN

         PI2   = TWOPI()
         FIRST = .FALSE.

      END IF

C
C     Assume the point is outside to start. This allows us
C     to skip setting INSIDE when we find a boundary test
C     failure.
C
      INSIDE = .FALSE.
C
C     Compare coordinates of the input point and the segment
C     bounds.
C
C     Special case: if the input point is at the origin, and the
C     volume element contains the origin, the point is inside.
C
      IF ( R .EQ. 0.D0 ) THEN

         IF ( BOUNDS(LOWER, RADIDX) .EQ. 0.D0 ) THEN

            INSIDE = .TRUE.

            RETURN

         END IF

      END IF

      IF ( EXCLUD .NE. RADIDX ) THEN
C
C        Compare the point's radius to the segment's radius bounds.
C
         MINR = BOUNDS(LOWER, RADIDX)
         MAXR = BOUNDS(UPPER, RADIDX)

         IF ( ( R .LT. MINR ) .OR. ( R .GT. MAXR ) ) THEN
C
C           The point's radius is outside of the segment's range.
C
            RETURN

         END IF

      END IF

      IF ( EXCLUD .NE. LATIDX ) THEN
C
C        Compare the point's latitude to the segment's latitude bounds.
C
         MINLAT = BOUNDS(LOWER, LATIDX)
         MAXLAT = BOUNDS(UPPER, LATIDX)

         IF ( ( LAT .LT. MINLAT ) .OR. ( LAT .GT. MAXLAT ) ) THEN
C
C           The point's latitude is outside of the segment's range.
C
            RETURN

         END IF

      END IF

C
C     Move the longitude of the input point into the interval
C
C        [ MINLON, MAXLON ]
C
C     if necessary and if possible.
C
      IF ( EXCLUD .NE. LONIDX ) THEN
C
C        Put the local longitude bounds in order, if necessary.
C
         CALL ZZNRMLON ( BOUNDS(1,LONIDX),  BOUNDS(2,LONIDX),
     .                   ANGMRG,   MINLON,  MAXLON           )
C
C        Compare the point's longitude to the segment's longitude
C        bounds.
C
         LOCLON = LON

         IF ( LON .LT. ( MINLON - LONALI ) ) THEN
C
C           If the point's longitude is less than the segment's
C           longitude by more than a small margin, shift the longitude
C           right by 2*pi.

            LOCLON = LON + PI2

         ELSE IF ( LON .GT. ( MAXLON + LONALI ) ) THEN
C
C           If the point's longitude is greater than the segment's
C           longitude by more than a small margin, shift the longitude
C           left by 2*pi.

            LOCLON = LON - PI2

         END IF

         IF (        ( LOCLON .LT. (MINLON-ANGMRG) )
     .          .OR. ( LOCLON .GT. (MAXLON+ANGMRG) )  ) THEN
C
C           The point's longitude, adjusted if necessary for
C           comparison, is outside of the segment's range.
C
            RETURN

         END IF

      END IF
C
C     Getting to this point means the input point is inside
C     the segment. Being on the boundary counts as inside.
C
      INSIDE = .TRUE.

      RETURN
      END