      SUBROUTINE EPI(PHI,CPHI,K2,L2,N,M,P,IERR)
C     ----------------------
C     ELLIPTIC INTEGRAL OF THE THIRD KIND
C     ----------------------
      REAL K2,L2,N,M
C
      IF (AMIN1(PHI,CPHI) .LT. 0.0) GO TO 100
      IF (ABS(N) .GT. 1.0) GO TO 110
      IF (K2 .LT. 0.0 .OR. K2 .GT. 1.0) GO TO 120
C
      IF (PHI .LT. 0.79) GO TO 10
          S = COS(CPHI)
          C = SIN(CPHI)
          GO TO 11
   10 S = SIN(PHI)
      C = COS(PHI)
   11 A = C*C
      B = L2 + K2*A
      S2 = S*S
      IF (N .LE. 0.0) GO TO 12
          R = M + N*A
          GO TO 20
   12 R = 1.0 - N*S2
C
   20 U = SPMPAR(1)
      IF (U .LT. 7.E-12) GO TO 22
      IF (U .LT. 7.E-09) GO TO 21
          ERR = 3.E-02
          GO TO 30
   21 ERR = 1.E-02
      GO TO 30
   22 ERR = 3.E-03
C
   30 P = RJ(A,B,1.0,R,ERR,IERR)
      IF (IERR .NE. 0) GO TO 130
      P = P*(S*S2)*N/3.0
      P = P + S*RF(A,B,1.0,ERR,IERR)
      RETURN
C
C     ERROR RETURN
C
  100 IERR = 1
      RETURN
  110 IERR = 2
      RETURN
  120 IERR = 3
      RETURN
  130 IERR = 4
      RETURN
      END
