*-----------------------------------------------------------------------
*     Copyright (C) 2000-2016 GFD Dennou Club. All rights reserved.
*-----------------------------------------------------------------------
      SUBROUTINE UVBXAZ(N,UPX,UPY1,UPY2,ITPAT1,ITPAT2)

      REAL      UPX(*),UPY1(*),UPY2(*)

      LOGICAL   LMISS, LXUNI, LYC1, LYC2
      CHARACTER COBJ*80

      COMMON    /SZBTN2/ IRMODE, IRMODR
      COMMON    /SZBTN3/ LCLIP
      LOGICAL   LCLIP


      IF (N.LT.1) THEN
        CALL MSGDMP('E','UVBXAZ','NUMBER OF POINTS IS LESS THAN 1.')
      END IF
      IF (ITPAT1.EQ.0 .OR. ITPAT2.EQ.0) THEN
        CALL MSGDMP('M','UVBXAZ','TONE PAT. INDEX IS 0 / DO NOTHING.')
        RETURN
      END IF
      IF (ITPAT1.LT.0 .OR. ITPAT2.LT.0) THEN
        CALL MSGDMP('E','UVBXAZ','TONE PAT. INDEX IS LESS THAN 0.')
      END IF

      CALL SGLGET('LCLIP' , LCLIP )
      CALL GLRGET('RUNDEF', RUNDEF)
      CALL GLRGET('RMISS' , RMISS)
      CALL GLLGET('LMISS' , LMISS)

      CALL STFPR2(0., 0., RX0, RY0)
      CALL STFPR2(0., 1., RX1, RY1)
      CALL STFPR2(1., 0., RX2, RY2)

      ROT = (RX2-RX0)*(RY1-RY0) - (RY2-RY0)*(RX1-RX0)

      IRMODE = 0
      IF (ROT.GT.0) THEN
        IRMODR = IRMODE
      ELSE
        IRMODR = MOD(IRMODE+1, 2)
      END IF

      WRITE(COBJ,'(2I8)') ITPAT1, ITPAT2
      CALL CDBLK(COBJ)
      CALL SWOOPN('UVBXAZ',COBJ)

      LXUNI = UPX(1).EQ.RUNDEF
      LYC1  = UPY1(1).EQ.RUNDEF
      LYC2  = UPY2(1).EQ.RUNDEF

      IF (LXUNI) THEN
        CALL UUQIDV(UXMIN, UXMAX)
        IF (UXMIN.EQ.RUNDEF) CALL SGRGET('UXMIN', UXMIN)
        IF (UXMAX.EQ.RUNDEF) CALL SGRGET('UXMAX', UXMAX)
        DX = (UXMAX-UXMIN)/N
      END IF

      IF (LYC1 .OR. LYC2) THEN
        CALL UURGET('UREF', UREF)
      END IF

      DO 20 I=1,N
        IF (LXUNI) THEN
          UX1 = UXMIN + DX*(I-1)
          UX2 = UXMIN + DX*I
        ELSE
          UX1 = UPX(I)
          UX2 = UPX(I+1)
        END IF

        IF (LYC1) THEN
          UY1 = UREF
        ELSE
          UY1 = UPY1(I)
        END IF

        IF (LYC2) THEN
          UY2 = UREF
        ELSE
          UY2 = UPY2(I)
        END IF

        IF (.NOT.
     #    ((UX1.EQ.RMISS .OR. UX1.EQ.RMISS .OR.
     #      UY1.EQ.RMISS .OR. UY2.EQ.RMISS) .AND. LMISS)) THEN

          CALL STFTRF(UX1, UY1, VX1, VY1)
          CALL STFTRF(UX2, UY2, VX2, VY2)

          IF (UY2 .GT. UY1) THEN
            CALL SZSTNI(ITPAT1)
          ELSE
            CALL SZSTNI(ITPAT2)
          END IF

          IF ((VY2-VY1)*(VX2-VX1).LT.0) THEN
            VYY = VY1
            VY1 = VY2
            VY2 = VYY
          END IF

          CALL SZOPTV
          CALL SZSTTV(VX1, VY1)
          CALL SZSTTV(VX2, VY1)
          CALL SZSTTV(VX2, VY2)
          CALL SZSTTV(VX1, VY2)
          CALL SZSTTV(VX1, VY1)
          CALL SZCLTV

        END IF
   20 CONTINUE

      CALL SWOCLS('UVBXAZ')

      END
