class _File(object):
    """
    Represents a FITS file on disk (or in some other file-like object).
    """

    def __init__(self, fileobj=None, mode=None, memmap=None, clobber=False):
        self.strict_memmap = bool(memmap)
        memmap = True if memmap is None else memmap

        if fileobj is None:
            self._file = None
            self.closed = False
            self.binary = True
            self.mode = mode
            self.memmap = memmap
            self.compression = None
            self.readonly = False
            self.writeonly = False
            self.simulateonly = True
            return
        else:
            self.simulateonly = False

        # Holds mmap instance for files that use mmap
        self._mmap = None

        if mode is None:
            if _is_random_access_file_backed(fileobj):
                fmode = fileobj_mode(fileobj)
                # If the mode is unsupported just leave it as None; we'll
                # catch this case below
                mode = FILE_MODES.get(fmode)
            else:
                mode = 'readonly'  # The default

        if mode not in PYFITS_MODES:
            raise ValueError("Mode '%s' not recognized" % mode)

        if (isinstance(fileobj, string_types) and
                mode not in ('ostream', 'append') and
                len(urllib.parse.urlparse(fileobj).scheme) > 1):
            # This is an URL.
            self.name, _ = urllib.request.urlretrieve(fileobj)
        else:
            self.name = fileobj_name(fileobj)

        self.closed = False
        self.binary = True
        self.mode = mode
        self.memmap = memmap

        # Underlying fileobj is a file-like object, but an actual file object
        self.file_like = False

        # More defaults to be adjusted below as necessary
        self.compression = None
        self.readonly = False
        self.writeonly = False

        # Initialize the internal self._file object
        if _is_random_access_file_backed(fileobj):
            self._open_fileobj(fileobj, mode, clobber)
        elif isinstance(fileobj, string_types):
            self._open_filename(fileobj, mode, clobber)
        else:
            self._open_filelike(fileobj, mode, clobber)

        self.fileobj_mode = fileobj_mode(self._file)

        if isinstance(fileobj, gzip.GzipFile):
            self.compression = 'gzip'
        elif isinstance(fileobj, zipfile.ZipFile):
            # Reading from zip files is supported but not writing (yet)
            self.compression = 'zip'
        elif isinstance(fileobj, bz2.BZ2File):
            self.compression = 'bzip2'

        if (mode in ('readonly', 'copyonwrite', 'denywrite') or
                (self.compression and mode == 'update')):
            self.readonly = True
        elif (mode == 'ostream' or
                (self.compression and mode == 'append')):
            self.writeonly = True

        # For 'ab+' mode, the pointer is at the end after the open in
        # Linux, but is at the beginning in Solaris.
        if (mode == 'ostream' or self.compression or
            not hasattr(self._file, 'seek')):
            # For output stream start with a truncated file.
            # For compressed files we can't really guess at the size
            self.size = 0
        else:
            pos = self._file.tell()
            self._file.seek(0, 2)
            self.size = self._file.tell()
            self._file.seek(pos)

        if self.memmap:
            if not isfile(self._file):
                self.memmap = False
            elif not self.readonly and not self._mmap_available:
                # Test mmap.flush--see
                # https://github.com/astropy/astropy/issues/968
                self.memmap = False

    def __repr__(self):
        return '<%s.%s %s>' % (self.__module__, self.__class__.__name__,
                               self._file)

    # Support the 'with' statement
    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def readable(self):
        if self.writeonly:
            return False
        return isreadable(self._file)

    def read(self, size=None):
        if not hasattr(self._file, 'read'):
            raise EOFError
        try:
            return self._file.read(size)
        except IOError:
            # On some versions of Python, it appears, GzipFile will raise an
            # IOError if you try to read past its end (as opposed to just
            # returning '')
            if self.compression == 'gzip':
                return ''
            raise

    def readarray(self, size=None, offset=0, dtype=np.uint8, shape=None):
        """
        Similar to file.read(), but returns the contents of the underlying
        file as a numpy array (or mmap'd array if memmap=True) rather than a
        string.

        Usually it's best not to use the `size` argument with this method, but
        it's provided for compatibility.
        """

        if not hasattr(self._file, 'read'):
            raise EOFError

        if not isinstance(dtype, np.dtype):
            dtype = np.dtype(dtype)

        if size and size % dtype.itemsize != 0:
            raise ValueError('size %d not a multiple of %s' % (size, dtype))

        if isinstance(shape, int):
            shape = (shape,)

        if not (size or shape):
            warnings.warn('No size or shape given to readarray(); assuming a '
                          'shape of (1,)')
            shape = (1,)

        if size and not shape:
            shape = (size // dtype.itemsize,)

        if size and shape:
            actualsize = np.prod(shape) * dtype.itemsize

            if actualsize < size:
                raise ValueError('size %d is too few bytes for a %s array of '
                                 '%s' % (size, shape, dtype))
            if actualsize < size:
                raise ValueError('size %d is too many bytes for a %s array of '
                                 '%s' % (size, shape, dtype))

        if self.memmap:
            if self._mmap is None:
                # Instantiate Memmap array of the file offset at 0
                # (so we can return slices of it to offset anywhere else into
                # the file)
                memmap = Memmap(self._file,
                                mode=MEMMAP_MODES[self.mode],
                                dtype=np.uint8)

                # Now we immediately discard the memmap array; we are really
                # just using it as a factory function to instantiate the mmap
                # object in a convenient way (may later do away with this
                # usage)
                self._mmap = memmap.base

                # Prevent dorking with self._memmap._mmap by memmap.__del__ in
                # Numpy 1.6 (see
                # https://github.com/numpy/numpy/commit/dcc355a0b179387eeba10c95baf2e1eb21d417c7)
                memmap._mmap = None
                del memmap

            return np.ndarray(shape=shape, dtype=dtype, offset=offset,
                              buffer=self._mmap)
        else:
            count = reduce(lambda x, y: x * y, shape)
            pos = self._file.tell()
            self._file.seek(offset)
            data = _array_from_file(self._file, dtype, count, '')
            data.shape = shape
            self._file.seek(pos)
            return data

    def writable(self):
        if self.readonly:
            return False
        return iswritable(self._file)

    def write(self, string):
        if hasattr(self._file, 'write'):
            _write_string(self._file, string)

    def writearray(self, array):
        """
        Similar to file.write(), but writes a numpy array instead of a string.

        Also like file.write(), a flush() or close() may be needed before
        the file on disk reflects the data written.
        """

        if hasattr(self._file, 'write'):
            _array_to_file(array, self._file)

    def flush(self):
        if hasattr(self._file, 'flush'):
            self._file.flush()

    def seek(self, offset, whence=0):
        # In newer Python versions, GzipFiles support the whence argument, but
        # I don't think it was added until 2.6; instead of assuming it's
        # present, we implement our own support for it here
        if not hasattr(self._file, 'seek'):
            return
        if isinstance(self._file, gzip.GzipFile):
            if whence:
                if whence == 1:
                    offset = self._file.offset + offset
                else:
                    raise ValueError('Seek from end not supported')
            self._file.seek(offset)
        else:
            self._file.seek(offset, whence)

        pos = self._file.tell()
        if self.size and pos > self.size:
            warnings.warn('File may have been truncated: actual file length '
                          '(%i) is smaller than the expected size (%i)' %
                          (self.size, pos))

    def tell(self):
        if not hasattr(self._file, 'tell'):
            raise EOFError
        return self._file.tell()

    def truncate(self, size=None):
        if hasattr(self._file, 'truncate'):
            self._file.truncate(size)

    def close(self):
        """
        Close the 'physical' FITS file.
        """

        if hasattr(self._file, 'close'):
            self._file.close()

        self._maybe_close_mmap()
        # Set self._memmap to None anyways since no new .data attributes can be
        # loaded after the file is closed
        self._mmap = None

        self.closed = True

    def _maybe_close_mmap(self, refcount_delta=0):
        """
        When mmap is in use these objects hold a reference to the mmap of the
        file (so there is only one, shared by all HDUs that reference this
        file).

        This will close the mmap if there are no arrays referencing it.
        """

        if (self._mmap is not None and
                sys.getrefcount(self._mmap) == 2 + refcount_delta):
            self._mmap.close()
            self._mmap = None

    def _overwrite_existing(self, clobber, fileobj, closed):
        """Overwrite an existing file if ``clobber`` is ``True``, otherwise
        raise an IOError.  The exact behavior of this method depends on the
        _File object state and is only meant for use within the ``_open_*``
        internal methods.
        """

        # The file will be overwritten...
        if ((self.file_like and
                (hasattr(fileobj, 'len') and fileobj.len > 0)) or
                (os.path.exists(self.name) and
                 os.path.getsize(self.name) != 0)):
            if clobber:
                warnings.warn("Overwriting existing file %r." % self.name)
                if self.file_like and hasattr(fileobj, 'truncate'):
                    fileobj.truncate(0)
                else:
                    if not closed:
                        fileobj.close()
                    os.remove(self.name)
            else:
                raise IOError("File %r already exists." % self.name)

    def _open_fileobj(self, fileobj, mode, clobber):
        """Open a FITS file from a file object or a GzipFile object."""

        closed = fileobj_closed(fileobj)
        fmode = fileobj_mode(fileobj) or PYFITS_MODES[mode]

        if mode == 'ostream':
            self._overwrite_existing(clobber, fileobj, closed)

        if not closed:
            # Although we have a specific mapping in PYFITS_MODES from our
            # custom file modes to raw file object modes, many of the latter
            # can be used appropriately for the former.  So determine whether
            # the modes match up appropriately
            if ((mode in ('readonly', 'denywrite', 'copyonwrite') and
                    not ('r' in fmode or '+' in fmode)) or
                    (mode == 'append' and fmode not in ('ab+', 'rb+')) or
                    (mode == 'ostream' and
                     not ('w' in fmode or 'a' in fmode or '+' in fmode)) or
                    (mode == 'update' and fmode not in ('rb+', 'wb+'))):
                raise ValueError(
                    "Mode argument '%s' does not match mode of the input "
                    "file (%s)." % (mode, fmode))
            self._file = fileobj
        elif isfile(fileobj):
            self._file = fileobj_open(self.name, PYFITS_MODES[mode])
        else:
            self._file = gzip.open(self.name, PYFITS_MODES[mode])

        if fmode == 'ab+':
            # Return to the beginning of the file--in Python 3 when opening in
            # append mode the file pointer is at the end of the file
            self._file.seek(0)

    def _open_filelike(self, fileobj, mode, clobber):
        """Open a FITS file from a file-like object, i.e. one that has
        read and/or write methods.
        """

        self.file_like = True
        self._file = fileobj

        if fileobj_closed(fileobj):
            raise IOError("Cannot read from/write to a closed file-like "
                          "object (%r)." % fileobj)

        if isinstance(fileobj, zipfile.ZipFile):
            self._open_zipfile(fileobj, mode)
            self._file.seek(0)
            # We can bypass any additional checks at this point since now
            # self._file points to the temp file extracted from the zip
            return

        # If there is not seek or tell methods then set the mode to
        # output streaming.
        if (not hasattr(self._file, 'seek') or
            not hasattr(self._file, 'tell')):
            self.mode = mode = 'ostream'

        if mode == 'ostream':
            self._overwrite_existing(clobber, fileobj, False)

        # Any "writeable" mode requires a write() method on the file object
        if (self.mode in ('update', 'append', 'ostream') and
            not hasattr(self._file, 'write')):
            raise IOError("File-like object does not have a 'write' "
                          "method, required for mode '%s'."
                          % self.mode)

        # Any mode except for 'ostream' requires readability
        if self.mode != 'ostream' and not hasattr(self._file, 'read'):
            raise IOError("File-like object does not have a 'read' "
                          "method, required for mode %r."
                          % self.mode)

    def _open_filename(self, filename, mode, clobber):
        """Open a FITS file from a filename string."""

        if mode == 'ostream':
            self._overwrite_existing(clobber, None, True)

        if os.path.exists(self.name):
            with fileobj_open(self.name, 'rb') as f:
                magic = f.read(4)
        else:
            magic = b('')

        ext = os.path.splitext(self.name)[1]

        if ext == '.gz' or magic.startswith(GZIP_MAGIC):
            # Handle gzip files
            self._file = gzip.open(self.name, PYFITS_MODES[mode])
            self.compression = 'gzip'
        elif ext == '.zip' or magic.startswith(PKZIP_MAGIC):
            # Handle zip files
            self._open_zipfile(self.name, mode)
        elif ext == '.bz2' or magic.startswith(BZIP2_MAGIC):
            # Handle bzip2 files
            if mode in ['update', 'append']:
                raise IOError("update and append modes are not supported "
                              "with bzip2 files")
            # bzip2 only supports 'w' and 'r' modes
            bzip2_mode = 'w' if mode == 'ostream' else 'r'
            self._file = bz2.BZ2File(self.name, bzip2_mode)
        else:
            self._file = fileobj_open(self.name, PYFITS_MODES[mode])

        # Make certain we're back at the beginning of the file
        # BZ2File does not support seek when the file is open for writing, but
        # when opening a file for write, bz2.BZ2File always truncates anyway.
        if isinstance(self._file, bz2.BZ2File) and mode == 'ostream':
            pass
        else:
            self._file.seek(0)

    def _open_zipfile(self, fileobj, mode):
        """Limited support for zipfile.ZipFile objects containing a single
        a file.  Allows reading only for now by extracting the file to a
        tempfile.
        """

        if mode in ('update', 'append'):
            raise IOError(
                  "Writing to zipped fits files is not currently "
                  "supported")

        if not isinstance(fileobj, zipfile.ZipFile):
            zfile = zipfile.ZipFile(fileobj)
            close = True
        else:
            zfile = fileobj
            close = False

        namelist = zfile.namelist()
        if len(namelist) != 1:
            raise IOError(
              "Zip files with multiple members are not supported.")
        self._file = tempfile.NamedTemporaryFile(suffix='.fits')
        self._file.write(zfile.read(namelist[0]))

        if close:
            zfile.close()
        self.compression = 'zip'

    @classproperty(lazy=True)
    def _mmap_available(cls):
        """Tests that mmap, and specifically mmap.flush works.  This may
        be the case on some uncommon platforms (see
        https://github.com/astropy/astropy/issues/968).

        If mmap.flush is found not to work, ``self.memmap = False`` is
        set and a warning is issued.
        """

        tmpfd, tmpname = tempfile.mkstemp()
        try:
            # Windows does not allow mappings on empty files
            os.write(tmpfd, encode_ascii(' '))
            os.fsync(tmpfd)
            try:
                mm = mmap.mmap(tmpfd, 1, access=mmap.ACCESS_WRITE)
            except mmap.error as exc:
                warnings.warn('Failed to create mmap: %s; mmap use will be '
                              'disabled' % exc)
                del exc
                return False
            try:
                mm.flush()
            except mmap.error:
                warnings.warn('mmap.flush is unavailable on this platform; '
                              'using mmap in writeable mode will be disabled')
                return False
            finally:
                mm.close()
        finally:
            os.close(tmpfd)
            os.remove(tmpname)

        return True class Header(object):
    """
    FITS header class.  This class exposes both a dict-like interface and a
    list-like interface to FITS headers.

    The header may be indexed by keyword and, like a dict, the associated value
    will be returned.  When the header contains cards with duplicate keywords,
    only the value of the first card with the given keyword will be returned.
    It is also possible to use a 2-tuple as the index in the form (keyword,
    n)--this returns the n-th value with that keyword, in the case where there
    are duplicate keywords.

    For example::

        >>> header['NAXIS']
        0
        >>> header[('FOO', 1)]  # Return the value of the second FOO keyword
        'foo'

    The header may also be indexed by card number::

        >>> header[0]  # Return the value of the first card in the header
        'T'

    Commentary keywords such as HISTORY and COMMENT are special cases: When
    indexing the Header object with either 'HISTORY' or 'COMMENT' a list of all
    the HISTORY/COMMENT values is returned::

        >>> header['HISTORY']
        This is the first history entry in this header.
        This is the second history entry in this header.
        ...

    See the PyFITS documentation for more details on working with headers.
    """

    def __init__(self, cards=[]):
        """
        Construct a `Header` from an iterable and/or text file.

        Parameters
        ----------
        cards : A list of `Card` objects, optional
            The cards to initialize the header with.
        """

        self.clear()

        if isinstance(cards, Header):
            cards = cards.cards

        for card in cards:
            self.append(card, end=True)

        self._modified = False

    def __len__(self):
        return len(self._cards)

    def __iter__(self):
        for card in self._cards:
            yield card.keyword

    def __contains__(self, keyword):
        if keyword in self._keyword_indices or keyword in self._rvkc_indices:
            # For the most common case (single, standard form keyword lookup)
            # this will work and is an O(1) check.  If it fails that doesn't
            # guarantee absence, just that we have to perform the full set of
            # checks in self._cardindex
            return True
        try:
            self._cardindex(keyword)
        except (KeyError, IndexError):
            return False
        return True

    def __getitem__(self, key):
        if isinstance(key, slice):
            return Header([copy.copy(c) for c in self._cards[key]])
        elif self._haswildcard(key):
            return Header([copy.copy(self._cards[idx])
                           for idx in self._wildcardmatch(key)])
        elif (isinstance(key, string_types) and
              key.upper() in Card._commentary_keywords):
            key = key.upper()
            # Special case for commentary cards
            return _HeaderCommentaryCards(self, key)
        if isinstance(key, tuple):
            keyword = key[0]
        else:
            keyword = key
        card = self._cards[self._cardindex(key)]
        if card.field_specifier is not None and keyword == card.rawkeyword:
            # This is RVKC; if only the top-level keyword was specified return
            # the raw value, not the parsed out float value
            return card.rawvalue
        return card.value

    def __setitem__(self, key, value):
        if self._set_slice(key, value, self):
            return

        if isinstance(value, tuple):
            if not (0 < len(value) <= 2):
                raise ValueError(
                    'A Header item may be set with either a scalar value, '
                    'a 1-tuple containing a scalar value, or a 2-tuple '
                    'containing a scalar value and comment string.')
            if len(value) == 1:
                value, comment = value[0], None
                if value is None:
                    value = ''
            elif len(value) == 2:
                value, comment = value
                if value is None:
                    value = ''
                if comment is None:
                    comment = ''
        else:
            comment = None

        card = None
        if isinstance(key, int):
            card = self._cards[key]
        elif isinstance(key, tuple):
            card = self._cards[self._cardindex(key)]
        if card:
            card.value = value
            if comment is not None:
                card.comment = comment
            if card._modified:
                self._modified = True
        else:
            # If we get an IndexError that should be raised; we don't allow
            # assignment to non-existing indices
            self._update((key, value, comment))

    def __delitem__(self, key):
        if isinstance(key, slice) or self._haswildcard(key):
            # This is very inefficient but it's not a commonly used feature.
            # If someone out there complains that they make heavy use of slice
            # deletions and it's too slow, well, we can worry about it then
            # [the solution is not too complicated--it would be wait 'til all
            # the cards are deleted before updating _keyword_indices rather
            # than updating it once for each card that gets deleted]
            if isinstance(key, slice):
                indices = range(*key.indices(len(self)))
                # If the slice step is backwards we want to reverse it, because
                # it will be reversed in a few lines...
                if key.step and key.step < 0:
                    indices = reversed(indices)
            else:
                indices = self._wildcardmatch(key)
            for idx in reversed(indices):
                del self[idx]
            return
        elif isinstance(key, string_types):
            # delete ALL cards with the same keyword name
            key = Card.normalize_keyword(key)
            indices = self._keyword_indices
            if key not in self._keyword_indices:
                indices = self._rvkc_indices

            if key not in indices:
                raise KeyError("Keyword '%s' not found." % key)

            for idx in reversed(indices[key]):
                # Have to copy the indices list since it will be modified below
                del self[idx]
            return

        idx = self._cardindex(key)
        card = self._cards[idx]
        keyword = card.keyword
        del self._cards[idx]
        indices = self._keyword_indices[keyword]
        indices.remove(idx)
        if not indices:
            del self._keyword_indices[keyword]

        # Also update RVKC indices if necessary :/
        if card.field_specifier is not None:
            indices = self._rvkc_indices[card.rawkeyword]
            indices.remove(idx)
            if not indices:
                del self._rvkc_indices[card.rawkeyword]


        # We also need to update all other indices
        self._updateindices(idx, increment=False)
        self._modified = True

    def __repr__(self):
        return self.tostring(sep='\n', endcard=False, padding=False)

    def __str__(self):
        return self.tostring()

    def __eq__(self, other):
        """
        Two Headers are equal only if they have the exact same string
        representation.
        """

        return str(self) == str(other)

    def __add__(self, other):
        temp = self.copy(strip=False)
        temp.extend(other)
        return temp

    def __iadd__(self, other):
        self.extend(other)
        return self

    @property
    def cards(self):
        """
        The underlying physical cards that make up this Header; it can be
        looked at, but it should not be modified directly.
        """

        return _CardAccessor(self)

    @property
    def comments(self):
        """
        View the comments associated with each keyword, if any.

        For example, to see the comment on the NAXIS keyword:

            >>> header.comments['NAXIS']
            number of data axes

        Comments can also be updated through this interface:

            >>> header.comments['NAXIS'] = 'Number of data axes'

        """

        return _HeaderComments(self)

    @property
    def _modified(self):
        """
        Whether or not the header has been modified; this is a property so that
        it can also check each card for modifications--cards may have been
        modified directly without the header containing it otherwise knowing.
        """

        modified_cards = any(c._modified for c in self._cards)
        if modified_cards:
            # If any cards were modified then by definition the header was
            # modified
            self.__dict__['_modified'] = True

        return self.__dict__['_modified']

    @_modified.setter
    def _modified(self, val):
        self.__dict__['_modified'] = val

    @classmethod
    def fromstring(cls, data, sep=''):
        """
        Creates an HDU header from a byte string containing the entire header
        data.

        Parameters
        ----------
        data : str
           String containing the entire header.

        sep : str, optional
            The string separating cards from each other, such as a newline.  By
            default there is no card separator (as is the case in a raw FITS
            file).

        Returns
        -------
        header
            A new `Header` instance.
        """

        cards = []

        # If the card separator contains characters that may validly appear in
        # a card, the only way to unambiguously distinguish between cards is to
        # require that they be Card.length long.  However, if the separator
        # contains non-valid characters (namely \n) the cards may be split
        # immediately at the separator
        require_full_cardlength = set(sep).issubset(VALID_HEADER_CHARS)

        # Split the header into individual cards
        idx = 0
        image = []

        while idx < len(data):
            if require_full_cardlength:
                end_idx = idx + Card.length
            else:
                try:
                    end_idx = data.index(sep, idx)
                except ValueError:
                    end_idx = len(data)

            next_image = data[idx:end_idx]
            idx = end_idx + len(sep)

            if image:
                if next_image[:8] == 'CONTINUE':
                    image.append(next_image)
                    continue
                cards.append(Card.fromstring(''.join(image)))

            if require_full_cardlength:
                if next_image == END_CARD:
                    image = []
                    break
            else:
                if next_image.split(sep)[0].rstrip() == 'END':
                    image = []
                    break

            image = [next_image]

        # Add the last image that was found before the end, if any
        if image:
            cards.append(Card.fromstring(''.join(image)))

        return cls(cards)

    @classmethod
    def fromfile(cls, fileobj, sep='', endcard=True, padding=True):
        """
        Similar to :meth:`Header.fromstring`, but reads the header string from
        a given file-like object or filename.

        Parameters
        ----------
        fileobj : str, file-like
            A filename or an open file-like object from which a FITS header is
            to be read.  For open file handles the file pointer must be at the
            beginning of the header.

        sep : str, optional
            The string separating cards from each other, such as a newline.  By
            default there is no card separator (as is the case in a raw FITS
            file).

        endcard : bool, optional
            If True (the default) the header must end with an END card in order
            to be considered valid.  If an END card is not found an
            `~.exceptions.IOError` is raised.

        padding : bool, optional
            If True (the default) the header will be required to be padded out
            to a multiple of 2880, the FITS header block size.  Otherwise any
            padding, or lack thereof, is ignored.

        Returns
        -------
        header
            A new `Header` instance.
        """

        close_file = False
        if isinstance(fileobj, string_types):
            # Open in text mode by default to support newline handling; if a
            # binary-mode file object is passed in, the user is on their own
            # with respect to newline handling
            fileobj = open(fileobj, 'r')
            close_file = True

        try:
            is_binary = fileobj_is_binary(fileobj)

            def block_iter(nbytes):
                while True:
                    data = fileobj.read(nbytes)

                    if data:
                        yield data
                    else:
                        break

            return cls._from_blocks(block_iter, is_binary, sep, endcard,
                                    padding)[1]
        finally:
            if close_file:
                fileobj.close()

    @classmethod
    def _from_blocks(cls, block_iter, is_binary, sep, endcard, padding):
        """
        The meat of `Header.fromfile`; in a separate method so that
        `Header.fromfile` itself is just responsible for wrapping file
        handling.  Also used by `_BaseHDU.fromstring`.

        ``block_iter`` should be a callable which, given a block size n
        (typically 2880 bytes as used by the FITS standard) returns an iterator
        of byte strings of that block size.

        ``is_binary`` specifies whether the returned blocks are bytes or text

        Returns both the entire header *string*, and the `Header` object
        returned by Header.fromstring on that string.
        """

        actual_block_size = _block_size(sep)
        clen = Card.length + len(sep)

        blocks = block_iter(actual_block_size)

        # Read the first header block.
        try:
            block = next(blocks)
        except StopIteration:
            raise EOFError()

        if not is_binary:
            # TODO: There needs to be error handling at *this* level for
            # non-ASCII characters; maybe at this stage decoding latin-1 might
            # be safer
            block = encode_ascii(block)

        read_blocks = []
        is_eof = False
        end_found = False

        # continue reading header blocks until END card or EOF is reached
        while True:
            # find the END card
            end_found, block = cls._find_end_card(block, clen)

            read_blocks.append(decode_ascii(block))

            if end_found:
                break

            try:
                block = next(blocks)
            except StopIteration:
                is_eof = True
                break

            if not block:
                is_eof = True
                break

            if not is_binary:
                block = encode_ascii(block)

        if not end_found and is_eof and endcard:
            # TODO: Pass this error to validation framework as an ERROR,
            # rather than raising an exception
            raise IOError('Header missing END card.')

        header_str = ''.join(read_blocks)

        # Strip any zero-padding (see ticket #106)
        if header_str and header_str[-1] == '\0':
            if is_eof and header_str.strip('\0') == '':
                # TODO: Pass this warning to validation framework
                warnings.warn(
                    'Unexpected extra padding at the end of the file.  This '
                    'padding may not be preserved when saving changes.')
                raise EOFError()
            else:
                # Replace the illegal null bytes with spaces as required by
                # the FITS standard, and issue a nasty warning
                # TODO: Pass this warning to validation framework
                warnings.warn(
                    'Header block contains null bytes instead of spaces for '
                    'padding, and is not FITS-compliant. Nulls may be '
                    'replaced with spaces upon writing.')
                header_str.replace('\0', ' ')

        if padding and (len(header_str) % actual_block_size) != 0:
            # This error message ignores the length of the separator for
            # now, but maybe it shouldn't?
            actual_len = len(header_str) - actual_block_size + BLOCK_SIZE
            # TODO: Pass this error to validation framework
            raise ValueError('Header size is not multiple of %d: %d'
                             % (BLOCK_SIZE, actual_len))

        return header_str, cls.fromstring(header_str, sep=sep)

    @classmethod
    def _find_end_card(cls, block, card_len):
        """
        Utility method to search a header block for the END card and handle
        invalid END cards.

        This method can also returned a modified copy of the input header block
        in case an invalid end card needs to be sanitized.
        """

        for mo in HEADER_END_RE.finditer(block):
            # Ensure the END card was found, and it started on the
            # boundary of a new card (see ticket #142)
            if mo.start() % card_len != 0:
                continue

            # This must be the last header block, otherwise the
            # file is malformatted
            if mo.group('invalid'):
                offset = mo.start()
                trailing = block[offset + 3:offset + card_len - 3].rstrip()
                if trailing:
                    trailing = repr(trailing).lstrip('ub')
                    # TODO: Pass this warning up to the validation framework
                    warnings.warn(
                        'Unexpected bytes trailing END keyword: %s; these '
                        'bytes will be replaced with spaces on write.' %
                        trailing)
                else:
                    # TODO: Pass this warning up to the validation framework
                    warnings.warn(
                        'Missing padding to end of the FITS block after the '
                        'END keyword; additional spaces will be appended to '
                        'the file upon writing to pad out to %d bytes.' %
                        BLOCK_SIZE)

                # Sanitize out invalid END card now that the appropriate
                # warnings have been issued
                block = (block[:offset] + encode_ascii(END_CARD) +
                         block[offset + len(END_CARD):])

            return True, block

        return False, block

    def tostring(self, sep='', endcard=True, padding=True):
        r"""
        Returns a string representation of the header.

        By default this uses no separator between cards, adds the END card, and
        pads the string with spaces to the next multiple of 2880 bytes.  That
        is, it returns the header exactly as it would appear in a FITS file.

        Parameters
        ----------
        sep : str, optional
            The character or string with which to separate cards.  By default
            there is no separator, but one could use ``'\\n'``, for example, to
            separate each card with a new line

        endcard : bool, optional
            If True (default) adds the END card to the end of the header
            string

        padding : bool, optional
            If True (default) pads the string with spaces out to the next
            multiple of 2880 characters

        Returns
        -------
        s : string
            A string representing a FITS header.
        """

        lines = []
        for card in self._cards:
            s = str(card)
            # Cards with CONTINUE cards may be longer than 80 chars; so break
            # them into multiple lines
            while s:
                lines.append(s[:Card.length])
                s = s[Card.length:]

        s = sep.join(lines)
        if endcard:
            s += sep + _pad('END')
        if padding:
            s += ' ' * _pad_length(len(s))
        return s

    def tofile(self, fileobj, sep='', endcard=True, padding=True,
               clobber=False):
        r"""
        Writes the header to file or file-like object.

        By default this writes the header exactly as it would be written to a
        FITS file, with the END card included and padding to the next multiple
        of 2880 bytes.  However, aspects of this may be controlled.

        Parameters
        ----------
        fileobj : str, file, optional
            Either the pathname of a file, or an open file handle or file-like
            object

        sep : str, optional
            The character or string with which to separate cards.  By default
            there is no separator, but one could use ``'\\n'``, for example, to
            separate each card with a new line

        endcard : bool, optional
            If `True` (default) adds the END card to the end of the header
            string

        padding : bool, optional
            If `True` (default) pads the string with spaces out to the next
            multiple of 2880 characters

        clobber : bool, optional
            If `True`, overwrites the output file if it already exists
        """

        close_file = fileobj_closed(fileobj)

        if not isinstance(fileobj, _File):
            fileobj = _File(fileobj, mode='ostream', clobber=clobber)

        try:
            blocks = self.tostring(sep=sep, endcard=endcard, padding=padding)
            actual_block_size = _block_size(sep)
            if padding and len(blocks) % actual_block_size != 0:
                raise IOError('Header size (%d) is not a multiple of block '
                              'size (%d).' %
                              (len(blocks) - actual_block_size + BLOCK_SIZE,
                               BLOCK_SIZE))

            if not fileobj.simulateonly:
                fileobj.flush()
                try:
                    offset = fileobj.tell()
                except (AttributeError, IOError):
                    offset = 0
                fileobj.write(blocks.encode('ascii'))
                fileobj.flush()
        finally:
            if close_file:
                fileobj.close()

    @classmethod
    def fromtextfile(cls, fileobj, endcard=False):
        """
        Equivalent to::

            >>> Header.fromfile(fileobj, sep='\\n', endcard=False,
            ...                 padding=False)
        """

        return cls.fromfile(fileobj, sep='\n', endcard=endcard, padding=False)

    def totextfile(self, fileobj, endcard=False, clobber=False):
        """
        Equivalent to::

            >>> Header.tofile(fileobj, sep='\\n', endcard=False,
            ...               padding=False, clobber=clobber)
        """

        self.tofile(fileobj, sep='\n', endcard=endcard, padding=False,
                    clobber=clobber)

    def clear(self):
        """
        Remove all cards from the header.
        """

        self._cards = []
        self._keyword_indices = defaultdict(list)
        self._rvkc_indices = defaultdict(list)

    def copy(self, strip=False):
        """
        Make a copy of the :class:`Header`.

        Parameters
        ----------
        strip : bool, optional
           If `True`, strip any headers that are specific to one of the
           standard HDU types, so that this header can be used in a different
           HDU.

        Returns
        -------
        header
            A new :class:`Header` instance.
        """

        tmp = Header([copy.copy(card) for card in self._cards])
        if strip:
            tmp._strip()
        return tmp

    @classmethod
    def fromkeys(cls, iterable, value=None):
        """
        Similar to :meth:`dict.fromkeys`--creates a new `Header` from an
        iterable of keywords and an optional default value.

        This method is not likely to be particularly useful for creating real
        world FITS headers, but it is useful for testing.

        Parameters
        ----------
        iterable
            Any iterable that returns strings representing FITS keywords.

        value : optional
            A default value to assign to each keyword; must be a valid type for
            FITS keywords.

        Returns
        -------
        header
            A new `Header` instance.
        """

        d = cls()
        if not isinstance(value, tuple):
            value = (value,)
        for key in iterable:
            d.append((key,) + value)
        return d

    def get(self, key, default=None):
        """
        Similar to :meth:`dict.get`--returns the value associated with keyword
        in the header, or a default value if the keyword is not found.

        Parameters
        ----------
        key : str
            A keyword that may or may not be in the header.

        default : optional
            A default value to return if the keyword is not found in the
            header.

        Returns
        -------
        value
            The value associated with the given keyword, or the default value
            if the keyword is not in the header.
        """

        try:
            return self[key]
        except (KeyError, IndexError):
            return default

    def set(self, keyword, value=None, comment=None, before=None, after=None,
            savecomment=False):
        """
        Set the value and/or comment and/or position of a specified keyword.

        If the keyword does not already exist in the header, a new keyword is
        created in the specified position, or appended to the end of the header
        if no position is specified.

        This method is similar to :meth:`Header.update` prior to PyFITS 3.1.

        .. note::
            It should be noted that ``header.set(keyword, value)`` and
            ``header.set(keyword, value, comment)`` are equivalent to
            ``header[keyword] = value`` and
            ``header[keyword] = (value, comment)`` respectively.

            New keywords can also be inserted relative to existing keywords
            using, for example::

                >>> header.insert('NAXIS1', ('NAXIS', 2, 'Number of axes'))

            to insert before an existing keyword, or::

                >>> header.insert('NAXIS', ('NAXIS1', 4096), after=True)

            to insert after an existing keyword.

            The only advantage of using :meth:`Header.set` is that it
            easily replaces the old usage of :meth:`Header.update` both
            conceptually and in terms of function signature.

        Parameters
        ----------
        keyword : str
            A header keyword

        value : str, optional
            The value to set for the given keyword; if None the existing value
            is kept, but '' may be used to set a blank value

        comment : str, optional
            The comment to set for the given keyword; if None the existing
            comment is kept, but ``''`` may be used to set a blank comment

        before : str, int, optional
            Name of the keyword, or index of the `Card` before which this card
            should be located in the header.  The argument ``before`` takes
            precedence over ``after`` if both specified.

        after : str, int, optional
            Name of the keyword, or index of the `Card` after which this card
            should be located in the header.

        savecomment : bool, optional
            This option is provided primarily for compatibilty with the old
            `Header.update` (which worked differently before PyFITS v3.4).
            If `True`, this causes the existing comment for the specified
            keyword (if it exists) to be preserved even if a different comment
            is provided via the ``comment`` argument.  In other words, it
            causes the ``comment`` argument to be ignored (but *only* if there
            is already a comment).
        """

        # Create a temporary card that looks like the one being set; if the
        # temporary card turns out to be a RVKC this will make it easier to
        # deal with the idiosyncrasies thereof
        # Don't try to make a temporary card though if they keyword looks like
        # it might be a HIERARCH card or is otherwise invalid--this step is
        # only for validating RVKCs.
        if (len(keyword) <= KEYWORD_LENGTH and
            Card._keywd_FSC_RE.match(keyword) and
                keyword not in self._keyword_indices):
            new_card = Card(keyword, value, comment)
            new_keyword = new_card.keyword
        else:
            new_keyword = keyword

        if (new_keyword not in Card._commentary_keywords and
                new_keyword in self):
            if comment is None or savecomment:
                comment = self.comments[keyword]
            if value is None:
                value = self[keyword]

            self[keyword] = (value, comment)

            if before is not None or after is not None:
                card = self._cards[self._cardindex(keyword)]
                self._relativeinsert(card, before=before, after=after,
                                     replace=True)
        elif before is not None or after is not None:
            self._relativeinsert((keyword, value, comment), before=before,
                                 after=after)
        else:
            self[keyword] = (value, comment)

    def items(self):
        """Like :meth:`dict.items`."""

        return list(self.iteritems())

    def iteritems(self):
        """Like :meth:`dict.iteritems`."""

        for card in self._cards:
            yield (card.keyword, card.value)

    def iterkeys(self):
        """
        Like :meth:`dict.iterkeys`--iterating directly over the `Header`
        instance has the same behavior.
        """

        return self.__iter__()

    def itervalues(self):
        """Like :meth:`dict.itervalues`."""

        for _, v in iteritems(self):
            yield v

    def keys(self):
        """
        Return a list of keywords in the header in the order they
        appear--like :meth:`dict.keys` but ordered.
        """

        return [keyword for keyword in self]

    def pop(self, *args):
        """
        Works like :meth:`list.pop` if no arguments or an index argument are
        supplied; otherwise works like :meth:`dict.pop`.
        """

        if len(args) > 2:
            raise TypeError('Header.pop expected at most 2 arguments, got '
                            '%d' % len(args))

        if len(args) == 0:
            key = -1
        else:
            key = args[0]

        try:
            value = self[key]
        except (KeyError, IndexError):
            if len(args) == 2:
                return args[1]
            raise

        del self[key]
        return value

    def popitem(self):
        """Similar to :meth:`dict.popitem`."""

        try:
            k, v = next(iteritems(self))
        except StopIteration:
            raise KeyError('Header is empty')
        del self[k]
        return k, v

    def setdefault(self, key, default=None):
        """Similar to :meth:`dict.setdefault`."""

        try:
            return self[key]
        except (KeyError, IndexError):
            self[key] = default
        return default

    def update(self, *args, **kwargs):
        """
        Update the Header with new keyword values, updating the values of
        existing keywords and appending new keywords otherwise; similar to
        `dict.update`.

        `update` accepts either a dict-like object or an iterable.  In the
        former case the keys must be header keywords and the values may be
        either scalar values or (value, comment) tuples.  In the case of an
        iterable the items must be (keyword, value) tuples or (keyword, value,
        comment) tuples.

        Arbitrary arguments are also accepted, in which case the update() is
        called again with the kwargs dict as its only argument.  That is,

        ::

            >>> header.update(NAXIS1=100, NAXIS2=100)

        is equivalent to::

            >>> header.update({'NAXIS1': 100, 'NAXIS2': 100})
        """

        if args:
            other = args[0]
        else:
            other = None

        def update_from_dict(k, v):
            if not isinstance(v, tuple):
                card = Card(k, v)
            elif 0 < len(v) <= 2:
                card = Card(*((k,) + v))
            else:
                raise ValueError(
                    'Header update value for key %r is invalid; the value '
                    'must be either a scalar, a 1-tuple containing the '
                    'scalar value, or a 2-tuple containing the value and a '
                    'comment string.' % k)
            self._update(card)

        if other is None:
            pass
        elif hasattr(other, 'iteritems'):
            for k, v in other.iteritems():
                update_from_dict(k, v)
        elif hasattr(other, 'keys'):
            for k in other.keys():
                update_from_dict(k, other[k])
        else:
            for idx, card in enumerate(other):
                if isinstance(card, Card):
                    self._update(card)
                elif isinstance(card, tuple) and (1 < len(card) <= 3):
                    self._update(Card(*card))
                else:
                    raise ValueError(
                        'Header update sequence item #%d is invalid; the '
                        'item must either be a 2-tuple containing a keyword '
                        'and value, or a 3-tuple containing a keyword, '
                        'value, and comment string.' % idx)
        if kwargs:
            self.update(kwargs)

    def values(self):
        """Returns a list of the values of all cards in the header."""

        return [v for _, v in iteritems(self)]

    def append(self, card=None, useblanks=True, bottom=False, end=False):
        """
        Appends a new keyword+value card to the end of the Header, similar
        to `list.append`.

        By default if the last cards in the Header have commentary keywords,
        this will append the new keyword before the commentary (unless the new
        keyword is also commentary).

        Also differs from `list.append` in that it can be called with no
        arguments: In this case a blank card is appended to the end of the
        Header.  In the case all the keyword arguments are ignored.

        Parameters
        ----------
        card : str, tuple
            A keyword or a (keyword, value, [comment]) tuple representing a
            single header card; the comment is optional in which case a
            2-tuple may be used

        useblanks : bool, optional
            If there are blank cards at the end of the Header, replace the
            first blank card so that the total number of cards in the Header
            does not increase.  Otherwise preserve the number of blank cards.

        bottom : bool, optional
            If True, instead of appending after the last non-commentary card,
            append after the last non-blank card.

        end : bool, optional
            If True, ignore the useblanks and bottom options, and append at the
            very end of the Header.

        """

        if isinstance(card, string_types):
            card = Card(card)
        elif isinstance(card, tuple):
            card = Card(*card)
        elif card is None:
            card = Card()
        elif not isinstance(card, Card):
            raise ValueError(
                'The value appended to a Header must be either a keyword or '
                '(keyword, value, [comment]) tuple; got: %r' % card)

        if not end and card.is_blank:
            # Blank cards should always just be appended to the end
            end = True

        if end:
            self._cards.append(card)
            idx = len(self._cards) - 1
        else:
            idx = len(self._cards) - 1
            while idx >= 0 and self._cards[idx].is_blank:
                idx -= 1

            if not bottom and card.keyword not in Card._commentary_keywords:
                while (idx >= 0 and
                       self._cards[idx].keyword in Card._commentary_keywords):
                    idx -= 1

            idx += 1
            self._cards.insert(idx, card)
            self._updateindices(idx)

        keyword = Card.normalize_keyword(card.keyword)
        self._keyword_indices[keyword].append(idx)
        if card.field_specifier is not None:
            self._rvkc_indices[card.rawkeyword].append(idx)

        if not end:
            # If the appended card was a commentary card, and it was appended
            # before existing cards with the same keyword, the indices for
            # cards with that keyword may have changed
            if not bottom and card.keyword in Card._commentary_keywords:
                self._keyword_indices[keyword].sort()

            # Finally, if useblanks, delete a blank cards from the end
            if useblanks and self._countblanks():
                # Don't do this unless there is at least one blanks at the end
                # of the header; we need to convert the card to its string
                # image to see how long it is.  In the vast majority of cases
                # this will just be 80 (Card.length) but it may be longer for
                # CONTINUE cards
                self._useblanks(len(str(card)) // Card.length)

        self._modified = True

    def extend(self, cards, strip=True, unique=False, update=False,
               update_first=False, useblanks=True, bottom=False, end=False):
        """
        Appends multiple keyword+value cards to the end of the header, similar
        to `list.extend`.

        Parameters
        ----------
        cards : iterable
            An iterable of (keyword, value, [comment]) tuples; see
            `Header.append`.

        strip : bool, optional
            Remove any keywords that have meaning only to specific types of
            HDUs, so that only more general keywords are added from extension
            Header or Card list (default: `True`).

        unique : bool, optional
            If `True`, ensures that no duplicate keywords are appended;
            keywords already in this header are simply discarded.  The
            exception is commentary keywords (COMMENT, HISTORY, etc.): they are
            only treated as duplicates if their values match.

        update : bool, optional
            If `True`, update the current header with the values and comments
            from duplicate keywords in the input header.  This supercedes the
            ``unique`` argument.  Commentary keywords are treated the same as
            if ``unique=True``.

        update_first : bool, optional
            If the first keyword in the header is 'SIMPLE', and the first
            keyword in the input header is 'XTENSION', the 'SIMPLE' keyword is
            replaced by the 'XTENSION' keyword.  Likewise if the first keyword
            in the header is 'XTENSION' and the first keyword in the input
            header is 'SIMPLE', the 'XTENSION' keyword is replaced by the
            'SIMPLE' keyword.  This behavior is otherwise dumb as to whether or
            not the resulting header is a valid primary or extension header.
            This is mostly provided to support backwards compatibility with the
            old :meth:`Header.fromTxtFile` method, and only applies if
            ``update=True``.

        useblanks, bottom, end : bool, optional
            These arguments are passed to :meth:`Header.append` while appending
            new cards to the header.
        """

        temp = Header(cards)
        if strip:
            temp._strip()

        if len(self):
            first = self.cards[0].keyword
        else:
            first = None

        # We don't immediately modify the header, because first we need to sift
        # out any duplicates in the new header prior to adding them to the
        # existing header, but while *allowing* duplicates from the header
        # being extended from (see ticket #156)
        extend_cards = []

        for idx, card in enumerate(temp.cards):
            keyword = card.keyword
            if keyword not in Card._commentary_keywords:
                if unique and not update and keyword in self:
                    continue
                elif update:
                    if idx == 0 and update_first:
                        # Dumbly update the first keyword to either SIMPLE or
                        # XTENSION as the case may be, as was in the case in
                        # Header.fromTxtFile
                        if ((keyword == 'SIMPLE' and first == 'XTENSION') or
                                (keyword == 'XTENSION' and first == 'SIMPLE')):
                            del self[0]
                            self.insert(0, card)
                        else:
                            self[keyword] = (card.value, card.comment)
                    elif keyword in self:
                        self[keyword] = (card.value, card.comment)
                    else:
                        extend_cards.append(card)
                else:
                    extend_cards.append(card)
            else:
                if (unique or update) and keyword in self:
                    if card.is_blank:
                        extend_cards.append(card)
                        continue

                    for value in self[keyword]:
                        if value == card.value:
                            break
                    else:
                        extend_cards.append(card)
                else:
                    extend_cards.append(card)

        for card in extend_cards:
            self.append(card, useblanks=useblanks, bottom=bottom, end=end)

    def count(self, keyword):
        """
        Returns the count of the given keyword in the header, similar to
        `list.count` if the Header object is treated as a list of keywords.

        Parameters
        ----------
        keyword : str
            The keyword to count instances of in the header

        """

        keyword = Card.normalize_keyword(keyword)

        # We have to look before we leap, since otherwise _keyword_indices,
        # being a defaultdict, will create an entry for the nonexistent keyword
        if keyword not in self._keyword_indices:
            raise KeyError("Keyword %r not found." % keyword)

        return len(self._keyword_indices[keyword])

    def index(self, keyword, start=None, stop=None):
        """
        Returns the index if the first instance of the given keyword in the
        header, similar to `list.index` if the Header object is treated as a
        list of keywords.

        Parameters
        ----------
        keyword : str
            The keyword to look up in the list of all keywords in the header

        start : int, optional
            The lower bound for the index

        stop : int, optional
            The upper bound for the index

        """

        if start is None:
            start = 0

        if stop is None:
            stop = len(self._cards)

        if stop < start:
            step = -1
        else:
            step = 1

        norm_keyword = Card.normalize_keyword(keyword)

        for idx in range(start, stop, step):
            if self._cards[idx].keyword.upper() == norm_keyword:
                return idx
        else:
            raise ValueError('The keyword %r is not in the header.' % keyword)

    def insert(self, key, card, useblanks=True, after=False):
        """
        Inserts a new keyword+value card into the Header at a given location,
        similar to `list.insert`.

        Parameters
        ----------
        key : int, str, or tuple
            The index into the list of header keywords before which the
            new keyword should be inserted, or the name of a keyword before
            which the new keyword should be inserted.  Can also accept a
            (keyword, index) tuple for inserting around duplicate keywords.

        card : str, tuple
            A keyword or a (keyword, value, [comment]) tuple; see
            `Header.append`

        useblanks : bool, optional
            If there are blank cards at the end of the Header, replace the
            first blank card so that the total number of cards in the Header
            does not increase.  Otherwise preserve the number of blank cards.

        after : bool, optional
            If set to `True`, insert *after* the specified index or keyword,
            rather than before it.  Defaults to `False`.
        """

        if not isinstance(key, int):
            # Don't pass through ints to _cardindex because it will not take
            # kindly to indices outside the existing number of cards in the
            # header, which insert needs to be able to support (for example
            # when inserting into empty headers)
            idx = self._cardindex(key)
        else:
            idx = key

        if after:
            if idx == -1:
                idx = len(self._cards)
            else:
                idx += 1

        if idx >= len(self._cards):
            # This is just an append (Though it must be an append absolutely to
            # the bottom, ignoring blanks, etc.--the point of the insert method
            # is that you get exactly what you asked for with no surprises)
            self.append(card, end=True)
            return

        if isinstance(card, string_types):
            card = Card(card)
        elif isinstance(card, tuple):
            card = Card(*card)
        elif not isinstance(card, Card):
            raise ValueError(
                'The value inserted into a Header must be either a keyword or '
                '(keyword, value, [comment]) tuple; got: %r' % card)

        self._cards.insert(idx, card)

        keyword = card.keyword

        # If idx was < 0, determine the actual index according to the rules
        # used by list.insert()
        if idx < 0:
            idx += len(self._cards) - 1
            if idx < 0:
                idx = 0

        # All the keyword indices above the insertion point must be updated
        self._updateindices(idx)

        self._keyword_indices[keyword].append(idx)
        count = len(self._keyword_indices[keyword])
        if count > 1:
            # There were already keywords with this same name
            if keyword not in Card._commentary_keywords:
                warnings.warn(
                    'A %r keyword already exists in this header.  Inserting '
                    'duplicate keyword.' % keyword)
            self._keyword_indices[keyword].sort()

        if card.field_specifier is not None:
            # Update the index of RVKC as well
            rvkc_indices = self._rvkc_indices[card.rawkeyword]
            rvkc_indices.append(idx)
            rvkc_indices.sort()

        if useblanks:
            self._useblanks(len(str(card)) // Card.length)

        self._modified = True

    def remove(self, keyword):
        """
        Removes the first instance of the given keyword from the header similar
        to `list.remove` if the Header object is treated as a list of keywords.

        Parameters
        ----------
        keyword : str
            The keyword of which to remove the first instance in the header

        """

        del self[self.index(keyword)]

    def rename_keyword(self, oldkeyword, newkeyword, force=False):
        """
        Rename a card's keyword in the header.

        Parameters
        ----------
        oldkeyword : str or int
            Old keyword or card index

        newkeyword : str
            New keyword

        force : bool, optional
            When `True`, if the new keyword already exists in the header, force
            the creation of a duplicate keyword. Otherwise a
            `~.exceptions.ValueError` is raised.
        """

        oldkeyword = Card.normalize_keyword(oldkeyword)
        newkeyword = Card.normalize_keyword(newkeyword)

        if newkeyword == 'CONTINUE':
            raise ValueError('Can not rename to CONTINUE')

        if (newkeyword in Card._commentary_keywords or
                oldkeyword in Card._commentary_keywords):
            if not (newkeyword in Card._commentary_keywords and
                    oldkeyword in Card._commentary_keywords):
                raise ValueError('Regular and commentary keys can not be '
                                 'renamed to each other.')
        elif not force and newkeyword in self:
            raise ValueError('Intended keyword %s already exists in header.'
                             % newkeyword)

        idx = self.index(oldkeyword)
        card = self.cards[idx]
        del self[idx]
        self.insert(idx, (newkeyword, card.value, card.comment))

    def add_history(self, value, before=None, after=None):
        """
        Add a ``HISTORY`` card.

        Parameters
        ----------
        value : str
            History text to be added.

        before : str or int, optional
            Same as in `Header.update`

        after : str or int, optional
            Same as in `Header.update`
        """

        self._add_commentary('HISTORY', value, before=before, after=after)

    def add_comment(self, value, before=None, after=None):
        """
        Add a ``COMMENT`` card.

        Parameters
        ----------
        value : str
            Text to be added.

        before : str or int, optional
            Same as in `Header.update`

        after : str or int, optional
            Same as in `Header.update`
        """

        self._add_commentary('COMMENT', value, before=before, after=after)

    def add_blank(self, value='', before=None, after=None):
        """
        Add a blank card.

        Parameters
        ----------
        value : str, optional
            Text to be added.

        before : str or int, optional
            Same as in `Header.update`

        after : str or int, optional
            Same as in `Header.update`
        """

        self._add_commentary('', value, before=before, after=after)

    def _update(self, card):
        """
        The real update code.  If keyword already exists, its value and/or
        comment will be updated.  Otherwise a new card will be appended.

        This will not create a duplicate keyword except in the case of
        commentary cards.  The only other way to force creation of a duplicate
        is to use the insert(), append(), or extend() methods.
        """

        keyword, value, comment = card

        # Lookups for existing/known keywords are case-insensitive
        keyword = keyword.upper()
        if keyword.startswith('HIERARCH '):
            keyword = keyword[9:]

        if (keyword not in Card._commentary_keywords and
                keyword in self._keyword_indices):
            # Easy; just update the value/comment
            idx = self._keyword_indices[keyword][0]
            existing_card = self._cards[idx]
            existing_card.value = value
            if comment is not None:
                # '' should be used to explicitly blank a comment
                existing_card.comment = comment
            if existing_card._modified:
                self._modified = True
        elif keyword in Card._commentary_keywords:
            cards = self._splitcommentary(keyword, value)
            if keyword in self._keyword_indices:
                # Append after the last keyword of the same type
                idx = self.index(keyword, start=len(self) - 1, stop=-1)
                isblank = not (keyword or value or comment)
                for c in reversed(cards):
                    self.insert(idx + 1, c, useblanks=(not isblank))
            else:
                for c in cards:
                    self.append(c, bottom=True)
        else:
            # A new keyword! self.append() will handle updating _modified
            self.append(card)

    def _cardindex(self, key):
        """Returns an index into the ._cards list given a valid lookup key."""

        # This used to just set key = (key, 0) and then go on to act as if the
        # user passed in a tuple, but it's much more common to just be given a
        # string as the key, so optimize more for that case
        if isinstance(key, string_types):
            keyword = key
            n = 0
        elif isinstance(key, int):
            # If < 0, determine the actual index
            if key < 0:
                key += len(self._cards)
            if key < 0 or key >= len(self._cards):
                raise IndexError('Header index out of range.')
            return key
        elif isinstance(key, slice):
            return key
        elif isinstance(key, tuple):
            if (len(key) != 2 or not isinstance(key[0], string_types) or
                    not isinstance(key[1], int)):
                raise ValueError(
                    'Tuple indices must be 2-tuples consisting of a '
                    'keyword string and an integer index.')
            keyword, n = key
        else:
            raise ValueError(
                'Header indices must be either a string, a 2-tuple, or '
                'an integer.')

        keyword = Card.normalize_keyword(keyword)
        # Returns the index into _cards for the n-th card with the given
        # keyword (where n is 0-based)
        indices = self._keyword_indices.get(keyword, None)

        if keyword and not indices:
            if len(keyword) > KEYWORD_LENGTH or '.' in keyword:
                raise KeyError("Keyword %r not found." % keyword)
            else:
                # Maybe it's a RVKC?
                indices = self._rvkc_indices.get(keyword, None)

        if not indices:
            raise KeyError("Keyword %r not found." % keyword)

        try:
            return indices[n]
        except IndexError:
            raise IndexError('There are only %d %r cards in the header.' %
                             (len(indices), keyword))

    def _keyword_from_index(self, idx):
        """
        Given an integer index, return the (keyword, repeat) tuple that index
        refers to.  For most keywords the repeat will always be zero, but it
        may be greater than zero for keywords that are duplicated (especially
        commentary keywords).

        In a sense this is the inverse of self.index, except that it also
        supports duplicates.
        """

        if idx < 0:
            idx += len(self._cards) - 1

        keyword = self._cards[idx].keyword
        repeat = self._keyword_indices[keyword].index(idx)
        return keyword, repeat

    def _relativeinsert(self, card, before=None, after=None, replace=False):
        """
        Inserts a new card before or after an existing card; used to
        implement support for the legacy before/after keyword arguments to
        Header.update().

        If replace=True, move an existing card with the same keyword.
        """

        if before is None:
            insertionkey = after
        else:
            insertionkey = before

        def get_insertion_idx():
            if not (isinstance(insertionkey, int) and
                    insertionkey >= len(self._cards)):
                idx = self._cardindex(insertionkey)
            else:
                idx = insertionkey

            if before is None:
                idx += 1

            return idx

        if replace:
            # The card presumably already exists somewhere in the header.
            # Check whether or not we actually have to move it; if it does need
            # to be moved we just delete it and then it will be reinserted
            # below
            old_idx = self._cardindex(card.keyword)
            insertion_idx = get_insertion_idx()

            if (insertion_idx >= len(self._cards) and
                    old_idx == len(self._cards) - 1):
                # The card would be appended to the end, but it's already at
                # the end
                return

            if before is not None:
                if old_idx == insertion_idx - 1:
                    return
            elif after is not None and old_idx == insertion_idx:
                return

            del self[old_idx]

        # Even if replace=True, the insertion idx may have changed since the
        # old card was deleted
        idx = get_insertion_idx()

        if card[0] in Card._commentary_keywords:
            cards = reversed(self._splitcommentary(card[0], card[1]))
        else:
            cards = [card]
        for c in cards:
            self.insert(idx, c)

    def _updateindices(self, idx, increment=True):
        """
        For all cards with index above idx, increment or decrement its index
        value in the keyword_indices dict.
        """

        if idx > len(self._cards):
            # Save us some effort
            return

        increment = 1 if increment else -1

        for index_sets in (self._keyword_indices, self._rvkc_indices):
            for indices in itervalues(index_sets):
                for jdx, keyword_index in enumerate(indices):
                    if keyword_index >= idx:
                        indices[jdx] += increment

    def _countblanks(self):
        """Returns the number of blank cards at the end of the Header."""

        for idx in range(1, len(self._cards)):
            if not self._cards[-idx].is_blank:
                return idx - 1
        return 0

    def _useblanks(self, count):
        for _ in range(count):
            if self._cards[-1].is_blank:
                del self[-1]
            else:
                break

    def _haswildcard(self, keyword):
        """Return `True` if the input keyword contains a wildcard pattern."""

        return (isinstance(keyword, string_types) and
                (keyword.endswith('...') or '*' in keyword or '?' in keyword))

    def _wildcardmatch(self, pattern):
        """
        Returns a list of indices of the cards matching the given wildcard
        pattern.

         * '*' matches 0 or more characters
         * '?' matches a single character
         * '...' matches 0 or more of any non-whitespace character
        """

        pattern = pattern.replace('*', r'.*').replace('?', r'.')
        pattern = pattern.replace('...', r'\S*') + '$'
        pattern_re = re.compile(pattern, re.I)

        return [idx for idx, card in enumerate(self._cards)
                if pattern_re.match(card.keyword)]

    def _set_slice(self, key, value, target):
        """
        Used to implement Header.__setitem__ and CardAccessor.__setitem__.
        """

        if isinstance(key, slice) or self._haswildcard(key):
            if isinstance(key, slice):
                indices = range(*key.indices(len(target)))
            else:
                indices = self._wildcardmatch(key)

            if isinstance(value, string_types) or not isiterable(value):
                value = itertools.repeat(value, len(indices))

            for idx, val in zip(indices, value):
                target[idx] = val

            return True

        return False

    def _splitcommentary(self, keyword, value):
        """
        Given a commentary keyword and value, returns a list of the one or more
        cards needed to represent the full value.  This is primarily used to
        create the multiple commentary cards needed to represent a long value
        that won't fit into a single commentary card.
        """

        # The maximum value in each card can be the maximum card length minus
        # the maximum key length (which can include spaces if they key length
        # less than 8
        maxlen = Card.length - KEYWORD_LENGTH
        valuestr = str(value)

        if len(valuestr) <= maxlen:
            # The value can fit in a single card
            cards = [Card(keyword, value)]
        else:
            # The value must be split across multiple consecutive commentary
            # cards
            idx = 0
            cards = []
            while idx < len(valuestr):
                cards.append(Card(keyword, valuestr[idx:idx + maxlen]))
                idx += maxlen
        return cards

    def _strip(self):
        """
        Strip cards specific to a certain kind of header.

        Strip cards like ``SIMPLE``, ``BITPIX``, etc. so the rest of
        the header can be used to reconstruct another kind of header.
        """

        # TODO: Previously this only deleted some cards specific to an HDU if
        # _hdutype matched that type.  But it seemed simple enough to just
        # delete all desired cards anyways, and just ignore the KeyErrors if
        # they don't exist.
        # However, it might be desirable to make this extendable somehow--have
        # a way for HDU classes to specify some headers that are specific only
        # to that type, and should be removed otherwise.

        if 'NAXIS' in self:
            naxis = self['NAXIS']
        else:
            naxis = 0

        if 'TFIELDS' in self:
            tfields = self['TFIELDS']
        else:
            tfields = 0

        for idx in range(naxis):
            try:
                del self['NAXIS' + str(idx + 1)]
            except KeyError:
                pass

        for name in ('TFORM', 'TSCAL', 'TZERO', 'TNULL', 'TTYPE',
                     'TUNIT', 'TDISP', 'TDIM', 'THEAP', 'TBCOL'):
            for idx in range(tfields):
                try:
                    del self[name + str(idx + 1)]
                except KeyError:
                    pass

        for name in ('SIMPLE', 'XTENSION', 'BITPIX', 'NAXIS', 'EXTEND',
                     'PCOUNT', 'GCOUNT', 'GROUPS', 'BSCALE', 'BZERO',
                     'TFIELDS'):
            try:
                del self[name]
            except KeyError:
                pass

    def _add_commentary(self, key, value, before=None, after=None):
        """
        Add a commentary card.

        If ``before`` and ``after`` are `None`, add to the last occurrence
        of cards of the same name (except blank card).  If there is no
        card (or blank card), append at the end.
        """

        if before is not None or after is not None:
            self._relativeinsert((key, value), before=before,
                                 after=after)
        else:
            self[key] = value

    # Some fixes for compatibility with the Python 3 dict interface, where
    # iteritems -> items, etc.
    if six.PY3:
        keys = iterkeys
        values = itervalues
        items = iteritems
        del iterkeys
        del itervalues
        del iteritems @contextmanager
def ignored(*exceptions):
    """A context manager for ignoring exceptions.  Equivalent to::

        try:
            <body>
        except exceptions:
            pass

    Example::

        >>> import os
        >>> with ignored(OSError):
        ...     os.remove('file-that-does-not-exist')

    """

    try:
        yield
    except exceptions:
        pass def getargspec(func):
    return inspect.getfullargspec(func)[:4] def first(iterable):
    """
    Returns the first item returned by iterating over an iterable object.

    Example:

    >>> a = [1, 2, 3]
    >>> first(a)
    1
    """

    return next(iter(iterable)) class lazyproperty(object):
    """
    Works similarly to property(), but computes the value only once.

    Adapted from the recipe at
    http://code.activestate.com/recipes/363602-lazy-property-evaluation
    """

    def __init__(self, fget, fset=None, fdel=None, doc=None):
        self._fget = fget
        self._fset = fset
        self._fdel = fdel
        if doc is None:
            self.__doc__ = fget.__doc__
        else:
            self.__doc__ = doc
        self._key = self._fget.__name__

    def __get__(self, obj, owner=None):
        if obj is None:
            return self
        try:
            return obj.__dict__[self._key]
        except KeyError:
            val = self._fget(obj)
            obj.__dict__[self._key] = val
            return val

    def __set__(self, obj, val):
        obj_dict = obj.__dict__
        if self._fset:
            ret = self._fset(obj, val)
            if ret is not None and obj_dict.get(self._key) is ret:
                # By returning the value set the setter signals that it took
                # over setting the value in obj.__dict__; this mechanism allows
                # it to override the input value
                return
        obj_dict[self._key] = val

    def __delete__(self, obj):
        if self._fdel:
            self._fdel(obj)
        if self._key in obj.__dict__:
            del obj.__dict__[self._key]

    def getter(self, fget):
        return self.__ter(fget, 0)

    def setter(self, fset):
        return self.__ter(fset, 1)

    def deleter(self, fdel):
        return self.__ter(fdel, 2)

    def __ter(self, f, arg):
        args = [self._fget, self._fset, self._fdel, self.__doc__]
        args[arg] = f
        cls_ns = sys._getframe(1).f_locals
        for k, v in iteritems(cls_ns):
            if v is self:
                property_name = k
                break

        cls_ns[property_name] = lazyproperty(*args)

        return cls_ns[property_name] def _is_int(val):
    return isinstance(val, integer_types + (np.integer,)) def _is_pseudo_unsigned(dtype):
    return dtype.kind == 'u' and dtype.itemsize >= 2 def _unsigned_zero(dtype):
    """
    Given a numpy dtype, finds its "zero" point, which is exactly in the
    middle of its range.
    """

    assert dtype.kind == 'u'
    return 1 << (dtype.itemsize * 8 - 1) def _pad_length(stringlen):
    """Bytes needed to pad the input stringlen to the next FITS block."""

    return (BLOCK_SIZE - (stringlen % BLOCK_SIZE)) % BLOCK_SIZE def itersubclasses(cls, _seen=None):
    """
    itersubclasses(cls)

    Generator over all subclasses of a given class, in depth first order.

    >>> list(itersubclasses(int)) == [bool]
    True
    >>> class A(object): pass
    >>> class B(A): pass
    >>> class C(A): pass
    >>> class D(B,C): pass
    >>> class E(D): pass
    >>>
    >>> for cls in itersubclasses(A):
    ...     print(cls.__name__)
    B
    D
    E
    C
    >>> # get ALL (new-style) classes currently defined
    >>> [cls.__name__ for cls in itersubclasses(object)] #doctest: +ELLIPSIS
    [...'tuple', ...'type', ...]

    From http://code.activestate.com/recipes/576949/
    """

    if not isinstance(cls, type):
        raise TypeError('itersubclasses must be called with '
                        'new-style classes, not %.100r' % cls)
    if _seen is None:
        _seen = set()
    try:
        subs = cls.__subclasses__()
    except TypeError:  # fails only when cls is type
        subs = cls.__subclasses__(cls)
    for sub in sorted(subs, key=lambda s: s.__name__):
        if sub not in _seen:
            _seen.add(sub)
            yield sub
            for sub in itersubclasses(sub, _seen):
                yield sub def decode_ascii(s):
    """
    In Python 2 this is a no-op.  Strings are left alone.  In Python 3 this
    will be replaced with a function that actually decodes ascii bytes to
    unicode.
    """

    return s def deprecated(since, message='', name='', alternative='', pending=False):
    """
    Used to mark a function as deprecated.

    To mark an attribute as deprecated, replace that attribute with a
    depcrecated property.

    Parameters
    ------------
    since : str
        The release at which this API became deprecated.  This is required.

    message : str, optional
        Override the default deprecation message.  The format specifier
        %(func)s may be used for the name of the function, and %(alternative)s
        may be used in the deprecation message to insert the name of an
        alternative to the deprecated function.

    name : str, optional
        The name of the deprecated function; if not provided the name is
        automatically determined from the passed in function, though this is
        useful in the case of renamed functions, where the new function is just
        assigned to the name of the deprecated function.  For example:
            def new_function():
                ...
            oldFunction = new_function

    alternative : str, optional
        An alternative function that the user may use in place of the
        deprecated function.  The deprecation warning will tell the user about
        this alternative if provided.

    pending : bool, optional
        If True, uses a PyfitsPendingDeprecationWarning instead of a
        PyfitsDeprecationWarning.

    """

    def deprecate(func, message=message, name=name, alternative=alternative,
                  pending=pending):
        if isinstance(func, classmethod):
            try:
                func = func.__func__
            except AttributeError:
                # classmethods in Python2.6 and below lack the __func__
                # attribute so we need to hack around to get it
                method = func.__get__(None, object)
                if hasattr(method, '__func__'):
                    func = method.__func__
                elif hasattr(method, 'im_func'):
                    func = method.im_func
                else:
                    # Nothing we can do really...  just return the original
                    # classmethod
                    return func
            is_classmethod = True
        else:
            is_classmethod = False

        if not name:
            name = func.__name__

        altmessage = ''
        if not message or type(message) == type(deprecate):
            if pending:
                message = ('The %(func)s function will be deprecated in a '
                           'future version.')
            else:
                message = (
                    'The %(func)s function is deprecated as of version '
                    '%(since)s and may be removed in a future version.')
            if alternative:
                altmessage = '\n\n        Use %s instead.' % alternative

        message = ((message % {'func': name, 'alternative': alternative,
                               'since': since}) + altmessage)

        @functools.wraps(func)
        def deprecated_func(*args, **kwargs):
            if pending:
                category = PyfitsPendingDeprecationWarning
            else:
                category = PyfitsDeprecationWarning

            warnings.warn(message, category, stacklevel=2)

            return func(*args, **kwargs)

        old_doc = deprecated_func.__doc__
        if not old_doc:
            old_doc = ''
        old_doc = textwrap.dedent(old_doc).strip('\n')
        altmessage = altmessage.strip()
        if not altmessage:
            altmessage = message.strip()
        new_doc = (('\n.. deprecated:: %(since)s'
                    '\n    %(message)s\n\n' %
                    {'since': since, 'message': altmessage.strip()}) + old_doc)
        if not old_doc:
            # This is to prevent a spurious 'unexected unindent' warning from
            # docutils when the original docstring was blank.
            new_doc += r'\ '

        deprecated_func.__doc__ = new_doc

        if is_classmethod:
            deprecated_func = classmethod(deprecated_func)
        return deprecated_func

    if type(message) == type(deprecate):
        return deprecate(message)

    return deprecate def _get_array_mmap(array):
    """
    If the array has an mmap.mmap at base of its base chain, return the mmap
    object; otherwise return None.
    """

    if isinstance(array, mmap.mmap):
        return array

    base = array
    while hasattr(base, 'base') and base.base is not None:
        if isinstance(base.base, mmap.mmap):
            return base.base
        base = base.base class _Verify(object):
    """
    Shared methods for verification.
    """

    def run_option(self, option='warn', err_text='', fix_text='Fixed.',
                   fix=None, fixable=True):
        """
        Execute the verification with selected option.
        """

        text = err_text

        if option in ['warn', 'exception']:
            fixable = False
        # fix the value
        elif not fixable:
            text = 'Unfixable error: %s' % text
        else:
            if fix:
                fix()
            text += '  ' + fix_text

        return (fixable, text)

    def verify(self, option='warn'):
        """
        Verify all values in the instance.

        Parameters
        ----------
        option : str
            Output verification option.  Must be one of ``"fix"``,
            ``"silentfix"``, ``"ignore"``, ``"warn"``, or
            ``"exception"``.  May also be any combination of ``"fix"`` or
            ``"silentfix"`` with ``"+ignore"``, ``+warn``, or ``+exception"
            (e.g. ``"fix+warn"``).  See :ref:`verify` for more info.
        """

        opt = option.lower()
        if opt not in VERIFY_OPTIONS:
            raise ValueError('Option %r not recognized.' % option)

        if opt == 'ignore':
            return

        errs = self._verify(opt)

        # Break the verify option into separate options related to reporting of
        # errors, and fixing of fixable errors
        if '+' in opt:
            fix_opt, report_opt = opt.split('+')
        elif opt in ['fix', 'silentfix']:
            # The original default behavior for 'fix' and 'silentfix' was to
            # raise an exception for unfixable errors
            fix_opt, report_opt = opt, 'exception'
        else:
            fix_opt, report_opt = None, opt

        if fix_opt == 'silentfix' and report_opt == 'ignore':
            # Fixable errors were fixed, but don't report anything
            return

        if fix_opt == 'silentfix':
            # Don't print out fixable issues; the first element of each verify
            # item is a boolean indicating whether or not the issue was fixable
            line_filter = lambda x: not x[0]
        elif fix_opt == 'fix' and report_opt == 'ignore':
            # Don't print *unfixable* issues, but do print fixed issues; this
            # is probably not very useful but the option exists for
            # completeness
            line_filter = lambda x: x[0]
        else:
            line_filter = None

        unfixable = False
        messages = []
        for fixable, message in errs.iter_lines(filter=line_filter):
            if fixable is not None:
                unfixable = not fixable
            messages.append(message)

        if messages:
            messages.insert(0, 'Verification reported errors:')
            messages.append('Note: PyFITS uses zero-based indexing.\n')

            if fix_opt == 'silentfix' and not unfixable:
                return
            elif report_opt == 'warn' or (fix_opt == 'fix' and not unfixable):
                for line in messages:
                    warnings.warn(line, VerifyWarning)
            else:
                raise VerifyError('\n' + '\n'.join(messages)) class _ErrList(list):
    """
    Verification errors list class.  It has a nested list structure
    constructed by error messages generated by verifications at
    different class levels.
    """

    def __new__(cls, val=None, unit='Element'):
        return super(cls, cls).__new__(cls, val)

    def __init__(self, val=None, unit='Element'):
        self.unit = unit

    def __str__(self):
        return '\n'.join(item[1] for item in self.iter_lines())

    def iter_lines(self, filter=None, shift=0):
        """
        Iterate the nested structure as a list of strings with appropriate
        indentations for each level of structure.
        """

        element = 0
        # go through the list twice, first time print out all top level
        # messages
        for item in self:
            if not isinstance(item, _ErrList):
                if filter is None or filter(item):
                    yield item[0], indent(item[1], shift=shift)

        # second time go through the next level items, each of the next level
        # must present, even it has nothing.
        for item in self:
            if isinstance(item, _ErrList):
                next_lines = item.iter_lines(filter=filter, shift=shift + 1)
                try:
                    first_line = next(next_lines)
                except StopIteration:
                    first_line = None

                if first_line is not None:
                    if self.unit:
                        # This line is sort of a header for the next level in
                        # the hierarchy
                        yield None, indent('%s %s:' % (self.unit, element),
                                           shift=shift)
                    yield first_line

                for line in next_lines:
                    yield line

                element += 1
import datetime
import os
import sys
import warnings
import numpy as np
import pyfits
from ..extern.six import string_types, add_metaclass
from ..extern.six.moves import range
from ..file import _File
from ..header import Header
from ..py3compat import ignored, getargspec
from ..util import (first, lazyproperty, _is_int, _is_pseudo_unsigned,
                    _unsigned_zero, _pad_length, itersubclasses,
                    decode_ascii, deprecated, _get_array_mmap)
from ..verify import _Verify, _ErrList
        from pyfits.hdu.hdulist import HDUList
        from pyfits.hdu.hdulist import HDUList
        from pyfits.hdu.image import PrimaryHDU

        For some special cases, supports using a header that was already
        created, and just using the input data for the actual array data.
        """

        hdu_buffer = None
        hdu_fileobj = None
        header_offset = 0

        if isinstance(data, _File):
            from_file = True
            if header is None:
                header_offset = data.tell()
                header = Header.fromfile(data, endcard=not ignore_missing_end)
            hdu_fileobj = data
            data_offset = data.tell()  # *after* reading the header
        else:
            from_file = False
            try:
                # Test that the given object supports the buffer interface by
                # ensuring an ndarray can be created from it
                np.ndarray((), dtype='ubyte', buffer=data)
            except TypeError:
                raise TypeError(
                    'The provided object %r does not contain an underlying '
                    'memory buffer.  fromstring() requires an object that '
                    'supports the buffer interface such as bytes, str '
                    '(in Python 2.x but not in 3.x), buffer, memoryview, '
                    'ndarray, etc.  This restriction is to ensure that '
                    'efficient access to the array/table data is possible.'
                    % data)

            if header is None:
                def block_iter(nbytes):
                    idx = 0
                    while idx < len(data):
                        yield data[idx:idx + nbytes]
                        idx += nbytes

                header_str, header = Header._from_blocks(
                    block_iter, True, '', not ignore_missing_end, True)

                if len(data) > len(header_str):
                    hdu_buffer = data
            elif data:
                hdu_buffer = data

            header_offset = 0
            data_offset = len(header_str)

        # Determine the appropriate arguments to pass to the constructor from
        # self._kwargs.  self._kwargs contains any number of optional arguments
        # that may or may not be valid depending on the HDU type
        cls = _hdu_class_from_header(cls, header)
        args, varargs, varkwargs, defaults = getargspec(cls.__init__)
        new_kwargs = kwargs.copy()
        if not varkwargs:
            # If __init__ accepts arbitrary keyword arguments, then we can go
            # ahead and pass all keyword arguments; otherwise we need to delete
            # any that are invalid
            for key in kwargs:
                if key not in args:
                    del new_kwargs[key]

        hdu = cls(data=DELAYED, header=header, **new_kwargs)

        # One of these may be None, depending on whether the data came from a
        # file or a string buffer--later this will be further abstracted
        hdu._file = hdu_fileobj
        hdu._buffer = hdu_buffer

        hdu._header_offset = header_offset     # beginning of the header area
        hdu._data_offset = data_offset         # beginning of the data area

        # data area size, including padding
        size = hdu.size
        hdu._data_size = size + _pad_length(size)

        # Checksums are not checked on invalid HDU types
        if checksum and checksum != 'remove' and isinstance(hdu, _ValidHDU):
            hdu._verify_checksum_datasum(checksum)

        return hdu


    def _get_raw_data(self, shape, code, offset):
        """
        Return raw array from either the HDU's memory buffer or underlying
        file.
        """

        if isinstance(shape, int):
            shape = (shape,)

        if self._buffer:
            return np.ndarray(shape, dtype=code, buffer=self._buffer,
                              offset=offset)
        elif self._file:
            return self._file.readarray(offset=offset, dtype=code, shape=shape)
        else:
            return None

    # TODO: Rework checksum handling so that it's not necessary to add a
    # checksum argument here
    # TODO: The BaseHDU class shouldn't even handle checksums since they're
    # only implemented on _ValidHDU...
    def _prewriteto(self, checksum=False, inplace=False):
        self._update_uint_scale_keywords()

        # Handle checksum
        self._update_checksum(checksum)


    def _update_uint_scale_keywords(self):
        """
        If the data is unsigned int 16, 32, or 64 add BSCALE/BZERO cards to
        header.
        """

        if (self._has_data and self._standard and

                _is_pseudo_unsigned(self.data.dtype)):