FUNCTION DI_readfits_flagmap, fn

;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Read a map of bit flags from a FITS file extension. The flags are:
;;
;; CALLING SEQUENCE:
;;	flags = DI_readfits_flagmap(fn)
;;
;; REQUIRED INPUTS:
;;	fn - filename of the FITS file with the flag map in it
;;
;; OUTPUTS:
;;	A two dimensional byte array of the flags at each pixel
;;
;; OPTIONAL INPUT KEYWORDS:
;;	none
;;
;; EXAMPLE:
;;      IDL> map = DI_readfits_flagmap(fn)
;;
;; PROCEDURES USED (i.e. called directly!):
;;    readFITS, SXPAR
;;
;; MODIFICATION HISTORY:
;;   2004-08-19  M. Desnoyer    Created
;;   2005-05-24  M. Desnoyer	Hey, it's my birthday. Yay! Anyway, I removed
;;				the space saving compression because it's very 
;;				complicated to get the headers right for PDS etc.
;;				so now, it's just a byte array the same size as
;;				the original image.
;;
;;-----------------------------------------------------------------------------

on_error, 2

;; Extract the flags from the FITS file
i=1
message, /reset
REPEAT BEGIN
	flag = readfits(fn, hdr, exten_no=i, /silent)
	IF !ERROR_STATE.CODE LT 0 THEN message, !ERROR_STATE.MSG, /ioerror
	i = i+1
ENDREP UNTIL strtrim(SXPAR(hdr, 'EXTNAME'),2) EQ 'FLAGS'

;; Make sure it's an 8-bit image
IF sxpar(hdr, 'BITPIX') NE 8 THEN message, 'Invalid flag map. It may be an old version' 

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;; 05/24/05 M. Desnoyer
;;ieee_to_host, comp
;;
;; Extract the flag values
;;flag = ishft(comp, -20)
;;
;; Extract the locations of the flags
;;loc = 'FFFFF'XL AND comp
;;
;; Create the flag map
;;out = uintarr(SXPAR(hdr, 'MAPAXIS1'), SXPAR(hdr, 'MAPAXIS2'))
;;out[loc] = flag
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


RETURN, byte(flag)

END