*-----------------------------------------------------------------------
*     SBYTES
*-----------------------------------------------------------------------
*     Copyright (C) 2000-2022 GFD Dennou Club. All rights reserved.
*-----------------------------------------------------------------------
      SUBROUTINE SBYTES (NPACK,ISAM,IBIT,NBITS,NSKIP,ITER)

      IMPLICIT  INTEGER (A-Z)

      INTEGER   ISAM(*),NPACK(*)

      PARAMETER (BPERI=32)

      INTEGER   MASK(BPERI)

      SAVE

      EXTERNAL  ISHIFT

      DATA      NCALL/0/


      IF (NCALL.EQ.0) THEN
        CALL GLIGET('NBITSPW',NBITPW)
        IF (NBITPW.NE.BPERI) THEN
          CALL MSGDMP('E','SBYTES',
     +      'NUMBER OF BITS PER ONE WORD IS INVALID / '//
     +      'CHECK BPERI IN THE PARAMETER STATEMENT OF GBYTES '//
     +      'AND CHANGE IT CORRECTLY.')
        END IF
        MASK(1)=1
        DO 10 I=2,BPERI
          MASK(I)=IOR(ISHIFT(MASK(I-1),1),1)
   10   CONTINUE
        NCALL=1
      END IF

      IF (.NOT.(NBITS.LE.BPERI .AND. NBITS.GT.0)) THEN
        CALL MSGDMP('E','SBYTES','NBITS OUT OF RANGE.')
      END IF

      MSK1=MASK(NBITS)
      MSK2=MASK(BPERI-NBITS)
      BITSEP=NBITS+NSKIP
      DO 20 I=1,ITER
        SBITS=IAND(MSK1,ISAM(I))
        BPO=IBIT+(I-1)*BITSEP
        WPO=BPO/BPERI+1
        RBITS=BPERI*WPO-BPO
        UBITS=BPERI-RBITS
        IF (RBITS.GE.NBITS) THEN
          LSHIFT=BPERI-UBITS-NBITS
          NPACK(WPO)=IAND(NPACK(WPO),ISHIFT(MSK2,LSHIFT+NBITS))
          NPACK(WPO)=IOR(NPACK(WPO),ISHIFT(SBITS,LSHIFT))
        ELSE
          RSHIFT=RBITS-NBITS
          BTMP=ISHIFT(SBITS,RSHIFT)
          NPACK(WPO)=IAND(NPACK(WPO),ISHIFT(MASK(UBITS),RBITS))
          NPACK(WPO)=IOR(NPACK(WPO),BTMP)
          BTMP=ISHIFT(IAND(MASK(-RSHIFT),SBITS),BPERI+RSHIFT)
          NPACK(WPO+1)=IAND(NPACK(WPO+1),MASK(BPERI+RSHIFT))
          NPACK(WPO+1)=IOR(NPACK(WPO+1),BTMP)
        END IF
   20 CONTINUE

      END
