C***************************************************************           
C              Subroutine LEBEM3 by Stephen Kirkup             *        
C***************************************************************
C 
C  Version 2 (July 2015) (previous version 2001) 
C  New GLS routine implemented and simplified integral equation
C   formulation
C  Stephen Kirkup, School of Engineering 
C  University of Central Lancashire - www.uclan.ac.uk 
C  smkirkup@uclan.ac.uk
C  http://www.researchgate.net/profile/Stephen_Kirkup
C
C  This open source code can be found at
C   www.boundary-element-method.com/fortran/LEBEM3.FOR 
C
C  Issued under the GNU General Public License 2007, see gpl.txt
C
C  Part of the the author's open source BEM packages. 
C  All codes and manuals can be downloaded from 
C  www.boundary-element-method.com
C
C***************************************************************
C This subroutine computes the solution to the three-dimensional 
C Laplace equation
C                  __ 2                
C                  \/    {\phi}   =  0   
C
C in the domain exterior to a closed boundary.
C
C The boundary (S) is defined (approximated) by a set of planar 
C triangular panels. The domain of the equation is within the
C boundary.
C
C The boundary condition may be Dirichlet, Robin or Neumann. It is 
C assumed to have the following general form
C
C           {\alpha}(q) {\phi}(q) + {\beta}(q) v(q) = f(q)
C    
C where {\phi}(q) is the solution at the point q on S, v(q) is the 
C derivative of {\phi} with respect to the outward normal to S at q and
C {\alpha}, {\beta} and f are real-valued functions defined on S. The
C functions {\alpha} and {\beta} must be specified to define the nature
C of the boundary condition. Important examples are {\alpha}=1, 
C {\beta}=0 which is equivalent to a Dirichlet boundary condition and 
C {\alpha}=0, {\beta}=1 which is equivalent to a Neumann boundary 
C condition. The specification of f completes the definition of the 
C boundary condition.
C
C
C How to use the subroutine
C -------------------------
C
C The following diagram shows how the subroutine is to be used. 
C
C                                   ....................................
C                                   :                                  :
C                                   :                                  :
C      ----------------------       :     --------------------------   :
C      |                    |       :     |                        |   :
C      |   MAIN PROGRAM     |------->-----|      LEBEM3            |   :
C      | (e.g.LEBEM3_t.for) |       :     |                        |   :
C      |                    |       :     --------------------------   :
C      ----------------------       :                 |                :
C                                   :                 >                :
C                                   :                 |                :
C                                   :      ------------------------    :
C          Package ---------------->:      | subordinate routines |    :
C                                   :      ------------------------    :
C                                   :                                  :
C                                   :      (this file)                 :  
C                                   :..................................:
C                                  /         |                 |
C                               |_           >                 >
C                              /             |                 |
C             ................       ................   ................  
C             :              :       :   --------   :   :  --------    : 
C             : (geom3d.for) :---<---:   | L3LC |   :   :  | GLS |    : 
C             :              :       :   --------   :   :  --------    :  
C             :..............:       : -------------:   : -------------:  
C                                    : |subordinate|:   : |subordinate|: 
C                                    : | routines  |:   : | routines  |:  
C                                    : -------------:   : -------------: 
C                                    :              :   :              : 
C                                    : (l3lc.for)   :   : (gls.for)   :
C                                    :..............:   :..............:
C                                    
C
C The contents of the main program must be linked to LEBEM3.FOR, L3LC.FOR
C and GLS.FOR.
C
C Method of solution
C ------------------
C 
C In the main program, the boundary must be described as a set of
C  panels. The panels are defined by three indices (integers) which
C  label a node or vertex on the boundary. The data structure VERTEX 
C  lists and enumerates the coordinates of the vertices, the data 
C  structure SELV defines each panel by indicating the labels for
C  the three nodes that are its vertices and hence enumerates the
C  panels.
C The boundary solution points (the points on the boundary at which 
C  {\phi} (SPHI) and d {\phi}/dn (SVEL) are returned) are at the centres
C  of the panels. The boundary functions {\alpha} (SALPHA), {\beta} 
C  (SBETA) and f (SF) are also defined by their values at the centres
C  of the panels.
C Normally a solution in the domain is required. By listing the 
C  coordinates of all the exterior points in PENT, the subroutine
C  returns the value of {\phi} at these points in PEPHI.
C
C
C Format and parameters of the subroutine
C ---------------------------------------
C
C The subroutine has the form
C
C      SUBROUTINE LEBEM3(MAXNV,NV,VERTEX,MAXNSE,NSE,SELV,
C     *                 MAXNPE,NPE,PENT,
C     *                 SALPHA,SBETA,SF,SIPHI,PDEPHI,
C     *                 LSOL,LVALID,EGEOM,
C     *                 SPHI,SVEL,PEPHI,
C     *                 L_SS,M_SSMINUS,L_DS,M_DS,
C     *                 PERM,XORY,C,WKSPC1,WKSPC2,WKSPC3)

C The parameters to the subroutine
C ================================

C Geometry of the boundary S (input)
C integer MAXNV: The limit on the number of vertices of the polygon
C  that defines (approximates) S. MAXNV>=4.
C integer NV: The number of vertices on S. 4<=NV<=MAXNV.
C real VERTEX(MAXNV,3): The coordinates of the vertices. VERTEX(i,1),
C  VERTEX(i,2), VERTEX(i,3) are the x,y,z coordinates of the i-th 
C  vertex.
C integer MAXNSE: The limit on the number of panels describing S.
C  MAXNSE>=4.
C integer NSE: The number of panels describing S. 4<=NSE<=MAXNSE.
C integer SELV(MAXNSE,3): The indices of the three vertices defining
C  each panel. The i-th panel have vertices 
C  (VERTEX(SELV(i,1),1),VERTEX(SELV(i,1),2)),VERTEX(SELV(i,1),3)),
C  (VERTEX(SELV(i,2),1),VERTEX(SELV(i,2),2)),VERTEX(SELV(i,2),3)) and
C  (VERTEX(SELV(i,3),1),VERTEX(SELV(i,3),2)),VERTEX(SELV(i,3),3)).

C Interior points at which the solution is to be observed (input)
C integer MAXNPE: Limit on the number of points exterior to the
C  boundary. MAXNPE>=1.
C integer NPE: The number of exterior points. 0<=NPE<=MAXNPE.
C real PENT(MAXNPE,3). The coordinates of the exterior point.
C  PENT(i,1),PENT(i,2),PENT(i,3) are the x,y,z coordinates of the i-th
C  point.

C The boundary condition ({\alpha} phi + {\beta} v = f) (input)
C real SALPHA(MAXNSE): The values of {\alpha} at the centres
C  of the panels.
C real SBETA(MAXNSE): The values of {\beta} at the centres
C  of the panels.
C real SF(MAXNSE): The values of "f" at the centres of the 
C  panels.

C Incident field
C real SIPHI(MAXNSE): The incident velocity potential at the
C  centres of the panels
C real PDEPHI(MAXNPE): The incident velocity potential at the chosen
C  exterior points

C Validation and control parameters (input) 
C logical LSOL: A switch to control whether the particular solution is
C  required.
C logical LVALID: A switch to enable the choice of checking of 
C  subroutine parameters.
C real EGEOM: The maximum absolute error in the parameters that
C  describe the geometry.

C Solution (output)
C real SPHI(MAXNSE): The velocity potential ({\phi}) at the 
C  centres of the boundary panels.
C real SVEL(MAXNSE): The velocity (v or d{\phi}/dn where n is
C  the outward normal to the boundary) at the centres of the boundary 
C  panels.
C real PEPHI(MAXNPE): The velocity potential ({\phi}) at the 
C  exterior points.

C Discrete Operators (L_SS and M_SSMINUS changed in GLS)
C real    L_SS(MAXNSE,MAXNSE)
C real    M_SSMINUS(MAXNSE,MAXNSE)
C real    L_DS(MAXNPE,MAXNSE)
C real    M_DS(MAXNPE,MAXNSE)

C Further information from system solution GLS
C logical XORY(MAXNSE)
C real C(MAXNSE)

C Work Space
C real  WKSPC1(MAXNSE)
C real  WKSPC2(MAXNSE)
C real  WKSPC3(MAXNSE)

C Notes on the geometric parameters
C ---------------------------------
C (1) Each of the vertices listed in VERTEX must be distinct points
C  with respect to EGEOM.
C (2) The boundary must be complete and closed. 
C (3) The indices of the nodes listed in SELV must be such that they
C  are ordered counter-clockwise around the boundary, when viewed
C  from just outside the boundary at the panel.
C (4) The largest panel must be no more than 10x the area of the
C  smallest panel.

C Notes on the exterior points 
C ----------------------------
C (1) The points in PENT should lie within the boundary, as defined
C  by the parameters VERTEX and SELV. Any point lying outside the 
C  boundary will return a corresponding value in PEPHI that is near
C  zero. This property can be if a useful check.

C Notes on the boundary condition
C -------------------------------
C (1) For each i=1..NSE, it must not be the case that both of SALPHA(i)
C  and SBETA(i) are zero

C External modules in external files
C ==================================
C subroutine L3LC: Returns the individual discrete Laplace integral
C  operators. (in file L3LC.FOR)
C subroutine GLS: Solves a general linear system of equations. 
C  (in file GLS.FOR)

C External modules provided in the package (this file)
C ====================================================
C subroutine GLT7: Returns the points and weights of the 7-point Gauss-
C  Legendre quadrature rule on the standard triangle.
C real function FNSQRT(X): real X : Returns the square root of X.
C real function FNEXP(X): real X : Returns the natural logarithm of X.

C The subroutine

      SUBROUTINE LEBEM3(MAXNV,NV,VERTEX,MAXNSE,NSE,SELV,
     *                 MAXNPE,NPE,PENT,
     *                 SALPHA,SBETA,SF,SIPHI,PDEPHI,
     *                 LSOL,LVALID,EGEOM,
     *                 SPHI,SVEL,PEPHI,
     *                 L_SS,M_SSMINUS,L_DS,M_DS,
     *                 PERM,XORY,C,WKSPC1,WKSPC2,WKSPC3)
      PARAMETER (MAXNQ=100)


C  Boundary geometry
C   Limit on the number of vertices on S
      INTEGER    MAXNV
C   The number of vertices on S
      INTEGER    NV
C   The coordinates of the vertices on S
      REAL*8     VERTEX(MAXNV,3)
C   Limit on the number of panels describing S
      INTEGER    MAXNSE
C   The number of panels describing S
      INTEGER    NSE
C   The indices of the vertices describing each panel
      INTEGER    SELV(MAXNSE,3)
      
C  Interior points at which the solution is to be observed
C   Limit on the number of points exterior to the boundary where 
C    solution is sought
      INTEGER    MAXNPE
C   The number of exterior points
      INTEGER    NPE
C   Coordinates of the exterior points
      REAL*8     PENT(MAXNPE,3)

C  The boundary condition is such that {\alpha} {\phi} + {\beta} v = f
C  where alpha, beta and f are real valued functions over S.
C  The functions are set values at the central points.
C   function alpha
      REAL*8     SALPHA(MAXNSE)
C   function beta
      REAL*8     SBETA(MAXNSE)
C   function f
      REAL*8     SF(MAXNSE)

C  The incident potential on S
      REAL*8     SIPHI(MAXNSE)
C  The incident potential at the chosen exterior points
      REAL*8     PDEPHI(MAXNPE)

C  Validation and control parameters
      LOGICAL    LSOL
      LOGICAL    LVALID
      REAL*8     EGEOM

C  Solution 
C   function phi
      REAL*8     SPHI(MAXNSE)
C   function vel
      REAL*8     SVEL(MAXNSE)
C   domain solution
      REAL*8     PEPHI(MAXNPE)

C  Discrete Operators (L_SS and M_SSPLUS changed in GLS)
      REAL*8     L_SS(MAXNSE,MAXNSE)
      REAL*8     M_SSMINUS(MAXNSE,MAXNSE)
      REAL*8     L_DS(MAXNPE,MAXNSE)
      REAL*8     M_DS(MAXNPE,MAXNSE)

C Further information from system solution GLS
      INTEGER*4  PERM(MAXNSE)
      LOGICAL    XORY(MAXNSE)
      REAL*8     C(MAXNSE)

C Work Space
      REAL*8     WKSPC1(MAXNSE)
      REAL*8     WKSPC2(MAXNSE)
      REAL*8     WKSPC3(MAXNSE)


c  External function
      REAL*8     DIST3
      REAL*8     AREA

C  Constants
C   Real scalars: 0, 1, 2, half, pi
      REAL*8     ZERO,ONE,TWO,THREE,HALF,THIRD

C  Geometrical description of the boundary
C   panels counter
      INTEGER    ISE,JSE
C   The points exterior to the boundary where the solution is sought 
      INTEGER    IPI
C   Parameters for L3LC
      REAL*8     P(3),PA(3),PB(3),PC(3),QA(3),QB(3),QC(3),VECP(3)
      LOGICAL    LPONEL


C  Quadrature rule information
C   [Note that in this program two quadrature rules are used: one for
C    the case when the point P lies on the panel (LPONEL=.TRUE.) and
C    one for the case when P does not lie on the panel. In general,
C    it is more efficient to define a larger set of quadrature rules
C    so that a particular rule can be selected for any given point P 
C    and panel QA-QB-QC. For example using more quadrature points when
C    the panel is large, less when the panel is small, more when
C    the panel is close to P, less when it is far from P.]
C   Quadrature rule used when LPONEL=.TRUE.
C    Number of quadrature points
      INTEGER    NQON
C    x-Abscissae of the actual quadrature rule
      REAL*8     XQON(MAXNQ)
C    y-Abscissae of the actual quadrature rule
      REAL*8     YQON(MAXNQ)
C    Weights of the actual quadrature rule
      REAL*8     WQON(MAXNQ)
C   Quadrature rule used when LPONEL=.FALSE.
C    Number of quadrature points
      INTEGER    NQOFF
C    x-Abscissae of the actual quadrature rule
      REAL*8     XQOFF(MAXNQ)
C    y-Abscissae of the actual quadrature rule
      REAL*8     YQOFF(MAXNQ)
C    Weights of the actual quadrature rule
      REAL*8     WQOFF(MAXNQ)
C   Quadrature rule parameters for L3LC
C    Actual number of quadrature points
      INTEGER    NQ
C    Abscissae of the actual quadrature rule
      REAL*8     XQ(MAXNQ)
C    Abscissae of the actual quadrature rule
      REAL*8     YQ(MAXNQ)
C    Weights of the actual quadrature rule
      REAL*8     WQ(MAXNQ)
C   Counter through the quadrature points
      INTEGER    IQ

C  Validation and control parameters for subroutine L3LC
      LOGICAL    LVAL
      REAL*8     EQRULE
      LOGICAL    LFAIL1
      LOGICAL    LL
      LOGICAL    LM
      LOGICAL    LMT
      LOGICAL    LN

C  Parameters for subroutine L3LC. 
      REAL*8 DISL
      REAL*8 DISM
      REAL*8 DISMT
      REAL*8 DISN

C  Other variables
C   Error flag
      LOGICAL    LERROR
C   Failure flag
      LOGICAL    LFAIL
C   Accumulation of solution {\phi}
      REAL*8 SUMPHI
C   Maximum,minimum sizes of panels
      REAL*8     SIZMAX,SIZMIN,ASIZE
C   The `diameter' of the boundary or the maximum distance between any
C    three vertices
      REAL*8     DIAM
      REAL*8     SUMM
     

C INITIALISATION
C --------------

C Set constants
      ZERO=0.0D0
      ONE=1.0D0
      TWO=2.0D0
      THREE=3.0D0
      HALF=ONE/TWO
      THIRD=ONE/THREE

C Validation
C ==========

C Validation of parameters of LEBEM3
C ---------------------------------

      IF (LVALID) THEN

C Validation of main paramters
        LERROR=.FALSE.
        IF (MAXNV.LT.3) THEN
          WRITE(*,*) 'MAXNV = ',MAXNV
          WRITE(*,*) 'ERROR(LEBEM3) - must have MAXNV>=4'
          LERROR=.TRUE.
        END IF
        IF (NV.LT.3.OR.NV.GT.MAXNV) THEN
          WRITE(*,*) 'NV = ',NV
          WRITE(*,*) 'ERROR(LEBEM3) - must have 4<=NV<=MAXNV'
          LERROR=.TRUE.
        END IF
        IF (MAXNSE.LT.3) THEN
          WRITE(*,*) 'MAXNSE = ',MAXNSE
          WRITE(*,*) 'ERROR(LEBEM3) - must have MAXNSE>=4'
          LERROR=.TRUE.
        END IF
        IF (NSE.LT.3.OR.NSE.GT.MAXNSE) THEN
          WRITE(*,*) 'NSE = ',NSE
          WRITE(*,*) 'ERROR(LEBEM3) - must have 4<=NSE<=MAXNSE'
          LERROR=.TRUE.
        END IF
        IF (MAXNPE.LT.1) THEN
          WRITE(*,*) 'MAXNPE = ',MAXNPE
          WRITE(*,*) 'ERROR(LEBEM3) - must have MAXNPE>=1'
          LERROR=.TRUE.
        END IF
        IF (NPE.LT.0.OR.NPE.GT.MAXNPE) THEN
          WRITE(*,*) 'NPE = ',NPE
          WRITE(*,*) 'ERROR(LEBEM3) - must have 3<=NPE<=MAXNPE'
          LERROR=.TRUE.
        END IF
        IF (EGEOM.LE.ZERO) THEN
          WRITE(*,*) 'NPE = ',NPE
          WRITE(*,*) 'ERROR(LEBEM3) - EGEOM must be positive'
          LERROR=.TRUE.
        END IF
        IF (LERROR) THEN
          LFAIL=.TRUE.
          WRITE(*,*)
          WRITE(*,*) 'Error(s) found in the main parameters of LEBEM3'
          WRITE(*,*) 'Execution terminated'
          STOP
        END IF
      END IF

C Find the diameter DIAM of the boundary
      DIAM=0.0
      DO 100 IV=1,NV-1
        PA(1)=VERTEX(IV,1)
        PA(2)=VERTEX(IV,2)
        PA(3)=VERTEX(IV,3)
        DO 110 JV=IV+1,NV
          PB(1)=VERTEX(JV,1)
          PB(2)=VERTEX(JV,2)
          PB(3)=VERTEX(JV,3)
          DIAM=MAX(DIAM,DIST3(PA,PB))
110     CONTINUE
100   CONTINUE

      IF (LVALID) THEN
        LERROR=.FALSE.
C Check that the boundary defined by SELV is complete and closed
        DO 120 ISE=1,NSE
120     CONTINUE


C Check that EGEOM is not too large
        IF (EGEOM.GT.DIAM/100.0D0) THEN
          WRITE(*,*) 'EGEOM = ',EGEOM
          WRITE(*,*) 'ERROR(LEBEM3) - EGEOM is set too large'
          LERROR=.TRUE.
        END IF
        IF (LERROR) THEN
          LFAIL=.TRUE.
          WRITE(*,*)
          WRITE(*,*) 'Error in boundary geometry or EGEOM'
          WRITE(*,*) 'Execution terminated'
        END IF
      END IF                  

      IF (LVALID) THEN
C Check that the vertices are distinct with respect to EGEOM
        LERROR=.FALSE.
        DO 130 IV=1,NV-1
          PA(1)=VERTEX(IV,1)
          PA(2)=VERTEX(IV,2)
          PA(3)=VERTEX(IV,3)
          DO 140 JV=IV+1,NV
            PB(1)=VERTEX(JV,1)
            PB(2)=VERTEX(JV,2)
            PB(3)=VERTEX(JV,3)
            IF (ABS(PA(1)-PB(1)).LT.EGEOM) THEN
              IF (ABS(PA(2)-PB(2)).LT.EGEOM) THEN
                IF (ABS(PA(3)-PB(3)).LT.EGEOM) THEN
                  WRITE(*,*) 'Vertices ',IV,JV,' are not distinct'
                  LERROR=.TRUE.
                END IF
              END IF
            END IF
140       CONTINUE
130     CONTINUE
        IF (LERROR) THEN
          WRITE(*,*) 
          WRITE(*,*) 'ERROR(LEBEM3) - Vertices (see above) coincide'
          WRITE(*,*) 'Execution terminated'
          STOP
        END IF
      END IF          


C Check that the panels are not of disproportionate sizes
      IF (LVALID) THEN
        SIZMAX=ZERO
        SIZMIN=DIAM**2
        DO 150 ISE=1,NSE
          QA(1)=VERTEX(SELV(ISE,1),1)
          QA(2)=VERTEX(SELV(ISE,1),2)
          QA(3)=VERTEX(SELV(ISE,1),3)
          QB(1)=VERTEX(SELV(ISE,2),1)
          QB(2)=VERTEX(SELV(ISE,2),2)
          QB(3)=VERTEX(SELV(ISE,2),3)
          QC(1)=VERTEX(SELV(ISE,3),1)
          QC(2)=VERTEX(SELV(ISE,3),2)
          QC(3)=VERTEX(SELV(ISE,3),3)
          ASIZE=AREA(QA,QB,QC)
          SIZMAX=MAX(SIZMAX,ASIZE)
          SIZMIN=MIN(SIZMIN,ASIZE)
150     CONTINUE
        IF (SIZMAX.GT.10.0D0*SIZMIN) THEN
          WRITE(*,*) 'WARNING(LEBEM3) - panels of disproportionate'
          WRITE(*,*) ' sizes'
        END IF
      END IF          
          

C Validation of the surface functions
      IF (LVALID.AND.LSOL) THEN
        LERROR=.FALSE.
        DO 170 ISE=1,NSE
          IF (MAX(ABS(SALPHA(ISE)),ABS(SBETA(ISE))).LT.1.0D-6) 
     *     LERROR=.TRUE.
170     CONTINUE
        IF (LERROR) THEN
          WRITE(*,*) 
          WRITE(*,*) 'ERROR(LEBEM3) - at most one of SALPHA(i),SBETA(i)'
          WRITE(*,*) ' may be zero for all i'
          WRITE(*,*) 'Execution terminated'
          STOP
        END IF
      END IF
        


C Set up validation and control parameters
C  Switch off the validation of L3LC
      LVAL=.FALSE.
C  Set EQRULE
      EQRULE=1.0D-6

C Set up the quadrature rule(s).
C  Set up quadrature rule for the case when P is not on the panel.
C   Set up 8 point Gauss-Legendre rules
      CALL GLT7(MAXNQ,NQOFF,WQOFF,XQOFF,YQOFF)

C  Set up quadrature rule for the case when P is on the panel.

C   Set up quadrature rule data. If LPONEL is false then use the standard
C    Gaussian quadrature rule above. If LPONEL is true then then a
C    quadrature rule with 3 times as many points is used, this is made
C    up from three standard quadrature rules with the quadrature points
C    translated to the three triangles that each have the cetroid and two
C    of the original vertices as its vertices.
      NQON=3*NQOFF
      DO 330 IQ=1,NQOFF
        XQON(IQ)=XQOFF(IQ)*THIRD+YQOFF(IQ)
        YQON(IQ)=XQOFF(IQ)*THIRD
        WQON(IQ)=WQOFF(IQ)/THREE
        XQON(IQ+NQOFF)=XQOFF(IQ)*THIRD
        YQON(IQ+NQOFF)=XQOFF(IQ)*THIRD+YQOFF(IQ)
        WQON(IQ+NQOFF)=WQOFF(IQ)/THREE
        XQON(IQ+2*NQOFF)=THIRD*(ONE+TWO*XQOFF(IQ)-YQOFF(IQ))
        YQON(IQ+2*NQOFF)=THIRD*(ONE-XQOFF(IQ)+TWO*YQOFF(IQ))
        WQON(IQ+2*NQOFF)=WQOFF(IQ)/THREE
330   CONTINUE


C Validation that the surface is closed
      IF (LVALID) THEN
        PA(1)=VERTEX(SELV(1,1),1)
        PA(2)=VERTEX(SELV(1,1),2)
        PA(3)=VERTEX(SELV(1,1),3)
        PB(1)=VERTEX(SELV(1,2),1)
        PB(2)=VERTEX(SELV(1,2),2)
        PB(3)=VERTEX(SELV(1,2),3)
        PC(1)=VERTEX(SELV(1,3),1)
        PC(2)=VERTEX(SELV(1,3),2)
        PC(3)=VERTEX(SELV(1,3),3)
        P(1)=(PA(1)+PB(1)+PC(1))/THREE
        P(2)=(PA(2)+PB(2)+PC(2))/THREE
        P(3)=(PA(3)+PB(3)+PC(3))/THREE
        VECP(1)=0.0D0
        VECP(2)=0.0D0
        VECP(3)=1.0D0
        SUMM=0.0D0
        DO 180 JSE=1,NSE
C  Set QA and QB, the coordinates of the edges of the JSEth panel
          QA(1)=VERTEX(SELV(JSE,1),1)
          QA(2)=VERTEX(SELV(JSE,1),2)
          QA(3)=VERTEX(SELV(JSE,1),3)
          QB(1)=VERTEX(SELV(JSE,2),1)
          QB(2)=VERTEX(SELV(JSE,2),2)
          QB(3)=VERTEX(SELV(JSE,2),3)
          QC(1)=VERTEX(SELV(JSE,3),1)
          QC(2)=VERTEX(SELV(JSE,3),2)
          QC(3)=VERTEX(SELV(JSE,3),3)
C     Set LPONEL
          LPONEL=(JSE.EQ.1)

C     Only the M operator is required. Set LM true, 
C      LL,LMT,LN false. 
          LL=.FALSE.
          LM=.TRUE.
          LMT=.FALSE.
          LN=.FALSE.

C     Call L3LC.
          CALL L3LC(P,VECP,QA,QB,QC,LPONEL,
     *     MAXNQ,NQON,XQON,YQON,WQON,
     *     LVAL,EGEOM,EQRULE,LFAIL1,
     *     LL,LM,LMT,LN,DISL,DISM,DISMT,DISN)

          
          SUMM=SUMM+DISM
180     CONTINUE
        IF (ABS(SUMM-0.5D0).LT.0.1) THEN
          WRITE(*,*) 
          WRITE(*,*) 'ERROR(LEBEM3) - in geometry'
          WRITE(*,*) ' The boundary could be oriented wrongly'
          WRITE(*,*) '  On the outer boundary arrange panels'
     *     // 'in clockwise order'
          WRITE(*,*) '  If there are inner boundaries arrange the'
     *     // 'panels in anticlockwise order'
          STOP
        END IF
        IF (ABS(SUMM+0.5D0).GT.0.1) THEN
          WRITE(*,*) 
          WRITE(*,*) 'WARNING(LEBEM3) - in geometry'
          WRITE(*,*) ' The boundary panels may be arranged incorrectly'
        END IF
      END IF  


C Validation that the points in PENT are exterior points
      IF (LVALID) THEN
        DO IPI=1,NPE
        P(1)=PENT(IPI,1)
        P(2)=PENT(IPI,2)
        P(3)=PENT(IPI,3)
        VECP(1)=0.0D0
        VECP(2)=0.0D0
        VECP(3)=1.0D0
        SUMM=0.0D0
        DO 210 JSE=1,NSE
C  Set QA and QB, the coordinates of the edges of the JSEth panel
          QA(1)=VERTEX(SELV(JSE,1),1)
          QA(2)=VERTEX(SELV(JSE,1),2)
          QA(3)=VERTEX(SELV(JSE,1),3)
          QB(1)=VERTEX(SELV(JSE,2),1)
          QB(2)=VERTEX(SELV(JSE,2),2)
          QB(3)=VERTEX(SELV(JSE,2),3)
          QC(1)=VERTEX(SELV(JSE,3),1)
          QC(2)=VERTEX(SELV(JSE,3),2)
          QC(3)=VERTEX(SELV(JSE,3),3)
C     Set LPONEL
          LPONEL=.FALSE.

C     Only the M operator is required. Set  LM true, 
C      LL,LMT,LN false. 
          LL=.FALSE.
          LM=.TRUE.
          LMT=.FALSE.
          LN=.FALSE.

C     Call L3LC.
          CALL L3LC(P,VECP,QA,QB,QC,LPONEL,
     *     MAXNQ,NQON,XQON,YQON,WQON,
     *     LVAL,EGEOM,EQRULE,LFAIL1,
     *     LL,LM,LMT,LN,DISL,DISM,DISMT,DISN)

          
          SUMM=SUMM+DISM
210     CONTINUE

        IF (ABS(SUMM).GT.0.25) THEN
          WRITE(*,*) 
          WRITE(*,*) 'WARNING(IBEM2) - The observation point'
          WRITE(*,*) ' (',P(1),',',P(2),',',P(3),')'
          WRITE(*,*) ' may not be exterior to the boundary'
        END IF
      END DO
      END IF


C  Compute the discrete L, M, Mt and N matrices
C   Loop(ISE) through the points on the boundary
      DO 510 ISE=1,NSE
C    Set P
        PA(1)=VERTEX(SELV(ISE,1),1)
        PA(2)=VERTEX(SELV(ISE,1),2)
        PA(3)=VERTEX(SELV(ISE,1),3)
        PB(1)=VERTEX(SELV(ISE,2),1)
        PB(2)=VERTEX(SELV(ISE,2),2)
        PB(3)=VERTEX(SELV(ISE,2),3)
        PC(1)=VERTEX(SELV(ISE,3),1)
        PC(2)=VERTEX(SELV(ISE,3),2)
        PC(3)=VERTEX(SELV(ISE,3),3)
        P(1)=(PA(1)+PB(1)+PC(1))/THREE
        P(2)=(PA(2)+PB(2)+PC(2))/THREE
        P(3)=(PA(3)+PB(3)+PC(3))/THREE
C    Set VECP to the normal on the boundary of the panel at P
        CALL NORM3(PA,PB,PC,VECP)
C    Loop(ISE) through the panels
        DO 520 JSE=1,NSE
C     Set QA and QB, the coordinates of the edges of the JSEth panel
          QA(1)=VERTEX(SELV(JSE,1),1)
          QA(2)=VERTEX(SELV(JSE,1),2)
          QA(3)=VERTEX(SELV(JSE,1),3)
          QB(1)=VERTEX(SELV(JSE,2),1)
          QB(2)=VERTEX(SELV(JSE,2),2)
          QB(3)=VERTEX(SELV(JSE,2),3)
          QC(1)=VERTEX(SELV(JSE,3),1)
          QC(2)=VERTEX(SELV(JSE,3),2)
          QC(3)=VERTEX(SELV(JSE,3),3)

C     Set LPONEL
          IF (ISE.EQ.JSE) THEN
            LPONEL=.TRUE.
          ELSE
            LPONEL=.FALSE.
          END IF

C     Select quadrature rule for L3LC
C   :  Select the quadrature rule XQON-WQON in the case when the
C   :   point p lies on the panel, otherwise select XQOFF-WQOFF
C      [Note that the overall method would benefit from selecting from
C       a wider set of quadrature rules, and an appropriate method
C       of selection]
          IF (LPONEL) THEN
            NQ=NQON
            DO 600 IQ=1,NQ
              XQ(IQ)=XQON(IQ)
              YQ(IQ)=YQON(IQ)
              WQ(IQ)=WQON(IQ)
600         CONTINUE
          ELSE 
            NQ=NQOFF
            DO 610 IQ=1,NQ
              XQ(IQ)=XQOFF(IQ)
              YQ(IQ)=YQOFF(IQ)
              WQ(IQ)=WQOFF(IQ)
610         CONTINUE
          END IF

C     All operators are required
          LL=.TRUE.
          LM=.TRUE.
          LMT=.FALSE.
          LN=.FALSE.

C     Call L3LC.
          CALL L3LC(P,VECP,QA,QB,QC,LPONEL,
     *     MAXNQ,NQ,XQ,YQ,WQ,
     *     LVAL,EGEOM,EQRULE,LFAIL1,
     *     LL,LM,LMT,LN,DISL,DISM,DISMT,DISN)

          L_SS(ISE,JSE)=DISL
          M_SSMINUS(ISE,JSE)=DISM
         
C    Close loop(JSE) 
520     CONTINUE

        M_SSMINUS(ISE,ISE)=M_SSMINUS(ISE,ISE)-HALF
        IF (LSOL) C(ISE)=SIPHI(ISE)
            
C   Close loop(ISE) 
510   CONTINUE

      IF (LSOL) THEN
        CALL GLS(MAXNSE,NSE,M_SSMINUS,L_SS,C,SALPHA,SBETA,SF,
     *   SPHI,SVEL,LFAIL,PERM,XORY,WKSPC1,WKSPC2,WKSPC3)
      END IF
        

C  SOLUTION IN THE DOMAIN

C   Compute the potential at the selected exterior points.
C    Loop through the the points in the exterior region
      DO 800 IPE=1,NPE
C    Set P
        P(1)=PENT(IPE,1)
        P(2)=PENT(IPE,2)
        P(3)=PENT(IPE,3)
C    Set VECP, this is arbitrary as the derivative of the potential
C     at P is not sought.
        VECP(1)=ONE
        VECP(2)=ZERO
        VECP(3)=ZERO

C    Initialise SUMPHI to the incident potential
        SUMPHI=PDEPHI(IPE)

C    Loop(JSE) through the panels
        DO 850 JSE=1,NSE
C     Compute the discrete L and M integral operators. 
            
C     Set QA, QB and QC the coordinates of the vertices of the JSEth panel
          QA(1)=VERTEX(SELV(JSE,1),1)
          QA(2)=VERTEX(SELV(JSE,1),2)
          QA(3)=VERTEX(SELV(JSE,1),3)
          QB(1)=VERTEX(SELV(JSE,2),1)
          QB(2)=VERTEX(SELV(JSE,2),2)
          QB(3)=VERTEX(SELV(JSE,2),3)
          QC(1)=VERTEX(SELV(JSE,3),1)
          QC(2)=VERTEX(SELV(JSE,3),2)
          QC(3)=VERTEX(SELV(JSE,3),3)

C     All the points do not lie on the boundary hence LPONEL=.FALSE.
          LPONEL=.FALSE.              

C     Only L, M operators are required. Set LL,LM true, 
C      LMT,LN false. 
          LL=.TRUE.
          LM=.TRUE.
          LMT=.FALSE.
          LN=.FALSE.
                
C     Call L3LC.
          CALL L3LC(P,VECP,QA,QB,QC,LPONEL,
     *     MAXNQ,NQOFF,XQOFF,YQOFF,WQOFF,
     *     LVAL,EGEOM,EQRULE,LFAIL,
     *     LL,LM,LMT,LN,DISL,DISM,DISMT,DISN)

C     Accumulate phi 
          IF (LSOL) SUMPHI=SUMPHI-DISL*SVEL(JSE)+DISM*SPHI(JSE)

          IF (.NOT.LSOL) THEN
            L_DS(IPE,JSE)=DISL
            M_DS(IPE,JSE)=DISM
          END IF

C      Close loop (JSE) through the panels
850     CONTINUE

        PEPHI(IPE)=SUMPHI

C     Close loop(IPE) through the exterior points
800   CONTINUE

      END


C ----------------------------------------------------------------------

C Subordinate routines for LEBEM3
C ==============================



C Subroutines required for L3LC (not in file L3LC.FOR) 
C  Subroutine for returning the square root.
       REAL*8 FUNCTION FNSQRT(X)
       REAL*8 X
       FNSQRT=SQRT(X)
       END

