*-----------------------------------------------------------------------
*     UDLINE
*-----------------------------------------------------------------------
*     Copyright (C) 2000-2016 GFD Dennou Club. All rights reserved.
*-----------------------------------------------------------------------
      SUBROUTINE UDLINE(Z,MX,KX,KY,KK,CX,LOPEN,IBR)

      INTEGER   IBR(*)
      REAL      Z(MX,*)
      LOGICAL   LOPEN

      INTEGER   JX(0:3),JY(0:3),JK(0:3)
      REAL      TX(0:3),TY(0:3),RTX(0:3)
      LOGICAL   LTX(0:3),LUDCHK,LNP,LEND

      SAVE


*     / MAIN /

      IX=KX
      IY=KY
      K =KK
      K1=1-K
      IX0=IX
      IY0=IY
      K0 =K
      CALL UDUXUY(Z,MX,IX,IY,K,CX,UX,UY)
      CALL SZOPLU
      CALL SZMVLU(UX,UY)
      IF (LOPEN) THEN
        CALL UDBCLR(IX,IY,K,0,IBR)
      END IF
      IX1=IX+K
      IY1=IY+K1
      IF (LUDCHK(IX1,IY1,K,1,IBR)) THEN
        CALL UDGRDN(1,IX,IY,K,JX,JY,JK)
      ELSE
        CALL UDGRDN(2,IX,IY,K,JX,JY,JK)
      END IF

   30 CONTINUE
        NP=0
        IF (LUDCHK(JX(2),JY(2),JK(2),1,IBR)) THEN
          LTX(0)=.TRUE.
          DO 10 J=1,3
            IF (LUDCHK(JX(J),JY(J),JK(J),0,IBR)) THEN
              NP=NP+1
              LTX(J)=.TRUE.
              JN=J
            ELSE
              LTX(J)=.FALSE.
            END IF
   10     CONTINUE
          IF (NP.EQ.1) THEN
            JP=JN
            CALL UDUXUY(Z,MX,JX(JP),JY(JP),JK(JP),CX,SX,SY)
          ELSE IF (NP.EQ.2) THEN
            IF (LTX(0).EQV.LTX(1)) THEN
              JP=1
            ELSE
              JP=3
            END IF
            CALL UDUXUY(Z,MX,JX(JP),JY(JP),JK(JP),CX,SX,SY)
          ELSE IF (NP.EQ.3) THEN
            DO 15 J=0,3
              CALL UDUXUY(Z,MX,JX(J),JY(J),JK(J),CX,TX(J),TY(J))
   15       CONTINUE
            CALL GLRGET('REALMAX',RTMIN)
            DO 20 J=0,3
              J1=J
              J2=MOD(J+1,4)
              RTX(J)=SQRT((TX(J1)-TX(J2))**2+(TY(J1)-TY(J2))**2)
              IF (RTX(J).LT.RTMIN) THEN
                RTMIN=RTX(J)
                JRT=J
              END IF
   20       CONTINUE
            JM1=JRT
            JM2=MOD(JRT+1,4)
            LTX(JM1)=.FALSE.
            LTX(JM2)=.FALSE.
            IF (LTX(0).EQV.LTX(1)) THEN
              JP=1
              SX=TX(1)
              SY=TY(1)
            ELSE
              JP=3
              SX=TX(3)
              SY=TY(3)
            END IF
          END IF
        END IF
        LNP=NP.EQ.0
        IF (.NOT.LNP) THEN
          CALL SZPLLU(SX,SY)
          IXD=JX(JP)-IX
          IYD=JY(JP)-IY
          IX=JX(JP)
          IY=JY(JP)
          K =JK(JP)
          CALL UDBCLR(IX,IY,K,0,IBR)
          IF ((K.EQ.0 .AND. IYD.EQ.1) .OR.
     +        (K.EQ.1 .AND. IXD.EQ.1)) THEN
            CALL UDGRDN(1,IX,IY,K,JX,JY,JK)
          ELSE
            CALL UDGRDN(2,IX,IY,K,JX,JY,JK)
          END IF
        END IF
        LEND=IX.EQ.IX0 .AND. IY.EQ.IY0 .AND. K.EQ.K0
      IF (.NOT.(LNP.OR.LEND)) GO TO 30

      CALL SZCLLU

      END
