;+
; Project     :	SOHO - CDS
;
; Name        :	EXTBITS()
;
; Purpose     :	Extract bits from data words.
;
; Category    :	EGSE
;
; Explanation :	Called from decompression routines.
;
; Syntax      :	Result = EXTBITS( NBITS, DATA, WORDPOS, BITPOS, GOOD )
;
; Examples    :	
;
; Inputs      :	NBITS	= Number of bits to extract.  Must be <= 16
;		DATA	= Integer*2 array to extract bits from.
;		WORDPOS	= Position of word to start extracting bits from.
;		BITPOS	= Position within word of first bit to extract.
;
; Opt. Inputs :	None.
;
; Outputs     :	The result of the function is an integer value containing the
;		extracted bits.
;
; Opt. Outputs:	GOOD	= If 1, then the value was successfully extracted, or 0
;			  otherwise.
;
; Keywords    :	None.
;
; Calls       :	None.
;
; Common      :	DECOMPBLOCK
;
; Restrictions:	None.
;
; Side effects:	If you try to extract bits past the end of data, then 0 is
;		returned, and GOOD is set to 0.
;
; Prev. Hist. :	Original by M K Carter, RAL
;
; History     :	EGSE version by C D Pike, RAL 7-Oct-93
;		Version 2, William Thompson, 17 November 1995
;			Added output parameter good.
;
; Contact     :	CDPIKE
;-
;

FUNCTION extbits, nbits, data, wordpos, bitpos, good


  COMMON decompblock, bits

; Define a default value of zero, and a default value of good of 1.  If good is
; set to zero, then the no data was extracted.

  value = 0
  good = 1

; bits(n) contains masks for first n bits of word 

; assumes nbits <= 16

  tbits = bitpos + nbits - 16

  IF tbits GT 0 THEN BEGIN

;   goes into next word

    if (wordpos+1) lt n_elements(data) then begin
      temp1 = ISHFT (data(wordpos), -bitpos) AND bits(16-bitpos)
      temp2 = ISHFT (data(wordpos+1) AND bits (tbits),16-bitpos)     
      value = temp1 OR temp2
      bitpos  = tbits
      wordpos = wordpos + 1
    end else good = 0
    
  ENDIF ELSE IF tbits EQ 0 THEN BEGIN

;   in current word, ends on word boundary

    if wordpos lt n_elements(data) then begin
      value = ISHFT (data(wordpos), -bitpos)
      bitpos  = 0
      wordpos = wordpos + 1
    end else good = 0

  ENDIF ELSE BEGIN

;   in current word

    if wordpos lt n_elements(data) then begin
      value = ISHFT (data(wordpos), -bitpos) AND bits(nbits)
      bitpos  = bitpos + nbits
    end else good = 0

  ENDELSE

  RETURN, value

END
