C Copyright 1981-2016 ECMWF.
C
C This software is licensed under the terms of the Apache Licence 
C Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
C
C In applying this licence, ECMWF does not waive the privileges and immunities 
C granted to it by virtue of its status as an intergovernmental organisation 
C nor does it submit to any jurisdiction.
C

      SUBROUTINE GBYTES (S,D,ISKIP1,IBSIZ,ISKIP2,NBYTES,KWOFF)
C
C---->
C**** GBYTES - Extract a number of bit fields. Cray routine.
C
C S CONTAINS A BIT STRING OF INDEFINITE LENGTH. GBYTES WILL
C EXTRACT NBYTES BITSTRINGS, IBSIZ BITS LONG, AND STORE THEM
C RIGHT JUSTIFIED 0 FILL, INTO SUCCESSIVE WORDS OF D. THE
C SUCCESSIVE BITSTRINGS START AT BIT POSITIONS
C     ISKIP1+1+(IBYTE-1)*(IBSIZ+ISKIP2)
C IN THE BIT STRING S. I.E. SKIP ISKIP1 BITS AT THE START,
C AND ISKIP2 BITS BETWEEN THE EXTRACTED STRINGS.
C BIT ISKP+1 IN A STRING IS FOUND IN WORD IS=1+ISKIP/NBPW IN S,
C WHERE NBPW IS THE NUMBER OF BITS PER WORD. THE STARTING BIT
C IS FOUND BY SKIPPING MOD(ISKP,NBPW) BITS IN THAT WORD.
C KWOFF IS AN OPTIONAL 7TH PARAMETER, WHICH DEFAULTS TO 0
C IF PRESENT KWOFF BITS ARE TOTALLY IGNORED AT THE START OF A WORD
C THUS IF A PACKED CYBER BIT STRING IS TRANSFERRED TO THE
C CRAY, WITH EACH 60 BIT CYBER WORD PLACED AT THE RIGHT END OF
C A 64 BIT CRAY WORD, A BYTE SEQUENCE WHICH WAS ORIGINALLY
C LOCATED WITH START POINTS IN ARITHMETIC PROGRESSION ON THE
C CYBER, WILL NO LONGER HAVE THIS PROPERTY ON THE CRAY. BY
C USING THE ROUTINE WITH KWOFF=4, THE ELEMENTS OF THE BYTE
C SEQUENCE CAN BE EXTRACTED ON THE CRAY, USING THE SAME SKIPS
C AS WERE USED ON THE CYBER.
C
C----<
      PARAMETER(NBPW=64)
      DIMENSION S(2) , D(NBYTES)
      INTEGER SH1
      IGNORE = 0
#ifdef CRAY
      IF(NUMARG().GT.6) IGNORE = KWOFF
#else
      IF(NUMARG(DUMMY).GT.6) IGNORE = KWOFF
#endif
      IS=1+ISKIP1/(NBPW-IGNORE)
      ISKIP = MOD(ISKIP1,NBPW-IGNORE) + IGNORE
      ISTEP = ISKIP2+IBSIZ
      DO 75 IBYTE = 1 , NBYTES
C WITH THE STARTING WORD AND BIT POSITION DETERMINED, THE
C DESIRED EXTRACTION CAN BE DONE BY
C***     CALL GBYTE(S(IS),D(IBYTE),ISKIP,IBSIZ)
C BUT SINCE THE CODE IS SHORT IT IS INSERTED IN-LINE.
         SH1 = ISKIP+IBSIZ
         IF(SH1.GT.NBPW) GO TO 50
C BYTE COMES FROM 1 WORD OF S
         D(IBYTE) = AND( SHIFT(S(IS),SH1),SHIFT(MASK(IBSIZ),IBSIZ))
         GO TO 65
   50    CONTINUE
         SH1 =SH1-NBPW
C BYTE COMES FROM 2 WORDS OF S.
         D(IBYTE) = OR(SHIFT(AND(S(IS),COMPL(MASK(ISKIP))),SH1)
     1                           ,
     2                SHIFT(AND(SHIFT(S(IS+1),IGNORE),MASK(SH1)),SH1)
     3                 )
   65    CONTINUE
C UPDATE STARTING WORD AND BIT POSITION
         ISKIP = ISKIP+ISTEP
         IF(ISKIP.LT.NBPW) GO TO 75
         ISKIP =ISKIP-NBPW
         IS = IS+1+ISKIP/(NBPW-IGNORE)
         ISKIP = MOD(ISKIP,NBPW-IGNORE) + IGNORE
   75 CONTINUE
      RETURN
      END
