*-----------------------------------------------------------------------
*     Copyright (C) 2000-2016 GFD Dennou Club. All rights reserved.
*-----------------------------------------------------------------------
      SUBROUTINE UETONB(Z,MX,NX,NY)

      REAL      Z(MX,*)

      INTEGER   NP(2),NI(2)
      REAL      XC(4),YC(4),ZC(4),AX(10),AY(10),TLM(2)
      LOGICAL   LMISS

      COMMON    /UEBLK1/ TL1,TL2,IPT,NT,LASCND
      PARAMETER (MAXNT=100)
      LOGICAL   LASCND
      INTEGER   IPT(MAXNT)
      REAL      TL1(MAXNT),TL2(MAXNT)

      EXTERNAL  RUWGX,RUWGY


*     / GET INTERNAL PARAMETERS /

      CALL GLLGET('LMISS   ',LMISS )
      CALL GLRGET('RMISS   ',RMISS )
      CALL SGIGET('ITR     ',ITR)

*     / SET GRID ATTRIBUTE IF IT HAS NOT BEEN SET YET /

      CALL UWDFLT(NX,NY)

*     / CHECK Z VALUES AND TONE LEVEL /

      CALL UEZCHK(Z,MX,NX,NY,'UETONB',ISTAT)
      IF (ISTAT.NE.0) RETURN

*     / SET TONE MODE (IRMODE) /

      CALL UWQGXB(UXMIN,UXMAX,NXZ)
      CALL UWQGYB(UYMIN,UYMAX,NYZ)

      IF (ITR.LT.4) THEN
        CALL STFTRF(UXMIN,UYMIN,VXMIN,VYMIN)
        CALL STFTRF(UXMAX,UYMAX,VXMAX,VYMAX)
        DX=VXMAX-VXMIN
        DY=VYMAX-VYMIN
      ELSE
        DX=UXMAX-UXMIN
        DY=UYMAX-UYMIN
      END IF

      IRMODE=0
      IF (DX.LT.0) IRMODE=MOD(IRMODE+1,2)
      IF (DY.LT.0) IRMODE=MOD(IRMODE+1,2)

      CALL SGISET('IRMODE', IRMODE)

*     / INITIALIZE /

      CALL UEAINT

*     / LOOP FOR EACH TONE PATTERN /

      DO 30 IT=1,NT

        CALL SZTNOP(IPT(IT))

*       / LOOP FOR EACH SECTION /

        DO 20 I=1,NX

          I0=I-1
          I1=I+1

          IF (I.EQ.1) THEN
            XC(1)=RUWGX(I)
          ELSE
            XC(1)=(RUWGX(I0)+RUWGX(I))/2.0
          END IF
          IF (I.EQ.NX) THEN
            XC(2)=RUWGX(I)
          ELSE
            XC(2)=(RUWGX(I)+RUWGX(I1))/2.0
          END IF
          XC(3)=XC(2)
          XC(4)=XC(1)

          DO 10 J=1,NY

            J0=J-1
            J1=J+1

            IF (Z(I,J).LT.TL1(IT)) GO TO 10
            IF (Z(I,J).GT.TL2(IT)) GO TO 10

            ZC(1)=Z(I,J)
            ZC(2)=Z(I,J)
            ZC(3)=Z(I,J)
            ZC(4)=Z(I,J)

            IF (LMISS .AND. NINDXR(ZC,4,1,RMISS).NE.0) GO TO 10

            IF (J.EQ.1) THEN
              YC(1)=RUWGY(J)
            ELSE
              YC(1)=(RUWGY(J0)+RUWGY(J))/2.0
            END IF
            IF (J.EQ.NY) THEN
              YC(3)=RUWGY(J)
            ELSE
              YC(3)=(RUWGY(J)+RUWGY(J1))/2.0
            END IF
            YC(2)=YC(1)
            YC(4)=YC(3)

            TLM(1)=TL1(IT)
            TLM(2)=TL2(IT)
            CALL UEAREA(XC,YC,ZC,TLM,AX,AY,NP,NI,NG)

            DO 40 N=1,NG
              CALL SZTNZU(NP(N),AX(NI(N)),AY(NI(N)))
   40       CONTINUE

   10     CONTINUE
   20   CONTINUE

        CALL SZTNCL

   30 CONTINUE

      END
