*-----------------------------------------------------------------------
*     Copyright (C) 2000-2016 GFD Dennou Club. All rights reserved.
*-----------------------------------------------------------------------
      SUBROUTINE UHBXAZ(N,UPX1,UPX2,UPY,ITPAT1,ITPAT2)

      REAL      UPX1(*),UPX2(*),UPY(*)

      LOGICAL   LMISS, LYUNI, LXC1, LXC2
      CHARACTER COBJ*80

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


      IF (N.LT.1) THEN
        CALL MSGDMP('E','UHBXAZ','NUMBER OF POINTS IS LESS THAN 1.')
      END IF
      IF (ITPAT1.EQ.0 .OR. ITPAT2.EQ.0) THEN
        CALL MSGDMP('M','UHBXAZ','TONE PAT. INDEX IS 0 / DO NOTHING.')
        RETURN
      END IF
      IF (ITPAT1.LT.0 .OR. ITPAT2.LT.0) THEN
        CALL MSGDMP('E','UHBXAZ','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('UHBXAZ',COBJ)

      LYUNI = UPY(1).EQ.RUNDEF
      LXC1  = UPX1(1).EQ.RUNDEF
      LXC2  = UPX2(1).EQ.RUNDEF

      IF (LYUNI) THEN
        CALL UUQIDV(UYMIN, UYMAX)
        IF (UYMIN.EQ.RUNDEF) CALL SGRGET('UYMIN', UYMIN)
        IF (UYMAX.EQ.RUNDEF) CALL SGRGET('UYMAX', UYMAX)
        DY = (UYMAX-UYMIN)/N
      END IF

      IF (LXC1 .OR. LXC2) THEN
        CALL UURGET('UREF', UREF)
      END IF

      DO 20 I=1,N
        IF (LYUNI) THEN
          UY1 = UYMIN + DY*(I-1)
          UY2 = UYMIN + DY*I
        ELSE
          UY1 = UPY(I)
          UY2 = UPY(I+1)
        END IF

        IF (LXC1) THEN
          UX1 = UREF
        ELSE
          UX1 = UPX1(I)
        END IF

        IF (LXC2) THEN
          UX2 = UREF
        ELSE
          UX2 = UPX2(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 (UX2 .GT. UX1) THEN
            CALL SZSTNI(ITPAT1)
          ELSE
            CALL SZSTNI(ITPAT2)
          END IF

          IF ((VY2-VY1)*(VX2-VX1).LT.0) THEN
            VXX = VX1
            VX1 = VX2
            VX2 = VXX
          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('UHBXAZ')

      END
