FITS2NUMPY = {'L': 'i1', 'B': 'u1', 'I': 'i2', 'J': 'i4', 'K': 'i8', 'E': 'f4',
              'D': 'f8', 'C': 'c8', 'M': 'c16', 'A': 'a'} KEYWORD_NAMES = ['TTYPE', 'TFORM', 'TUNIT', 'TNULL', 'TSCAL', 'TZERO',
                 'TDISP', 'TBCOL', 'TDIM'] KEYWORD_TO_ATTRIBUTE = \
    OrderedDict((keyword, attr)
                for keyword, attr in zip(KEYWORD_NAMES, KEYWORD_ATTRIBUTES)) ATTRIBUTE_TO_KEYWORD = \
    OrderedDict((value, key)
                for key, value in KEYWORD_TO_ATTRIBUTE.items()) TDEF_RE = re.compile(r'(?P<label>^T[A-Z]*)(?P<num>[1-9][0-9 ]*$)') class Column(NotifierMixin):
    """
    Class which contains the definition of one column, e.g.  ``ttype``,
    ``tform``, etc. and the array containing values for the column.
    """

    def __init__(self, name=None, format=None, unit=None, null=None,
                 bscale=None, bzero=None, disp=None, start=None, dim=None,
                 array=None, ascii=None):
        """
        Construct a `Column` by specifying attributes.  All attributes
        except ``format`` can be optional; see :ref:`column_creation` and
        :ref:`creating_ascii_table` for more information regarding
        ``TFORM`` keyword.

        Parameters
        ----------
        name : str, optional
            column name, corresponding to ``TTYPE`` keyword

        format : str
            column format, corresponding to ``TFORM`` keyword

        unit : str, optional
            column unit, corresponding to ``TUNIT`` keyword

        null : str, optional
            null value, corresponding to ``TNULL`` keyword

        bscale : int-like, optional
            bscale value, corresponding to ``TSCAL`` keyword

        bzero : int-like, optional
            bzero value, corresponding to ``TZERO`` keyword

        disp : str, optional
            display format, corresponding to ``TDISP`` keyword

        start : int, optional
            column starting position (ASCII table only), corresponding
            to ``TBCOL`` keyword

        dim : str, optional
            column dimension corresponding to ``TDIM`` keyword

        array : iterable, optional
            a `list`, `numpy.ndarray` (or other iterable that can be used to
            initialize an ndarray) providing initial data for this column.
            The array will be automatically converted, if possible, to the data
            format of the column.  In the case were non-trivial ``bscale``
            and/or ``bzero`` arguments are given, the values in the array must
            be the *physical* values--that is, the values of column as if the
            scaling has already been applied (the array stored on the column
            object will then be converted back to its storage values).

        ascii : bool, optional
            set `True` if this describes a column for an ASCII table; this
            may be required to disambiguate the column format
        """

        if format is None:
            raise ValueError('Must specify format to construct Column.')

        # any of the input argument (except array) can be a Card or just
        # a number/string
        kwargs = {'ascii': ascii}
        for attr in KEYWORD_ATTRIBUTES:
            value = locals()[attr]  # get the argument's value

            if isinstance(value, Card):
                value = value.value

            kwargs[attr] = value

        valid_kwargs, invalid_kwargs = self._verify_keywords(**kwargs)

        if invalid_kwargs:
            msg = ['The following keyword arguments to Column were invalid:']

            for val in invalid_kwargs.values():
                msg.append(indent(val[1]))

            raise VerifyError('\n'.join(msg))

        for attr in KEYWORD_ATTRIBUTES:
            setattr(self, attr, valid_kwargs.get(attr))

        # TODO: For PyFITS 3.3 try to eliminate the following two special cases
        # for recformat and dim:
        # This is not actually stored as an attribute on columns for some
        # reason
        recformat = valid_kwargs['recformat']

        # The 'dim' keyword's original value is stored in self.dim, while
        # *only* the tuple form is stored in self._dims.
        self._dims = self.dim
        self.dim = dim

        # Awful hack to use for now to keep track of whether the column holds
        # pseudo-unsigned int data
        self._pseudo_unsigned_ints = False

        # if the column data is not ndarray, make it to be one, i.e.
        # input arrays can be just list or tuple, not required to be ndarray
        # does not include Object array because there is no guarantee
        # the elements in the object array are consistent.
        if not isinstance(array,
                          (np.ndarray, chararray.chararray, Delayed)):
            try:  # try to convert to a ndarray first
                if array is not None:
                    array = np.array(array)
            except:
                try:  # then try to convert it to a strings array
                    itemsize = int(recformat[1:])
                    array = chararray.array(array, itemsize=itemsize)
                except ValueError:
                    # then try variable length array
                    # Note: This includes _FormatQ by inheritance
                    if isinstance(recformat, _FormatP):
                        array = _VLF(array, dtype=recformat.dtype)
                    else:
                        raise ValueError('Data is inconsistent with the '
                                         'format `%s`.' % format)

        array = self._convert_to_valid_data_type(array)

        # We have required (through documentation) that arrays passed in to
        # this constructor are already in their physical values, so we make
        # note of that here
        if isinstance(array, np.ndarray):
            self._physical_values = True
        else:
            self._physical_values = False

        self._parent_fits_rec = None
        self.array = array

    def __repr__(self):
        text = ''
        for attr in KEYWORD_ATTRIBUTES:
            value = getattr(self, attr)
            if value is not None:
                text += attr + ' = ' + repr(value) + '; '
        return text[:-2]

    def __eq__(self, other):
        """
        Two columns are equal if their name and format are the same.  Other
        attributes aren't taken into account at this time.
        """

        # According to the FITS standard column names must be case-insensitive
        a = (self.name.lower(), self.format)
        b = (other.name.lower(), other.format)
        return a == b

    def __hash__(self):
        """
        Like __eq__, the hash of a column should be based on the unique column
        name and format, and be case-insensitive with respect to the column
        name.
        """

        return hash((self.name.lower(), self.format))

    @property
    def array(self):
        """
        The Numpy `~numpy.ndarray` associated with this `Column`.

        If the column was instantiated with an array passed to the ``array``
        argument, this will return that array.  However, if the column is
        later added to a table, such as via `BinTableHDU.from_columns` as
        is typically the case, this attribute will be updated to reference
        the associated field in the table, which may no longer be the same
        array.
        """

        # Ideally the .array attribute never would have existed in the first
        # place, or would have been internal-only.  This is a legacy of the
        # older design from PyFITS that needs to have continued support, for
        # now.

        # One of the main problems with this design was that it created a
        # reference cycle.  When the .array attribute was updated after
        # creating a FITS_rec from the column (as explained in the docstring) a
        # reference cycle was created.  This is because the code in BinTableHDU
        # (and a few other places) does essentially the following:
        #
        # data._coldefs = columns  # The ColDefs object holding this Column
        # for col in columns:
        #     col.array = data.field(col.name)
        #
        # This way each columns .array attribute now points to the field in the
        # table data.  It's actually a pretty confusing interface (since it
        # replaces the array originally pointed to by .array), but it's the way
        # things have been for a long, long time.
        #
        # However, this results, in *many* cases, in a reference cycle.
        # Because the array returned by data.field(col.name), while sometimes
        # an array that owns its own data, is usually like a slice of the
        # original data.  It has the original FITS_rec as the array .base.
        # This results in the following reference cycle (for the n-th column):
        #
        #    data -> data._coldefs -> data._coldefs[n] ->
        #     data._coldefs[n].array -> data._coldefs[n].array.base -> data
        #
        # Because ndarray objects do not handled by Python's garbage collector
        # the reference cycle cannot be broken.  Therefore the FITS_rec's
        # refcount never goes to zero, its __del__ is never called, and its
        # memory is never freed.  This didn't occur in *all* cases, but it did
        # occur in many cases.
        #
        # To get around this, Column.array is no longer a simple attribute
        # like it was previously.  Now each Column has a ._parent_fits_rec
        # attribute which is a weakref to a FITS_rec object.  Code that
        # previously assigned each col.array to field in a FITS_rec (as in
        # the example a few paragraphs above) is still used, however now
        # array.setter checks if a reference cycle will be created.  And if
        # so, instead of saving directly to the Column's __dict__, it creates
        # the ._prent_fits_rec weakref, and all lookups of the column's .array
        # go through that instead.
        #
        # This alone does not fully solve the problem.  Because
        # _parent_fits_rec is a weakref, if the user ever holds a reference to
        # the Column, but deletes all references to the underlying FITS_rec,
        # the .array attribute would suddenly start returning None instead of
        # the array data.  This problem is resolved on FITS_rec's end.  See the
        # note in the FITS_rec._coldefs property for the rest of the story.

        # If the Columns's array is not a reference to an existing FITS_rec,
        # then it is just stored in self.__dict__; otherwise check the
        # _parent_fits_rec reference if it 's still available.
        if 'array' in self.__dict__:
            return self.__dict__['array']
        elif self._parent_fits_rec is not None:
            parent = self._parent_fits_rec()
            if parent is not None:
                return parent[self.name]
        else:
            return None

    @array.setter
    def array(self, array):
        # The following looks over the bases of the given array to check if it
        # has a ._coldefs attribute (i.e. is a FITS_rec) and that that _coldefs
        # contains this Column itself, and would create a reference cycle if we
        # stored the array directly in self.__dict__.
        # In this case it instead sets up the _parent_fits_rec weakref to the
        # underlying FITS_rec, so that array.getter can return arrays through
        # self._parent_fits_rec().field(self.name), rather than storing a
        # hard reference to the field like it used to.
        base = array
        while True:
            if (hasattr(base, '_coldefs') and
                    isinstance(base._coldefs, ColDefs)):
                for col in base._coldefs:
                    if col is self and self._parent_fits_rec is None:
                        self._parent_fits_rec = weakref.ref(base)

                        # Just in case the user already set .array to their own
                        # array.
                        if 'array' in self.__dict__:
                            del self.__dict__['array']
                        return

            if getattr(base, 'base', None) is not None:
                base = base.base
            else:
                break

        self.__dict__['array'] = array

    @array.deleter
    def array(self):
        try:
            del self.__dict__['array']
        except KeyError:
            pass

        self._parent_fits_rec = None

    @ColumnAttribute('TTYPE')
    def name(col, name):
        if name is None:
            # Allow None to indicate deleting the name, or to just indicate an
            # unspecified name (when creating a new Column).
            return

        # Check that the name meets the recommended standard--other column
        # names are *allowed*, but will be discouraged
        if isinstance(name, string_types) and not TTYPE_RE.match(name):
            warnings.warn(
                'It is strongly recommended that column names contain only '
                'upper and lower-case ASCII letters, digits, or underscores '
                'for maximum compatibility with other software '
                '(got {0!r}).'.format(name), VerifyWarning)

        # This ensures that the new name can fit into a single FITS card
        # without any special extension like CONTINUE cards or the like.
        assert (isinstance(name, string_types) and
                len(str(Card('TTYPE', name))) == CARD_LENGTH), \
                    ('Column name must be a string able to fit in a single '
                     'FITS card--typically this means a maximum of 68 '
                     'characters, though it may be fewer if the string '
                     'contains special characters like quotes.')

    format = ColumnAttribute('TFORM')
    unit = ColumnAttribute('TUNIT')
    null = ColumnAttribute('TNULL')
    bscale = ColumnAttribute('TSCAL')
    bzero = ColumnAttribute('TZERO')
    disp = ColumnAttribute('TDISP')
    start = ColumnAttribute('TBCOL')
    dim = ColumnAttribute('TDIM')

    @lazyproperty
    def ascii(self):
        """Whether this `Column` represents an column in an ASCII table."""

        return isinstance(self.format, _AsciiColumnFormat)

    @lazyproperty
    def dtype(self):
        return self.format.dtype

    def copy(self):
        """
        Return a copy of this `Column`.
        """
        tmp = Column(format='I')  # just use a throw-away format
        tmp.__dict__ = self.__dict__.copy()
        return tmp

    if sys.version_info < (2, 7):
        # This is only needed on Python 2.6, where it appears deepcopy has
        # problems with weakrefs, and especially weak-keyed dicts.
        def __deepcopy__(self, memo=None):
            tmp = object.__new__(self.__class__)
            tmp_dict = dict(self.__dict__)
            array = self.array
            listeners = None
            if array is not None:
                tmp_dict['array'] = array.copy()
            tmp_dict['_parent_fits_rec'] = None

            if '_listeners' in tmp_dict:
                listners = tmp_dict['_listeners']
                del tmp_dict['_listeners']

            tmp.__dict__ = copy.deepcopy(tmp_dict, memo=memo)

            if listeners is not None:
                tmp.__dict__['_listeners'] = listeners
            return tmp

    @staticmethod
    def _convert_format(format, cls):
        """The format argument to this class's initializer may come in many
        forms.  This uses the given column format class ``cls`` to convert
        to a format of that type.

        TODO: There should be an abc base class for column format classes
        """

        # Short circuit in case we're already a _BaseColumnFormat--there is at
        # least one case in which this can happen
        if isinstance(format, _BaseColumnFormat):
            return format, format.recformat

        if format in NUMPY2FITS:
            with ignored(VerifyError):
                # legit recarray format?
                recformat = format
                format = cls.from_recformat(format)

        try:
            # legit FITS format?
            format = cls(format)
            recformat = format.recformat
        except VerifyError:
            raise VerifyError('Illegal format `%s`.' % format)

        return format, recformat

    @classmethod
    def _verify_keywords(cls, name=None, format=None, unit=None, null=None,
                         bscale=None, bzero=None, disp=None, start=None,
                         dim=None, ascii=None):
        """
        Given the keyword arguments used to initialize a Column, specifically
        those that typically read from a FITS header (so excluding array),
        verify that each keyword has a valid value.

        Returns a 2-tuple of dicts.  The first maps valid keywords to their
        values.  The second maps invalid keywords to a 2-tuple of their value,
        and a message explaining why they were found invalid.
        """

        valid = {}
        invalid = {}

        format, recformat = cls._determine_formats(format, start, dim, ascii)
        valid.update(format=format, recformat=recformat)

        # Currently we don't have any validation for name, unit, bscale, or
        # bzero so include those by default
        # TODO: Add validation for these keywords, obviously
        for k, v in [('name', name), ('unit', unit), ('bscale', bscale),
                     ('bzero', bzero)]:
            if v is not None and v != '':
                valid[k] = v

        # Validate null option
        # Note: Enough code exists that thinks empty strings are sensible
        # inputs for these options that we need to treat '' as None
        if null is not None and null != '':
            msg = None
            if isinstance(format, _AsciiColumnFormat):
                null = str(null)
                if len(null) > format.width:
                    msg = (
                        "ASCII table null option (TNULLn) is longer than "
                        "the column's character width and will be truncated "
                        "(got %r)." % null)
            else:
                if not _is_int(null):
                    # Make this an exception instead of a warning, since any
                    # non-int value is meaningless
                    msg = (
                        'Column null option (TNULLn) must be an integer for '
                        'binary table columns (got %r).  The invalid value '
                        'will be ignored for the purpose of formatting '
                        'the data in this column.' % null)

                tnull_formats = ('B', 'I', 'J', 'K')

                if not (format.format in tnull_formats or
                        (format.format in ('P', 'Q') and
                         format.p_format in tnull_formats)):
                    # TODO: We should also check that TNULLn's integer value
                    # is in the range allowed by the column's format
                    msg = (
                        'Column null option (TNULLn) is invalid for binary '
                        'table columns of type %r (got %r).  The invalid '
                        'value will be ignored for the purpose of formatting '
                        'the data in this column.' % (format, null))

            if msg is None:
                valid['null'] = null
            else:
                invalid['null'] = (null, msg)

        # Validate the disp option
        # TODO: Add full parsing and validation of TDISPn keywords
        if disp is not None and disp != '':
            msg = None
            if not isinstance(disp, string_types):
                msg = (
                    'Column disp option (TDISPn) must be a string (got %r).'
                    'The invalid value will be ignored for the purpose of '
                    'formatting the data in this column.' % disp)

            if (isinstance(format, _AsciiColumnFormat) and
                    disp[0].upper() == 'L'):
                # disp is at least one character long and has the 'L' format
                # which is not recognized for ASCII tables
                msg = (
                    "Column disp option (TDISPn) may not use the 'L' format "
                    "with ASCII table columns.  The invalid value will be "
                    "ignored for the purpose of formatting the data in this "
                    "column.")

            if msg is None:
                valid['disp'] = disp
            else:
                invalid['disp'] = (disp, msg)

        # Validate the start option
        if start is not None and start != '':
            msg = None
            if not isinstance(format, _AsciiColumnFormat):
                # The 'start' option only applies to ASCII columns
                msg = (
                    'Column start option (TBCOLn) is not allowed for binary '
                    'table columns (got %r).  The invalid keyword will be '
                    'ignored for the purpose of formatting the data in this '
                    'column.'% start)
            try:
                start = int(start)
            except (TypeError, ValueError):
                pass

            if not _is_int(start) and start < 1:
                msg = (
                    'Column start option (TBCOLn) must be a positive integer '
                    '(got %r).  The invalid value will be ignored for the '
                    'purpose of formatting the data in this column.' % start)

            if msg is None:
                valid['start'] = start
            else:
                invalid['start'] = (start, msg)

        # Process TDIMn options
        # ASCII table columns can't have a TDIMn keyword associated with it;
        # for now we just issue a warning and ignore it.
        # TODO: This should be checked by the FITS verification code
        if dim is not None and dim != '':
            msg = None
            dims_tuple = tuple()
            # NOTE: If valid, the dim keyword's value in the the valid dict is
            # a tuple, not the original string; if invalid just the original
            # string is returned
            if isinstance(format, _AsciiColumnFormat):
                msg = (
                    'Column dim option (TDIMn) is not allowed for ASCII table '
                    'columns (got %r).  The invalid keyword will be ignored '
                    'for the purpose of formatting this column.' % dim)

            elif isinstance(dim, string_types):
                dims_tuple = _parse_tdim(dim)
            elif isinstance(dim, tuple):
                dims_tuple = dim
            else:
                msg = (
                    "`dim` argument must be a string containing a valid value "
                    "for the TDIMn header keyword associated with this column, "
                    "or a tuple containing the C-order dimensions for the "
                    "column.  The invalid value will be ignored for the purpose "
                    "of formatting this column.")

            if dims_tuple:
                if reduce(operator.mul, dims_tuple) > format.repeat:
                    msg = (
                        "The repeat count of the column format %r for column %r "
                        "is fewer than the number of elements per the TDIM "
                        "argument %r.  The invalid TDIMn value will be ignored "
                        "for the purpose of formatting this column." %
                        (name, format, dim))

            if msg is None:
                valid['dim'] = dims_tuple
            else:
                invalid['dim'] = (dim, msg)

        return valid, invalid

    @classmethod
    def _determine_formats(cls, format, start, dim, ascii):
        """
        Given a format string and whether or not the Column is for an
        ASCII table (ascii=None means unspecified, but lean toward binary table
        where ambiguous) create an appropriate _BaseColumnFormat instance for
        the column's format, and determine the appropriate recarray format.

        The values of the start and dim keyword arguments are also useful, as
        the former is only valid for ASCII tables and the latter only for
        BINARY tables.
        """

        # If the given format string is unambiguously a Numpy dtype or one of
        # the Numpy record format type specifiers supported by PyFITS then that
        # should take priority--otherwise assume it is a FITS format
        if isinstance(format, np.dtype):
            format, _, _ = _dtype_to_recformat(format)

        # check format
        if ascii is None and not isinstance(format, _BaseColumnFormat):
            # We're just give a string which could be either a Numpy format
            # code, or a format for a binary column array *or* a format for an
            # ASCII column array--there may be many ambiguities here.  Try our
            # best to guess what the user intended.
            format, recformat = cls._guess_format(format, start, dim)
        elif not ascii and not isinstance(format, _BaseColumnFormat):
            format, recformat = cls._convert_format(format, _ColumnFormat)
        elif ascii and not isinstance(format, _AsciiColumnFormat):
            format, recformat = cls._convert_format(format,
                                                    _AsciiColumnFormat)
        else:
            # The format is already acceptable and unambiguous
            recformat = format.recformat

        return format, recformat

    @classmethod
    def _guess_format(cls, format, start, dim):
        if start and dim:
            # This is impossible; this can't be a valid FITS column
            raise ValueError(
                'Columns cannot have both a start (TCOLn) and dim '
                '(TDIMn) option, since the former is only applies to '
                'ASCII tables, and the latter is only valid for binary '
                'tables.')
        elif start:
            # Only ASCII table columns can have a 'start' option
            guess_format = _AsciiColumnFormat
        elif dim:
            # Only binary tables can have a dim option
            guess_format = _ColumnFormat
        else:
            # If the format is *technically* a valid binary column format
            # (i.e. it has a valid format code followed by arbitrary
            # "optional" codes), but it is also strictly a valid ASCII
            # table format, then assume an ASCII table column was being
            # requested (the more likely case, after all).
            with ignored(VerifyError):
                format = _AsciiColumnFormat(format, strict=True)

            # A safe guess which reflects the existing behavior of previous
            # PyFITS versions
            guess_format = _ColumnFormat

        try:
            format, recformat = cls._convert_format(format, guess_format)
        except VerifyError:
            # For whatever reason our guess was wrong (for example if we got
            # just 'F' that's not a valid binary format, but it an ASCII format
            # code albeit with the width/precision omitted
            guess_format = (_AsciiColumnFormat
                            if guess_format is _ColumnFormat
                            else _ColumnFormat)
            # If this fails too we're out of options--it is truly an invalid
            # format, or at least not supported
            format, recformat = cls._convert_format(format, guess_format)

        return format, recformat

    def _convert_to_valid_data_type(self, array):
        # Convert the format to a type we understand
        if isinstance(array, Delayed):
            return array
        elif array is None:
            return array
        else:
            format = self.format
            dims = self._dims

            if dims:
                shape = dims[:-1] if 'A' in format else dims
                shape = (len(array),) + shape
                array = array.reshape(shape)

            if 'P' in format or 'Q' in format:
                return array
            elif 'A' in format:
                if array.dtype.char in 'SU':
                    if dims:
                        # The 'last' dimension (first in the order given
                        # in the TDIMn keyword itself) is the number of
                        # characters in each string
                        fsize = dims[-1]
                    else:
                        fsize = np.dtype(format.recformat).itemsize
                    return chararray.array(array, itemsize=fsize)
                else:
                    return _convert_array(array, np.dtype(format.recformat))
            elif 'L' in format:
                # boolean needs to be scaled back to storage values ('T', 'F')
                if array.dtype == np.dtype('bool'):
                    return np.where(array == False, ord('F'), ord('T'))
                else:
                    return np.where(array == 0, ord('F'), ord('T'))
            elif 'X' in format:
                return _convert_array(array, np.dtype('uint8'))
            else:
                # Preserve byte order of the original array for now; see #77
                numpy_format = array.dtype.byteorder + format.recformat

                # Handle arrays passed in as unsigned ints as pseudo-unsigned
                # int arrays; blatantly tacked in here for now--we need columns
                # to have explicit knowledge of whether they treated as
                # pseudo-unsigned
                bzeros = {2: np.uint16(2**15), 4: np.uint32(2**31),
                          8: np.uint64(2**63)}
                if (array.dtype.kind == 'u' and
                        array.dtype.itemsize in bzeros and
                        self.bscale in (1, None, '') and
                        self.bzero == bzeros[array.dtype.itemsize]):
                    # Basically the array is uint, has scale == 1.0, and the
                    # bzero is the appropriate value for a pseudo-unsigned
                    # integer of the input dtype, then go ahead and assume that
                    # uint is assumed
                    numpy_format = numpy_format.replace('i', 'u')
                    self._pseudo_unsigned_ints = True

                # The .base here means we're dropping the shape information,
                # which is only used to format recarray fields, and is not
                # useful for converting input arrays to the correct data type
                dtype = np.dtype(numpy_format).base

                return _convert_array(array, dtype) class ColDefs(NotifierMixin):
    """
    Column definitions class.

    It has attributes corresponding to the `Column` attributes
    (e.g. `ColDefs` has the attribute ``names`` while `Column`
    has ``name``). Each attribute in `ColDefs` is a list of
    corresponding attribute values from all `Column` objects.
    """

    _padding_byte = '\x00'
    _col_format_cls = _ColumnFormat

    def __new__(cls, input, tbtype=None, ascii=False):
        if tbtype is not None:
            warnings.warn(
                'The ``tbtype`` argument to `ColDefs` is deprecated as of '
                'PyFITS 3.3; instead the appropriate table type should be '
                'inferred from the formats of the supplied columns.  Use the '
                '``ascii=True`` argument to ensure that ASCII table columns '
                'are used.')
        else:
            tbtype = 'BinTableHDU'  # The old default

        # Backwards-compat support
        # TODO: Remove once the tbtype argument is removed entirely
        if tbtype == 'BinTableHDU':
            klass = cls
        elif tbtype == 'TableHDU':
            klass = _AsciiColDefs
        else:
            raise ValueError('Invalid table type: %s.' % tbtype)

        if (hasattr(input, '_columns_type') and
                issubclass(input._columns_type, ColDefs)):
            klass = input._columns_type
        elif (hasattr(input, '_col_format_cls') and
                issubclass(input._col_format_cls, _AsciiColumnFormat)):
            klass = _AsciiColDefs

        if ascii:  # force ASCII if this has been explicitly requested
            klass = _AsciiColDefs

        return object.__new__(klass)

    def __getnewargs__(self):
        return (self._arrays,)

    def __init__(self, input, tbtype=None, ascii=False):
        """
        Parameters
        ----------

        input : sequence of `Column`, `ColDefs`, other
            An existing table HDU, an existing `ColDefs`, or any multi-field
            Numpy array or `numpy.recarray`.

        **(Deprecated)** tbtype : str, optional
            which table HDU, ``"BinTableHDU"`` (default) or
            ``"TableHDU"`` (text table).
            Now ColDefs for a normal (binary) table by default, but converted
            automatically to ASCII table ColDefs in the appropriate contexts
            (namely, when creating an ASCII table).

        ascii : bool
        """

        from pyfits.hdu.table import _TableBaseHDU
        from pyfits.fitsrec import FITS_rec

        if isinstance(input, ColDefs):
            self._init_from_coldefs(input)
        elif (isinstance(input, FITS_rec) and hasattr(input, '_coldefs') and
                input._coldefs):
            # If given a FITS_rec object we can directly copy its columns, but
            # only if its columns have already been defined, otherwise this
            # will loop back in on itself and blow up
            self._init_from_coldefs(input._coldefs)
        elif isinstance(input, np.ndarray) and input.dtype.fields is not None:
            # Construct columns from the fields of a record array
            self._init_from_array(input)
        elif isiterable(input):
            # if the input is a list of Columns
            self._init_from_sequence(input)
        elif isinstance(input, _TableBaseHDU):
            # Construct columns from fields in an HDU header
            self._init_from_table(input)
        else:
            raise TypeError('Input to ColDefs must be a table HDU, a list '
                            'of Columns, or a record/field array.')

        # Listen for changes on all columns
        for col in self.columns:
            col._add_listener(self)

    def _init_from_coldefs(self, coldefs):
        """Initialize from an existing ColDefs object (just copy the
        columns and convert their formats if necessary).
        """

        self.columns = [self._copy_column(col) for col in coldefs]

    def _init_from_sequence(self, columns):
        for idx, col in enumerate(columns):
            if not isinstance(col, Column):
                raise TypeError(
                    'Element %d in the ColDefs input is not a Column.' % idx)

        self._init_from_coldefs(columns)

    def _init_from_array(self, array):
        self.columns = []
        for idx in range(len(array.dtype)):
            cname = array.dtype.names[idx]
            ftype = array.dtype.fields[cname][0]
            format = self._col_format_cls.from_recformat(ftype)

            # Determine the appropriate dimensions for items in the column
            # (typically just 1D)
            dim = array.dtype[idx].shape[::-1]
            if dim and (len(dim) > 1 or 'A' in format):
                if 'A' in format:
                    # n x m string arrays must include the max string
                    # length in their dimensions (e.g. l x n x m)
                    dim = (array.dtype[idx].base.itemsize,) + dim
                dim = repr(dim).replace(' ', '')
            else:
                dim = None

            # Check for unsigned ints.
            bzero = None
            if 'I' in format and ftype == np.dtype('uint16'):
                bzero = np.uint16(2**15)
            elif 'J' in format and ftype == np.dtype('uint32'):
                bzero = np.uint32(2**31)
            elif 'K' in format and ftype == np.dtype('uint64'):
                bzero = np.uint64(2**63)

            c = Column(name=cname, format=format,
                       array=array.view(np.ndarray)[cname], bzero=bzero,
                       dim=dim)
            self.columns.append(c)

    def _init_from_table(self, table):
        hdr = table._header
        nfields = hdr['TFIELDS']

        # go through header keywords to pick out column definition keywords
        # definition dictionaries for each field
        col_keywords = [{} for i in range(nfields)]
        for keyword, value in iteritems(hdr):
            key = TDEF_RE.match(keyword)
            try:
                keyword = key.group('label')
            except:
                continue  # skip if there is no match
            if keyword in KEYWORD_NAMES:
                col = int(key.group('num'))
                if col <= nfields and col > 0:
                    attr = KEYWORD_TO_ATTRIBUTE[keyword]
                    if attr == 'format':
                        # Go ahead and convert the format value to the
                        # appropriate ColumnFormat container now
                        value = self._col_format_cls(value)
                    col_keywords[col - 1][attr] = value

        # Verify the column keywords and display any warnings if necessary;
        # we only want to pass on the valid keywords
        for idx, kwargs in enumerate(col_keywords):
            valid_kwargs, invalid_kwargs = Column._verify_keywords(**kwargs)
            for val in invalid_kwargs.values():
                warnings.warn(
                    'Invalid keyword for column %d: %s' % (idx + 1, val[1]),
                    VerifyWarning)
            # Special cases for recformat and dim
            # TODO: Try to eliminate the need for these special cases
            del valid_kwargs['recformat']
            if 'dim' in valid_kwargs:
                valid_kwargs['dim'] = kwargs['dim']
            col_keywords[idx] = valid_kwargs

        # data reading will be delayed
        for col in range(nfields):
            col_keywords[col]['array'] = Delayed(table, col)

        # now build the columns
        self.columns = [Column(**attrs) for attrs in col_keywords]

        # Add the table HDU is a listener to changes to the columns
        # (either changes to individual columns, or changes to the set of
        # columns (add/remove/etc.))
        self._add_listener(table)

    def __copy__(self):
        return self.__class__(self)

    def __deepcopy__(self, memo):
        return self.__class__([copy.deepcopy(c, memo) for c in self.columns])

    def _copy_column(self, column):
        """Utility function used currently only by _init_from_coldefs
        to help convert columns from binary format to ASCII format or vice
        versa if necessary (otherwise performs a straight copy).
        """

        if isinstance(column.format, self._col_format_cls):
            # This column has a FITS format compatible with this column
            # definitions class (that is ascii or binary)
            return column.copy()

        new_column = column.copy()

        # Try to use the Numpy recformat as the equivalency between the
        # two formats; if that conversion can't be made then these
        # columns can't be transferred
        # TODO: Catch exceptions here and raise an explicit error about
        # column format conversion
        new_column.format = self._col_format_cls.from_column_format(
                column.format)

        # Handle a few special cases of column format options that are not
        # compatible between ASCII an binary tables
        # TODO: This is sort of hacked in right now; we really need
        # separate classes for ASCII and Binary table Columns, and they
        # should handle formatting issues like these
        if not isinstance(new_column.format, _AsciiColumnFormat):
            # the column is a binary table column...
            new_column.start = None
            if new_column.null is not None:
                # We can't just "guess" a value to represent null
                # values in the new column, so just disable this for
                # now; users may modify it later
                new_column.null = None
        else:
            # the column is an ASCII table column...
            if new_column.null is not None:
                new_column.null = DEFAULT_ASCII_TNULL
            if (new_column.disp is not None and
                    new_column.disp.upper().startswith('L')):
                # ASCII columns may not use the logical data display format;
                # for now just drop the TDISPn option for this column as we
                # don't have a systematic conversion of boolean data to ASCII
                # tables yet
                new_column.disp = None

        return new_column

    def __getattr__(self, name):
        """
        Automatically returns the values for the given keyword attribute for
        all `Column`s in this list.

        Implements for example self.units, self.formats, etc.
        """

        cname = name[:-1]
        if cname in KEYWORD_ATTRIBUTES and name[-1] == 's':
            attr = []
            for col in self:
                val = getattr(col, cname)
                if val is not None:
                    attr.append(val)
                else:
                    attr.append('')
            return attr
        raise AttributeError(name)

    @lazyproperty
    def dtype(self):
        # Note: This previously returned a dtype that just used the raw field
        # widths based on the format's repeat count, and did not incorporate
        # field *shapes* as provided by TDIMn keywords.
        # Now this incorporates TDIMn from the start, which makes *this* method
        # a little more complicated, but simplifies code elsewhere (for example
        # fields will have the correct shapes even in the raw recarray).
        fields = []
        offsets = [0]

        for name, format_, dim in zip(self.names, self.formats, self._dims):
            dt = format_.dtype

            if len(offsets) < len(self.formats):
                # Note: the size of the *original* format_ may be greater than
                # one would expect from the number of elements determined by
                # dim.  The FITS format allows this--the rest of the field is
                # filled with undefined values.
                offsets.append(offsets[-1] + dt.itemsize)

            if dim:
                if format_.format == 'A':
                    dt = np.dtype((dt.char + str(dim[-1]), dim[:-1]))
                else:
                    dt = np.dtype((dt.base, dim))

            fields.append((name, dt))

        return nh.realign_dtype(np.dtype(fields), offsets)

    @lazyproperty
    def _arrays(self):
        return [col.array for col in self.columns]

    @lazyproperty
    def _recformats(self):
        return [fmt.recformat for fmt in self.formats]

    @lazyproperty
    def _dims(self):
        """Returns the values of the TDIMn keywords parsed into tuples."""

        return [col._dims for col in self.columns]

    def __getitem__(self, key):
        if isinstance(key, string_types):
            key = _get_index(self.names, key)

        x = self.columns[key]
        if _is_int(key):
            return x
        else:
            return ColDefs(x)

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

    def __repr__(self):
        rep = 'ColDefs('
        if hasattr(self, 'columns') and self.columns:
            # The hasattr check is mostly just useful in debugging sessions
            # where self.columns may not be defined yet
            rep += '\n    '
            rep += '\n    '.join([repr(c) for c in self.columns])
            rep += '\n'
        rep += ')'
        return rep

    def __add__(self, other, option='left'):
        if isinstance(other, Column):
            b = [other]
        elif isinstance(other, ColDefs):
            b = list(other.columns)
        else:
            raise TypeError('Wrong type of input.')
        if option == 'left':
            tmp = list(self.columns) + b
        else:
            tmp = b + list(self.columns)
        return ColDefs(tmp)

    def __radd__(self, other):
        return self.__add__(other, 'right')

    def __sub__(self, other):
        if not isinstance(other, (list, tuple)):
            other = [other]
        _other = [_get_index(self.names, key) for key in other]
        indx = range(len(self))
        for x in _other:
            indx.remove(x)
        tmp = [self[i] for i in indx]
        return ColDefs(tmp)

    def _update_column_attribute_changed(self, column, attr, old_value,
                                         new_value):
        """
        Handle column attribute changed notifications from columns that are
        members of this `ColDefs`.

        `ColDefs` itself does not currently do anything with this, and just
        bubbles the notification up to any listening table HDUs that may need
        to update their headers, etc.  However, this also informs the table of
        the numerical index of the column that changed.
        """

        idx = 0
        for idx, col in enumerate(self.columns):
            if col is column:
                break

        self._notify('column_attribute_changed', column, idx, attr, old_value,
                     new_value)

    def add_col(self, column):
        """
        Append one `Column` to the column definition.

        .. warning::

            *New in pyfits 2.3*: This function appends the new column
            to the `ColDefs` object in place.  Prior to pyfits 2.3,
            this function returned a new `ColDefs` with the new column
            at the end.
        """

        assert isinstance(column, Column)

        self._arrays.append(column.array)
        # Obliterate caches of certain things
        del self.dtype
        del self._recformats
        del self._dims

        self.columns.append(column)

        # Listen for changes on the new column
        column._add_listener(self)

        # If this ColDefs is being tracked by a Table, inform the
        # table that its data is now invalid.
        self._notify('column_added', self, column)
        return self

    def del_col(self, col_name):
        """
        Delete (the definition of) one `Column`.

        col_name : str or int
            The column's name or index
        """

        indx = _get_index(self.names, col_name)
        col = self.columns[indx]

        del self._arrays[indx]
        # Obliterate caches of certain things
        del self.dtype
        del self._recformats
        del self._dims

        del self.columns[indx]

        col._remove_listener(self)

        # If this ColDefs is being tracked by a table HDU, inform the HDU (or
        # any other listeners) that the column has been removed
        # Just send a reference to self, and the index of the column that was
        # removed
        self._notify('column_removed', self, indx)
        return self

    def change_attrib(self, col_name, attrib, new_value):
        """
        Change an attribute (in the ``KEYWORD_ATTRIBUTES`` list) of a `Column`.

        Parameters
        ----------
        col_name : str or int
            The column name or index to change

        attrib : str
            The attribute name

        new_value : object
            The new value for the attribute
        """

        setattr(self[col_name], attrib, new_value)

    def change_name(self, col_name, new_name):
        """
        Change a `Column`'s name.

        Parameters
        ----------
        col_name : str
            The current name of the column

        new_name : str
            The new name of the column
        """

        if new_name != col_name and new_name in self.names:
            raise ValueError('New name %s already exists.' % new_name)
        else:
            self.change_attrib(col_name, 'name', new_name)

    def change_unit(self, col_name, new_unit):
        """
        Change a `Column`'s unit.

        Parameters
        ----------
        col_name : str or int
            The column name or index

        new_unit : str
            The new unit for the column
        """

        self.change_attrib(col_name, 'unit', new_unit)

    def info(self, attrib='all', output=None):
        """
        Get attribute(s) information of the column definition.

        Parameters
        ----------
        attrib : str
            Can be one or more of the attributes listed in
            ``pyfits.column.KEYWORD_ATTRIBUTES``.  The default is ``"all"``
            which will print out all attributes.  It forgives plurals and
            blanks.  If there are two or more attribute names, they must be
            separated by comma(s).

        output : file, optional
            File-like object to output to.  Outputs to stdout by default.
            If `False`, returns the attributes as a `dict` instead.

        Notes
        -----
        This function doesn't return anything by default; it just prints to
        stdout.
        """

        if output is None:
            output = sys.stdout

        if attrib.strip().lower() in ['all', '']:
            lst = KEYWORD_ATTRIBUTES
        else:
            lst = attrib.split(',')
            for idx in range(len(lst)):
                lst[idx] = lst[idx].strip().lower()
                if lst[idx][-1] == 's':
                    lst[idx] = list[idx][:-1]

        ret = {}

        for attr in lst:
            if output:
                if attr not in KEYWORD_ATTRIBUTES:
                    output.write("'%s' is not an attribute of the column "
                                 "definitions.\n" % attr)
                    continue
                output.write("%s:\n" % attr)
                output.write('    %s\n' % getattr(self, attr + 's'))
            else:
                ret[attr] = getattr(self, attr + 's')

        if not output:
            return ret class _AsciiColDefs(ColDefs):
    """ColDefs implementation for ASCII tables."""

    _padding_byte = ' '
    _col_format_cls = _AsciiColumnFormat

    def __init__(self, input, tbtype=None, ascii=True):
        super(_AsciiColDefs, self).__init__(input)

        # if the format of an ASCII column has no width, add one
        if not isinstance(input, _AsciiColDefs):
            self._update_field_metrics()
        else:
            for idx, s in enumerate(input.starts):
                self.columns[idx].start = s

            self._spans = input.spans
            self._width = input._width

    @lazyproperty
    def dtype(self):
        _itemsize = self.spans[-1] + self.starts[-1] - 1
        dtype = {}

        for j in range(len(self)):
            data_type = 'S' + str(self.spans[j])
            dtype[self.names[j]] = (data_type, self.starts[j] - 1)

        return np.dtype(dtype)

    @property
    def spans(self):
        """A list of the widths of each field in the table."""

        return self._spans

    @lazyproperty
    def _recformats(self):
        if len(self) == 1:
            widths = []
        else:
            widths = [y - x for x, y in pairwise(self.starts)]

        # Widths is the width of each field *including* any space between
        # fields; this is so that we can map the fields to string records in a
        # Numpy recarray
        widths.append(self._width - self.starts[-1] + 1)
        return ['a' + str(w) for w in widths]

    def add_col(self, column):
        super(_AsciiColDefs, self).add_col(column)
        self._update_field_metrics()

    def del_col(self, col_name):
        super(_AsciiColDefs, self).del_col(col_name)
        self._update_field_metrics()

    def _update_field_metrics(self):
        """
        Updates the list of the start columns, the list of the widths of each
        field, and the total width of each record in the table.
        """

        spans = [0] * len(self.columns)
        end_col = 0  # Refers to the ASCII text column, not the table col
        for idx, col in enumerate(self.columns):
            width = col.format.width

            # Update the start columns and column span widths taking into
            # account the case that the starting column of a field may not
            # be the column immediately after the previous field
            if not col.start:
                col.start = end_col + 1
            end_col = col.start + width - 1
            spans[idx] = width

        self._spans = spans
        self._width = end_col class _FormatP(str):
    """For P format in variable length table."""

    # As far as I can tell from my reading of the FITS standard, a type code is
    # *required* for P and Q formats; there is no default
    _format_re_template = (r'(?P<repeat>\d+)?%s(?P<dtype>[LXBIJKAEDCM])'
                            '(?:\((?P<max>\d*)\))?')
    _format_code = 'P'
    _format_re = re.compile(_format_re_template % _format_code)
    _descriptor_format = '2i4'

    def __new__(cls, dtype, repeat=None, max=None):
        obj = super(_FormatP, cls).__new__(cls, cls._descriptor_format)
        obj.format = NUMPY2FITS[dtype]
        obj.dtype = dtype
        obj.repeat = repeat
        obj.max = max
        return obj

    def __getnewargs__(self):
        return (self.dtype, self.repeat, self.max)

    @classmethod
    def from_tform(cls, format):
        m = cls._format_re.match(format)
        if not m or m.group('dtype') not in FITS2NUMPY:
            raise VerifyError('Invalid column format: %s' % format)
        repeat = m.group('repeat')
        array_dtype = m.group('dtype')
        max = m.group('max')
        if not max:
            max = None
        return cls(FITS2NUMPY[array_dtype], repeat=repeat, max=max)

    @property
    def tform(self):
        repeat = '' if self.repeat is None else self.repeat
        max = '' if self.max is None else self.max
        return '%s%s%s(%s)' % (repeat, self._format_code, self.format, max) class _FormatQ(_FormatP):
    """Carries type description of the Q format for variable length arrays.

    The Q format is like the P format but uses 64-bit integers in the array
    descriptors, allowing for heaps stored beyond 2GB into a file.
    """

    _format_code = 'Q'
    _format_re = re.compile(_FormatP._format_re_template % _format_code)
    _descriptor_format = '2i8' def _makep(array, descr_output, format, nrows=None):
    """
    Construct the P (or Q) format column array, both the data descriptors and
    the data.  It returns the output "data" array of data type `dtype`.

    The descriptor location will have a zero offset for all columns
    after this call.  The final offset will be calculated when the file
    is written.

    Parameters
    ----------
    array
        input object array

    descr_output
        output "descriptor" array of data type int32 (for P format arrays) or
        int64 (for Q format arrays)--must be nrows long in its first dimension

    format
        the _FormatP object representing the format of the variable array

    nrows : int, optional
        number of rows to create in the column; defaults to the number of rows
        in the input array
    """

    # TODO: A great deal of this is redundant with FITS_rec._convert_p; see if
    # we can merge the two somehow.

    _offset = 0

    if not nrows:
        nrows = len(array)
    n = min(len(array), nrows)

    data_output = _VLF([None] * nrows, dtype=format.dtype)

    if format.dtype == 'a':
        _nbytes = 1
    else:
        _nbytes = np.array([], dtype=format.dtype).itemsize

    for idx in range(nrows):
        if idx < len(array):
            rowval = array[idx]
        else:
            if format.dtype == 'a':
                rowval = ' ' * data_output.max
            else:
                rowval = [0] * data_output.max
        if format.dtype == 'a':
            data_output[idx] = chararray.array(encode_ascii(rowval),
                                               itemsize=1)
        else:
            data_output[idx] = np.array(rowval, dtype=format.dtype)

        descr_output[idx, 0] = len(data_output[idx])
        descr_output[idx, 1] = _offset
        _offset += len(data_output[idx]) * _nbytes

    return data_output def _parse_tformat(tform):
    """Parse ``TFORMn`` keyword for a binary table into a
    ``(repeat, format, option)`` tuple.
    """

    try:
        (repeat, format, option) = TFORMAT_RE.match(tform.strip()).groups()
    except:
        # TODO: Maybe catch this error use a default type (bytes, maybe?) for
        # unrecognized column types.  As long as we can determine the correct
        # byte width somehow..
        raise VerifyError('Format %r is not recognized.' % tform)

    if repeat == '':
        repeat = 1
    else:
        repeat = int(repeat)

    return (repeat, format.upper(), option) def _scalar_to_format(value):
    """
    Given a scalar value or string, returns the minimum FITS column format
    that can represent that value.  'minimum' is defined by the order given in
    FORMATORDER.
    """

    # TODO: Numpy 1.6 and up has a min_scalar_type() function that can handle
    # this; in the meantime we have to use our own implementation (which for
    # now is pretty naive)

    # First, if value is a string, try to convert to the appropriate scalar
    # value
    for type_ in (int, float, complex):
        try:
            value = type_(value)
            break
        except ValueError:
            continue

    if isinstance(value, int) and value in (0, 1):
        # Could be a boolean
        return 'L'
    elif isinstance(value, int):
        for char in ('B', 'I', 'J', 'K'):
            type_ = np.dtype(FITS2NUMPY[char]).type
            if type_(value) == value:
                return char
    elif isinstance(value, float):
        # For now just assume double precision
        return 'D'
    elif isinstance(value, complex):
        return 'M'
    else:
        return 'A' + str(len(value)) @staticmethod
def _convert_format(format, cls):
    """The format argument to this class's initializer may come in many
    forms.  This uses the given column format class ``cls`` to convert
    to a format of that type.

    TODO: There should be an abc base class for column format classes
    """

    # Short circuit in case we're already a _BaseColumnFormat--there is at
    # least one case in which this can happen
    if isinstance(format, _BaseColumnFormat):
        return format, format.recformat

    if format in NUMPY2FITS:
        with ignored(VerifyError):
            # legit recarray format?
            recformat = format
            format = cls.from_recformat(format)

    try:
        # legit FITS format?
        format = cls(format)
        recformat = format.recformat
    except VerifyError:
        raise VerifyError('Illegal format `%s`.' % format)

    return format, recformat def _cmp_recformats(f1, f2):
    """
    Compares two numpy recformats using the ordering given by FORMATORDER.
    """

    if f1[0] == 'a' and f2[0] == 'a':
        return cmp(int(f1[1:]), int(f2[1:]))
    else:
        f1, f2 = NUMPY2FITS[f1], NUMPY2FITS[f2]
        return cmp(FORMATORDER.index(f1), FORMATORDER.index(f2)) def _get_index(names, key):
    """
    Get the index of the ``key`` in the ``names`` list.

    The ``key`` can be an integer or string.  If integer, it is the index
    in the list.  If string,

        a. Field (column) names are case sensitive: you can have two
           different columns called 'abc' and 'ABC' respectively.

        b. When you *refer* to a field (presumably with the field
           method), it will try to match the exact name first, so in
           the example in (a), field('abc') will get the first field,
           and field('ABC') will get the second field.

        If there is no exact name matched, it will try to match the
        name with case insensitivity.  So, in the last example,
        field('Abc') will cause an exception since there is no unique
        mapping.  If there is a field named "XYZ" and no other field
        name is a case variant of "XYZ", then field('xyz'),
        field('Xyz'), etc. will get this field.
    """

    if _is_int(key):
        indx = int(key)
    elif isinstance(key, string_types):
        # try to find exact match first
        try:
            indx = names.index(key.rstrip())
        except ValueError:
            # try to match case-insentively,
            _key = key.lower().rstrip()
            names = [n.lower().rstrip() for n in names]
            count = names.count(_key)  # occurrence of _key in names
            if count == 1:
                indx = names.index(_key)
            elif count == 0:
                raise KeyError("Key '%s' does not exist." % key)
            else:              # multiple match
                raise KeyError("Ambiguous key name '%s'." % key)
    else:
        raise KeyError("Illegal key '%s'." % repr(key))

    return indx class FITS_rec(np.recarray):
    """
    FITS record array class.

    `FITS_rec` is the data part of a table HDU's data part.  This is a layer
    over the `~numpy.recarray`, so we can deal with scaled columns.

    It inherits all of the standard methods from `numpy.ndarray`.
    """

    _record_type = FITS_record

    def __new__(subtype, input):
        """
        Construct a FITS record array from a recarray.
        """

        # input should be a record array
        if input.dtype.subdtype is None:
            self = np.recarray.__new__(subtype, input.shape, input.dtype,
                                       buf=input.data)
        else:
            self = np.recarray.__new__(subtype, input.shape, input.dtype,
                                       buf=input.data, strides=input.strides)

        self._init()
        if self.dtype.fields:
            self._nfields = len(self.dtype.fields)

        return self

    def __setstate__(self, state):
        meta = state[-1]
        column_state = state[-2]
        state = state[:-2]

        super(FITS_rec, self).__setstate__(state)

        self._col_weakrefs = WeakSet()

        for attr, value in zip(meta, column_state):
            setattr(self, attr, value)

    def __reduce__(self):
        """
        Return a 3-tuple for pickling a FITS_rec. Use the super-class
        functionality but then add in a tuple of FITS_rec-specific
        values that get used in __setstate__.
        """
        super_class = np.ndarray
        reconst_func, reconst_func_args, state = super_class.__reduce__(self)

        # Define FITS_rec-specific attrs that get added to state
        column_state = []
        meta = []

        if '_coldefs' in self.__dict__:
            meta.append('_coldefs')
            column_state.append(self._coldefs.__deepcopy__(None))

        for attr in set(dir(self))-set(dir(self.__class__)):
            # _coldefs can be Delayed, and file objects cannot be
            # picked, it needs to be deepcopied first
            if attr == '_col_weakrefs':
                continue
            else:
                column_state.append(getattr(self, attr))
            meta.append(attr)

        state = state + (column_state, meta)

        return reconst_func, reconst_func_args, state

    def __array_finalize__(self, obj):
        if obj is None:
            return

        if isinstance(obj, FITS_rec) and obj.dtype == self.dtype:
            self._converted = obj._converted
            self._heapoffset = obj._heapoffset
            self._heapsize = obj._heapsize
            self._col_weakrefs = obj._col_weakrefs
            self._coldefs = obj._coldefs
            self._nfields = obj._nfields
            self._gap = obj._gap
            self._uint = obj._uint
        elif self.dtype.fields is not None:
            # This will allow regular ndarrays with fields, rather than
            # just other FITS_rec objects
            self._nfields = len(self.dtype.fields)
            self._converted = {}

            self._heapoffset = getattr(obj, '_heapoffset', 0)
            self._heapsize = getattr(obj, '_heapsize', 0)

            self._gap = getattr(obj, '_gap', 0)
            self._uint = getattr(obj, '_uint', False)
            self._col_weakrefs = WeakSet()
            self._coldefs = ColDefs(self)

            # Work around chicken-egg problem.  Column.array relies on the
            # _coldefs attribute to set up ref back to parent FITS_rec; however
            # in the above line the self._coldefs has not been assigned yet so
            # this fails.  This patches that up...
            for col in self._coldefs:
                del col.array
                col._parent_fits_rec = weakref.ref(self)
        else:
            self._init()

    def _init(self):
        """Initializes internal attributes specific to FITS-isms."""

        self._nfields = 0
        self._converted = {}
        self._heapoffset = 0
        self._heapsize = 0
        self._col_weakrefs = WeakSet()
        self._coldefs = None
        self._gap = 0
        self._uint = False

    @classmethod
    def from_columns(cls, columns, nrows=0, fill=False):
        """
        Given a `ColDefs` object of unknown origin, initialize a new `FITS_rec`
        object.

        .. note::

            This was originally part of the `new_table` function in the table
            module but was moved into a class method since most of its
            functionality always had more to do with initializing a `FITS_rec`
            object than anything else, and much of it also overlapped with
            ``FITS_rec._scale_back``.

        Parameters
        ----------
        columns : sequence of `Column` or a `ColDefs`
            The columns from which to create the table data.  If these
            columns have data arrays attached that data may be used in
            initializing the new table.  Otherwise the input columns
            will be used as a template for a new table with the requested
            number of rows.

        nrows : int
            Number of rows in the new table.  If the input columns have data
            associated with them, the size of the largest input column is used.
            Otherwise the default is 0.

        fill : bool
            If `True`, will fill all cells with zeros or blanks.  If
            `False`, copy the data from input, undefined cells will still
            be filled with zeros/blanks.
        """

        if not isinstance(columns, ColDefs):
            columns = ColDefs(columns)

        # read the delayed data
        for column in columns:
            arr = column.array
            if isinstance(arr, Delayed):
                if arr.hdu.data is None:
                    column.array = None
                else:
                    column.array = _get_recarray_field(arr.hdu.data,
                                                       arr.field)
        # Reset columns._arrays (which we may want to just do away with
        # altogether
        del columns._arrays

        # use the largest column shape as the shape of the record
        if nrows == 0:
            for arr in columns._arrays:
                if arr is not None:
                    dim = arr.shape[0]
                else:
                    dim = 0
                if dim > nrows:
                    nrows = dim

        raw_data = np.empty(columns.dtype.itemsize * nrows, dtype=np.uint8)
        raw_data.fill(ord(columns._padding_byte))
        data = np.recarray(nrows, dtype=columns.dtype, buf=raw_data).view(cls)

        # Make sure the data is a listener for changes to the columns
        columns._add_listener(data)

        # Previously this assignment was made from hdu.columns, but that's a
        # bug since if a _TableBaseHDU has a FITS_rec in its .data attribute
        # the _TableBaseHDU.columns property is actually returned from
        # .data._coldefs, so this assignment was circular!  Don't make that
        # mistake again.
        # All of this is an artifact of the fragility of the FITS_rec class,
        # and that it can't just be initialized by columns...
        data._coldefs = columns

        # If fill is True we don't copy anything from the column arrays.  We're
        # just using them as a template, and returning a table filled with
        # zeros/blanks
        if fill:
            return data

        # Otherwise we have to fill the recarray with data from the input
        # columns
        for idx, column in enumerate(columns):
            # For each column in the ColDef object, determine the number of
            # rows in that column.  This will be either the number of rows in
            # the ndarray associated with the column, or the number of rows
            # given in the call to this function, which ever is smaller.  If
            # the input FILL argument is true, the number of rows is set to
            # zero so that no data is copied from the original input data.
            arr = column.array

            if arr is None:
                array_size = 0
            else:
                array_size = len(arr)

            n = min(array_size, nrows)

            # TODO: At least *some* of this logic is mostly redundant with the
            # _convert_foo methods in this class; see if we can eliminate some
            # of that duplication.

            if not n:
                # The input column had an empty array, so just use the fill
                # value
                continue

            field = _get_recarray_field(data, idx)
            name = column.name
            fitsformat = column.format
            recformat = fitsformat.recformat

            outarr = field[:n]
            inarr = arr[:n]

            if isinstance(recformat, _FormatX):
                # Data is a bit array
                if inarr.shape[-1] == recformat.repeat:
                    _wrapx(inarr, outarr, recformat.repeat)
                    continue
            elif isinstance(recformat, _FormatP):
                data._cache_field(name, _makep(inarr, field, recformat,
                                               nrows=nrows))
                continue
            # TODO: Find a better way of determining that the column is meant
            # to be FITS L formatted
            elif recformat[-2:] == FITS2NUMPY['L'] and inarr.dtype == bool:
                # column is boolean
                # The raw data field should be filled with either 'T' or 'F'
                # (not 0).  Use 'F' as a default
                field[:] = ord('F')
                # Also save the original boolean array in data._converted so
                # that it doesn't have to be re-converted
                converted = np.zeros(field.shape, dtype=bool)
                converted[:n] = inarr
                data._cache_field(name, converted)
                # TODO: Maybe this step isn't necessary at all if _scale_back
                # will handle it?
                inarr = np.where(inarr == False, ord('F'), ord('T'))
            elif (columns[idx]._physical_values and
                    columns[idx]._pseudo_unsigned_ints):
                # Temporary hack...
                bzero = column.bzero
                converted = np.zeros(field.shape, dtype=inarr.dtype)
                converted[:n] = inarr
                data._cache_field(name, converted)
                if n < nrows:
                    # Pre-scale rows below the input data
                    field[n:] = -bzero

                inarr = inarr - bzero
            elif isinstance(columns, _AsciiColDefs):
                # Regardless whether the format is character or numeric, if the
                # input array contains characters then it's already in the raw
                # format for ASCII tables
                if fitsformat._pseudo_logical:
                    # Hack to support converting from 8-bit T/F characters
                    # Normally the column array is a chararray of 1 character
                    # strings, but we need to view it as a normal ndarray of
                    # 8-bit ints to fill it with ASCII codes for 'T' and 'F'
                    outarr = field.view(np.uint8, np.ndarray)[:n]
                elif arr.dtype.kind not in ('S', 'U'):
                    # Set up views of numeric columns with the appropriate
                    # numeric dtype
                    # Fill with the appropriate blanks for the column format
                    data._cache_field(name, np.zeros(nrows, dtype=arr.dtype))
                    outarr = data._converted[name][:n]

                outarr[:] = inarr
                continue

            if inarr.shape != outarr.shape:
                if (inarr.dtype.kind == outarr.dtype.kind and
                        inarr.dtype.kind in ('U', 'S') and
                        inarr.dtype != outarr.dtype):

                    inarr_rowsize = inarr[0].size
                    inarr = inarr.flatten().view(outarr.dtype)

                # This is a special case to handle input arrays with
                # non-trivial TDIMn.
                # By design each row of the outarray is 1-D, while each row of
                # the input array may be n-D
                if outarr.ndim > 1:
                    # The normal case where the first dimension is the rows
                    inarr_rowsize = inarr[0].size
                    inarr = inarr.reshape((n, inarr_rowsize))
                    outarr[:, :inarr_rowsize] = inarr
                else:
                    # Special case for strings where the out array only has one
                    # dimension (the second dimension is rolled up into the
                    # strings
                    outarr[:n] = inarr.ravel()
            else:
                outarr[:] = inarr

        # Now replace the original column array references with the new
        # fields
        # This is required to prevent the issue reported in
        # https://github.com/spacetelescope/PyFITS/issues/99
        for idx in range(len(columns)):
            columns._arrays[idx] = data.field(idx)

        return data

    def __repr__(self):
        # Force use of the normal ndarray repr (rather than the new
        # one added for recarray in Numpy 1.10) for backwards compat
        return np.ndarray.__repr__(self)

    def __getitem__(self, key):
        if self._coldefs is None:
            return super(FITS_rec, self).__getitem__(key)

        if isinstance(key, string_types):
            return self.field(key)
        elif isinstance(key, (slice, np.ndarray, tuple, list)):
            # Have to view as a recarray then back as a FITS_rec, otherwise the
            # circular reference fix/hack in FITS_rec.field() won't preserve
            # the slice
            subtype = type(self)
            out = self.view(np.recarray).__getitem__(key).view(subtype)
            out._coldefs = ColDefs(self._coldefs)
            arrays = []
            out._converted = {}
            for idx, name in enumerate(self._coldefs.names):
                #
                # Store the new arrays for the _coldefs object
                #
                arrays.append(self._coldefs._arrays[idx][key])

                # Ensure that the sliced FITS_rec will view the same scaled
                # columns as the original; this is one of the few cases where
                # it is not necessary to use _cache_field()
                if name in self._converted:
                    dummy = self._converted[name]
                    field = np.ndarray.__getitem__(dummy, key)
                    out._converted[name] = field

            out._coldefs._arrays = arrays
            return out

        # if not a slice, do this because Record has no __getstate__.
        # also more efficient.
        else:
            if isinstance(key, int) and key >= len(self):
                raise IndexError("Index out of bounds")

            newrecord = self._record_type(self, key)
            return newrecord

    def __setitem__(self, key, value):
        if self._coldefs is None:
            return super(FITS_rec, self).__setitem__(key, value)

        if isinstance(key, string_types):
            self[key][:] = value
            return

        if isinstance(key, slice):
            end = min(len(self), key.stop or len(self))
            end = max(0, end)
            start = max(0, key.start or 0)
            end = min(end, start + len(value))

            for idx in range(start, end):
                self.__setitem__(idx, value[idx - start])
            return

        if isinstance(value, FITS_record):
            for idx in range(self._nfields):
                self.field(self.names[idx])[key] = value.field(self.names[idx])
        elif isinstance(value, (tuple, list, np.void)):
            if self._nfields == len(value):
                for idx in range(self._nfields):
                    self.field(idx)[key] = value[idx]
            else:
                raise ValueError('Input tuple or list required to have %s '
                                 'elements.' % self._nfields)
        else:
            raise TypeError('Assignment requires a FITS_record, tuple, or '
                            'list as input.')

    def __getslice__(self, start, end):
        return self[slice(start, end)]

    def __setslice__(self, start, end, value):
        self[slice(start, end)] = value

    def copy(self, order='C'):
        """
        The Numpy documentation lies; `numpy.ndarray.copy` is not equivalent to
        `numpy.copy`.  Differences include that it re-views the copied array as
        self's ndarray subclass, as though it were taking a slice; this means
        ``__array_finalize__`` is called and the copy shares all the array
        attributes (including ``._converted``!).  So we need to make a deep
        copy of all those attributes so that the two arrays truly do not share
        any data.
        """

        new = super(FITS_rec, self).copy(order=order)
        new_dict = dict(self.__dict__)
        del new_dict['_col_weakrefs']
        new.__dict__ = copy.deepcopy(new_dict)

        # Re-fill _col_weakrefs
        new.__dict__['_col_weakrefs'] = WeakSet()
        new._coldefs = new._coldefs
        return new

    @property
    def columns(self):
        """
        A user-visible accessor for the coldefs.

        See https://aeon.stsci.edu/ssb/trac/pyfits/ticket/44
        """

        return self._coldefs

    @property
    def _coldefs(self):
        # This used to be a normal internal attribute, but it was changed to a
        # property as a quick and transparent way to work around the reference
        # leak bug fixed in https://github.com/astropy/astropy/pull/4539
        #
        # See the long comment in the Column.array property for more details
        # on this.  But in short, FITS_rec now has a ._col_weakrefs attribute
        # which is a WeakSet of weakrefs to each Column in _coldefs.
        #
        # So whenever ._coldefs is set we also add each Column in the ColDefs
        # to the weakrefs set.  This is an easy way to find out if a Column has
        # any references to it external to the FITS_rec (i.e. a user assigned a
        # column to a variable).  If the column is still in _col_weakrefs then
        # there are other references to it external to this FITS_rec.  We use
        # that information in __del__ to save off copies of the array data
        # for those columns to their Column.array property before our memory
        # is freed.
        return self.__dict__.get('_coldefs')

    @_coldefs.setter
    def _coldefs(self, cols):
        self.__dict__['_coldefs'] = cols
        if isinstance(cols, ColDefs):
            for col in cols.columns:
                self._col_weakrefs.add(col)

    @_coldefs.deleter
    def _coldefs(self):
        try:
            del self.__dict__['_coldefs']
        except KeyError as exc:
            raise AttributeError(exc.args[0])

    def __del__(self):
        try:
            del self._coldefs
        except AttributeError:
            pass
        else:
            if self.dtype.fields is not None:
                for col in self._col_weakrefs:
                    if isinstance(col.array, np.ndarray):
                        col.array = col.array.copy()

    @property
    def names(self):
        """List of column names."""

        if hasattr(self, '_coldefs') and self._coldefs is not None:
            return self._coldefs.names
        elif self.dtype.fields:
            return list(self.dtype.names)
        else:
            return None

    @property
    def formats(self):
        """List of column FITS foramts."""

        if hasattr(self, '_coldefs') and self._coldefs is not None:
            return self._coldefs.formats

        return None

    @property
    def _raw_itemsize(self):
        """
        Returns the size of row items that would be written to the raw FITS
        file, taking into account the possibility of unicode columns being
        compactified.

        Currently for internal use only.
        """

        if _has_unicode_fields(self):
            total_itemsize = 0
            for field in self.dtype.fields.values():
                itemsize = field[0].itemsize
                if field[0].kind == 'U':
                    itemsize = itemsize // 4
                total_itemsize += itemsize
            return total_itemsize
        else:
            # Just return the normal itemsize
            return self.itemsize

    def field(self, key):
        """
        A view of a `Column`'s data as an array.
        """

        # NOTE: The *column* index may not be the same as the field index in
        # the recarray, if the column is a phantom column
        column = self.columns[key]
        name = column.name
        format = column.format

        if format.dtype.itemsize == 0:
            warnings.warn(
                'Field %r has a repeat count of 0 in its format code, '
                'indicating an empty field.' % key)
            return np.array([], dtype=format.dtype)

        # If field's base is a FITS_rec, we can run into trouble because it
        # contains a reference to the ._coldefs object of the original data;
        # this can lead to a circular reference; see ticket #49
        base = self
        while (isinstance(base, FITS_rec) and
                isinstance(base.base, np.recarray)):
            base = base.base
        # base could still be a FITS_rec in some cases, so take care to
        # use rec.recarray.field to avoid a potential infinite
        # recursion
        field = _get_recarray_field(base, name)

        if name not in self._converted:
            recformat = format.recformat
            # TODO: If we're now passing the column to these subroutines, do we
            # really need to pass them the recformat?
            if isinstance(recformat, _FormatP):
                # for P format
                converted = self._convert_p(column, field, recformat)
            else:
                # Handle all other column data types which are fixed-width
                # fields
                converted = self._convert_other(column, field, recformat)

            # Note: Never assign values directly into the self._converted dict;
            # always go through self._cache_field; this way self._converted is
            # only used to store arrays that are not already direct views of
            # our own data.
            self._cache_field(name, converted)
            return converted

        return self._converted[name]

    def _cache_field(self, name, field):
        """
        Do not store fields in _converted if one of its bases is self,
        or if it has a common base with self.

        This results in a reference cycle that cannot be broken since
        ndarrays do not participate in cyclic garbage collection.
        """

        base = field
        while True:
            self_base = self
            while True:
                if self_base is base:
                    return

                if getattr(self_base, 'base', None) is not None:
                    self_base = self_base.base
                else:
                    break

            if getattr(base, 'base', None) is not None:
                base = base.base
            else:
                break

        self._converted[name] = field

    def _update_column_attribute_changed(self, column, idx, attr, old_value,
                                         new_value):
        """
        Update how the data is formatted depending on changes to column
        attributes initiated by the user through the `Column` interface.

        Dispatches column attribute change notifications to individual methods
        for each attribute ``_update_column_<attr>``
        """

        method_name = '_update_column_{0}'.format(attr)
        if hasattr(self, method_name):
            # Right now this is so we can be lazy and not implement updaters
            # for every attribute yet--some we may not need at all, TBD
            getattr(self, method_name)(column, idx, old_value, new_value)

    def _update_column_name(self, column, idx, old_name, name):
        """Update the dtype field names when a column name is changed."""

        dtype = self.dtype
        # Updating the names on the dtype should suffice
        dtype.names = dtype.names[:idx] + (name,) + dtype.names[idx + 1:]

    def _convert_x(self, field, recformat):
        """Convert a raw table column to a bit array as specified by the
        FITS X format.
        """

        dummy = np.zeros(self.shape + (recformat.repeat,), dtype=np.bool_)
        _unwrapx(field, dummy, recformat.repeat)
        return dummy

    def _convert_p(self, column, field, recformat):
        """Convert a raw table column of FITS P or Q format descriptors
        to a VLA column with the array data returned from the heap.
        """

        dummy = _VLF([None] * len(self), dtype=recformat.dtype)
        raw_data = self._get_raw_data()

        if raw_data is None:
            raise IOError(
                "Could not find heap data for the %r variable-length "
                "array column." % column.name)

        for idx in range(len(self)):
            offset = field[idx, 1] + self._heapoffset
            count = field[idx, 0]

            if recformat.dtype == 'a':
                dt = np.dtype(recformat.dtype + str(1))
                arr_len = count * dt.itemsize
                da = raw_data[offset:offset + arr_len].view(dt)
                da = np.char.array(da.view(dtype=dt), itemsize=count)
                dummy[idx] = decode_ascii(da)
            else:
                dt = np.dtype(recformat.dtype)
                arr_len = count * dt.itemsize
                dummy[idx] = raw_data[offset:offset + arr_len].view(dt)
                dummy[idx].dtype = dummy[idx].dtype.newbyteorder('>')
                # Each array in the field may now require additional
                # scaling depending on the other scaling parameters
                # TODO: The same scaling parameters apply to every
                # array in the column so this is currently very slow; we
                # really only need to check once whether any scaling will
                # be necessary and skip this step if not
                # TODO: Test that this works for X format; I don't think
                # that it does--the recformat variable only applies to the P
                # format not the X format
                dummy[idx] = self._convert_other(column, dummy[idx],
                                                 recformat)

        return dummy

    def _convert_ascii(self, column, field):
        """
        Special handling for ASCII table columns to convert columns containing
        numeric types to actual numeric arrays from the string representation.
        """

        format = column.format
        recformat = ASCII2NUMPY[format[0]]
        # if the string = TNULL, return ASCIITNULL
        nullval = str(column.null).strip().encode('ascii')
        if len(nullval) > format.width:
            nullval = nullval[:format.width]

        dummy = np.char.ljust(field, format.width)
        dummy = np.char.replace(dummy, encode_ascii('D'), encode_ascii('E'))
        null_fill = encode_ascii(str(ASCIITNULL).rjust(format.width))
        dummy = np.where(np.char.strip(dummy) == nullval, null_fill, dummy)

        try:
            dummy = np.array(dummy, dtype=recformat)
        except ValueError as exc:
            indx = self._coldefs.names.index(column.name)
            raise ValueError(
                '%s; the header may be missing the necessary TNULL%d '
                'keyword or the table contains invalid data' %
                (exc, indx + 1))

        return dummy

    def _convert_other(self, column, field, recformat):
        """Perform conversions on any other fixed-width column data types.

        This may not perform any conversion at all if it's not necessary, in
        which case the original column array is returned.
        """

        if isinstance(recformat, _FormatX):
            # special handling for the X format
            return self._convert_x(field, recformat)

        (_str, _bool, _number, _scale, _zero, bscale, bzero, dim) = \
            self._get_scale_factors(column)

        indx = self._coldefs.names.index(column.name)

        # ASCII table, convert strings to numbers
        # TODO:
        # For now, check that these are ASCII columns by checking the coldefs
        # type; in the future all columns (for binary tables, ASCII tables, or
        # otherwise) should "know" what type they are already and how to handle
        # converting their data from FITS format to native format and vice
        # versa...
        if not _str and isinstance(self._coldefs, _AsciiColDefs):
            field = self._convert_ascii(column, field)

        # Test that the dimensions given in dim are sensible; otherwise
        # display a warning and ignore them
        if dim:
            # See if the dimensions already match, if not, make sure the
            # number items will fit in the specified dimensions
            if field.ndim > 1:
                actual_shape = field.shape[1:]
                if _str:
                    actual_shape = actual_shape + (field.itemsize,)
            else:
                actual_shape = field.shape[0]

            if dim == actual_shape:
                # The array already has the correct dimensions, so we
                # ignore dim and don't convert
                dim = None
            else:
                nitems = reduce(operator.mul, dim)
                if _str:
                    actual_nitems = field.itemsize
                elif len(field.shape) == 1:  # No repeat count in TFORMn, equivalent to 1
                    actual_nitems = 1
                else:
                    actual_nitems = field.shape[1]
                if nitems > actual_nitems:
                    warnings.warn(
                        'TDIM%d value %s does not fit with the size of '
                        'the array items (%d).  TDIM%d will be ignored.'
                        % (indx + 1, self._coldefs.dims[indx],
                           actual_nitems, indx + 1))
                    dim = None

        # further conversion for both ASCII and binary tables
        # For now we've made columns responsible for *knowing* whether their
        # data has been scaled, but we make the FITS_rec class responsible for
        # actually doing the scaling
        # TODO: This also needs to be fixed in the effort to make Columns
        # responsible for scaling their arrays to/from FITS native values
        if not column.ascii and column.format.p_format:
            format_code = column.format.p_format
        else:
            # TODO: Rather than having this if/else it might be nice if the
            # ColumnFormat class had an attribute guaranteed to give the format
            # of actual values in a column regardless of whether the true
            # format is something like P or Q
            format_code = column.format.format

        if (_number and (_scale or _zero) and not column._physical_values):
            # This is to handle pseudo unsigned ints in table columns
            # TODO: For now this only really works correctly for binary tables
            # Should it work for ASCII tables as well?
            if self._uint:
                if bzero == 2**15 and format_code == 'I':
                    field = np.array(field, dtype=np.uint16)
                elif bzero == 2**31 and format_code == 'J':
                    field = np.array(field, dtype=np.uint32)
                elif bzero == 2**63 and format_code == 'K':
                    field = np.array(field, dtype=np.uint64)
                    bzero64 = np.uint64(2 ** 63)
                else:
                    field = np.array(field, dtype=np.float64)
            else:
                field = np.array(field, dtype=np.float64)

            if _scale:
                np.multiply(field, bscale, field)
            if _zero:
                if self._uint and format_code == 'K':
                    # There is a chance of overflow, so be careful
                    test_overflow = field.copy()
                    try:
                        test_overflow += bzero64
                    except OverflowError:
                        warnings.warn(
                            "Overflow detected while applying TZERO{0:d}. "
                            "Returning unscaled data.".format(indx + 1))
                    else:
                        field = test_overflow
                else:
                    field += bzero
        elif _bool and field.dtype != bool:
            field = np.equal(field, ord('T'))
        elif _str:
            with ignored(UnicodeDecodeError):
                field = decode_ascii(field)

        if dim:
            # Apply the new field item dimensions
            nitems = reduce(operator.mul, dim)
            if field.ndim > 1:
                field = field[:, :nitems]
            if _str:
                fmt = field.dtype.char
                dtype = ('|%s%d' % (fmt, dim[-1]), dim[:-1])
                field.dtype = dtype
            else:
                field.shape = (field.shape[0],) + dim

        return field

    def _get_heap_data(self):
        """
        Returns a pointer into the table's raw data to its heap (if present).

        This is returned as a numpy byte array.
        """

        if self._heapsize:
            raw_data = self._get_raw_data().view(np.ubyte)
            heap_end = self._heapoffset + self._heapsize
            return raw_data[self._heapoffset:heap_end]
        else:
            return np.array([], dtype=np.ubyte)

    def _get_raw_data(self):
        """
        Returns the base array of self that "raw data array" that is the
        array in the format that it was first read from a file before it was
        sliced or viewed as a different type in any way.

        This is determined by walking through the bases until finding one that
        has at least the same number of bytes as self, plus the heapsize.  This
        may be the immediate .base but is not always.  This is used primarily
        for variable-length array support which needs to be able to find the
        heap (the raw data *may* be larger than nbytes + heapsize if it
        contains a gap or padding).

        May return ``None`` if no array resembling the "raw data" according to
        the stated criteria can be found.
        """

        raw_data_bytes = self.nbytes + self._heapsize
        base = self
        while hasattr(base, 'base') and base.base is not None:
            base = base.base
            if hasattr(base, 'nbytes') and base.nbytes >= raw_data_bytes:
                return base

    def _get_scale_factors(self, column):
        """Get all the scaling flags and factors for one column."""

        # TODO: Maybe this should be a method/property on Column?  Or maybe
        # it's not really needed at all...
        _str = column.format.format == 'A'
        _bool = column.format.format == 'L'

        _number = not (_bool or _str)
        bscale = column.bscale
        bzero = column.bzero

        _scale = bscale not in ('', None, 1)
        _zero = bzero not in ('', None, 0)

        # ensure bscale/bzero are numbers
        if not _scale:
            bscale = 1
        if not _zero:
            bzero = 0

        # column._dims gives a tuple, rather than column.dim which returns the
        # original string format code from the FITS header...
        dim = column._dims

        return (_str, _bool, _number, _scale, _zero, bscale, bzero, dim)

    def _scale_back(self, update_heap_pointers=True):
        """
        Update the parent array, using the (latest) scaled array.

        If ``update_heap_pointers`` is `False`, this will leave all the heap
        pointers in P/Q columns as they are verbatim--it only makes sense to do
        this if there is already data on the heap and it can be guaranteed that
        that data has not been modified, and there is not new data to add to
        the heap.  Currently this is only used as an optimization for
        CompImageHDU that does its own handling of the heap.
        """

        # Running total for the new heap size
        heapsize = 0

        for indx, name in enumerate(self.dtype.names):
            column = self._coldefs[indx]
            recformat = column.format.recformat
            raw_field = _get_recarray_field(self, indx)

            # add the location offset of the heap area for each
            # variable length column
            if isinstance(recformat, _FormatP):
                # Irritatingly, this can return a different dtype than just
                # doing np.dtype(recformat.dtype); but this returns the results
                # that we want.  For example if recformat.dtype is 'a' we want
                # an array of characters.
                dtype = np.array([], dtype=recformat.dtype).dtype

                if update_heap_pointers and name in self._converted:
                    # The VLA has potentially been updated, so we need to
                    # update the array descriptors
                    raw_field[:] = 0  # reset
                    npts = [len(arr) for arr in self._converted[name]]

                    raw_field[:len(npts), 0] = npts
                    raw_field[1:, 1] = (np.add.accumulate(raw_field[:-1, 0]) *
                                        dtype.itemsize)
                    raw_field[:, 1][:] += heapsize

                heapsize += raw_field[:, 0].sum() * dtype.itemsize
                # Even if this VLA has not been read or updated, we need to
                # include the size of its constituent arrays in the heap size
                # total

            if isinstance(recformat, _FormatX) and name in self._converted:
                _wrapx(self._converted[name], raw_field, recformat.repeat)
                continue

            _str, _bool, _number, _scale, _zero, bscale, bzero, _ = \
                self._get_scale_factors(column)

            field = self._converted.get(name, raw_field)

            # conversion for both ASCII and binary tables
            if _number or _str:
                if _number and (_scale or _zero) and column._physical_values:
                    dummy = field.copy()
                    if _zero:
                        dummy -= bzero
                    if _scale:
                        dummy /= bscale
                    # This will set the raw values in the recarray back to
                    # their non-physical storage values, so the column should
                    # be mark is not scaled
                    column._physical_values = False
                elif _str or isinstance(self._coldefs, _AsciiColDefs):
                    dummy = field
                else:
                    continue

                # ASCII table, convert numbers to strings
                if isinstance(self._coldefs, _AsciiColDefs):
                    self._scale_back_ascii(indx, dummy, raw_field)
                # binary table string column
                elif isinstance(raw_field, chararray.chararray):
                    self._scale_back_strings(indx, dummy, raw_field)
                # all other binary table columns
                else:
                    if len(raw_field) and isinstance(raw_field[0],
                                                     np.integer):
                        dummy = np.around(dummy)

                    if raw_field.shape == dummy.shape:
                        raw_field[:] = dummy
                    else:
                        # Reshaping the data is necessary in cases where the
                        # TDIMn keyword was used to shape a column's entries
                        # into arrays
                        raw_field[:] = dummy.ravel().view(raw_field.dtype)

                del dummy

            # ASCII table does not have Boolean type
            elif _bool and name in self._converted:
                choices = (np.array([ord('F')], dtype=np.int8)[0],
                           np.array([ord('T')], dtype=np.int8)[0])
                raw_field[:] = np.choose(field, choices)

        # Store the updated heapsize
        self._heapsize = heapsize

    def _scale_back_strings(self, col_idx, input_field, output_field):
        # There are a few possibilities this has to be able to handle properly
        # The input_field, which comes from the _converted column is of dtype
        # 'Sn' (where n in string length) on Python 2--this is maintain the
        # existing user expectation of not being returned Python 2-style
        # unicode strings.  One Python 3 the array in _converted is of dtype
        # 'Un' so that elements read out of the array are normal Python 3 str
        # objects (i.e. unicode strings)
        #
        # At the other end the *output_field* may also be of type 'S' or of
        # type 'U'.  It will *usually* be of type 'S' (regardless of Python
        # version) because when reading an existing FITS table the raw data is
        # just ASCII strings, and represented in Numpy as an S array.
        # However, when a user creates a new table from scratch, they *might*
        # pass in a column containing unicode strings (dtype 'U'), especially
        # on Python 3 where this will be the default.  Therefore the
        # output_field of the raw array is actually a unicode array.  But we
        # still want to make sure the data is encodable as ASCII.  Later when
        # we write out the array we use, in the dtype 'U' case, a different
        # write routine that writes row by row and encodes any 'U' columns to
        # ASCII.

        # If the output_field is non-ASCII we will worry about ASCII encoding
        # later when writing; otherwise we can do it right here
        if input_field.dtype.kind == 'U' and output_field.dtype.kind == 'S':
            try:
                _ascii_encode(input_field, out=output_field)
            except _UnicodeArrayEncodeError as exc:
                raise ValueError(
                    "Could not save column '{0}': Contains characters that "
                    "cannot be encoded as ASCII as required by FITS, starting "
                    "at the index {1!r} of the column, and the index {2} of "
                    "the string at that location.".format(
                        self._coldefs.names[col_idx],
                        exc.index[0] if len(exc.index) == 1 else exc.index,
                        exc.start))
        else:
            # Otherwise go ahead and do a direct copy into--if both are type
            # 'U' we'll handle encoding later
            input_field = input_field.flatten().view(output_field.dtype)
            output_field.flat[:] = input_field

        # Ensure that blanks at the end of each string are
        # converted to nulls instead of spaces, see Trac #15
        # and #111
        _rstrip_inplace(output_field)


    def _scale_back_ascii(self, col_idx, input_field, output_field):
        """
        Convert internal array values back to ASCII table representation.

        The ``input_field`` is the internal representation of the values, and
        the ``output_field`` is the character array representing the ASCII
        output that will be written.
        """

        starts = self._coldefs.starts[:]
        spans = self._coldefs.spans
        format = self._coldefs.formats[col_idx]

        # The the index of the "end" column of the record, beyond
        # which we can't write
        end = super(FITS_rec, self).field(-1).itemsize
        starts.append(end + starts[-1])

        if col_idx > 0:
            lead = starts[col_idx] - starts[col_idx - 1] - spans[col_idx - 1]
        else:
            lead = 0

        if lead < 0:
            warnings.warn('Column %r starting point overlaps the previous '
                          'column.' % (col_idx + 1))

        trail = starts[col_idx + 1] - starts[col_idx] - spans[col_idx]

        if trail < 0:
            warnings.warn('Column %r ending point overlaps the next '
                          'column.' % (col_idx + 1))

        # TODO: It would be nice if these string column formatting
        # details were left to a specialized class, as is the case
        # with FormatX and FormatP
        if 'A' in format:
            _pc = '%-'
        else:
            _pc = '%'

        fmt = ''.join([_pc, format[1:], ASCII2STR[format[0]],
                       (' ' * trail)])

        # Even if the format precision is 0, we should output a decimal point
        # as long as there is space to do so--not including a decimal point in
        # a float value is discouraged by the FITS Standard
        trailing_decimal = (format.precision == 0 and
                            format.format in ('F', 'E', 'D'))

        # not using numarray.strings's num2char because the
        # result is not allowed to expand (as C/Python does).
        for jdx, value in enumerate(input_field):
            value = fmt % value
            if len(value) > starts[col_idx + 1] - starts[col_idx]:
                raise ValueError(
                    "Value %r does not fit into the output's itemsize of "
                    "%s." % (value, spans[col_idx]))

            if trailing_decimal and value[0] == ' ':
                # We have some extra space in the field for the trailing
                # decimal point
                value = value[1:] + '.'

            output_field[jdx] = value

        # Replace exponent separator in floating point numbers
        if 'D' in format:
            output_field.replace(encode_ascii('E'), encode_ascii('D')) def _get_recarray_field(array, key):
    """
    Compatibility function for using the recarray base class's field method.
    This incorporates the legacy functionality of returning string arrays as
    Numeric-style chararray objects.
    """

    # Numpy >= 1.10.dev recarray no longer returns chararrays for strings
    # This is currently needed for backwards-compatibility and for
    # automatic truncation of trailing whitespace
    field = np.recarray.field(array, key)
    if (field.dtype.char in ('S', 'U') and
            not isinstance(field, chararray.chararray)):
        field = field.view(chararray.chararray)
    return field def _has_unicode_fields(array):
    """
    Returns True if any fields in a structured array have Unicode dtype.
    """

    dtypes = (d[0] for d in array.dtype.fields.values())
    return any(d.kind == 'U' for d in dtypes) 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 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 _str_to_num(val):
    """Converts a given string to either an int or a float if necessary."""

    try:
        num = int(val)
    except ValueError:
        # If this fails then an exception should be raised anyways
        num = float(val)
    return num 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 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 DELAYED = _Delayed() class _ValidHDU(_BaseHDU, _Verify):
    """
    Base class for all HDUs which are not corrupted.
    """

    def __init__(self, data=None, header=None, name=None, **kwargs):
        super(_ValidHDU, self).__init__(data=data, header=header)
        if name is not None:
            self.name = name

    @classmethod
    def match_header(cls, header):
        """
        Matches any HDU that is not recognized as having either the SIMPLE or
        XTENSION keyword in its header's first card, but is nonetheless not
        corrupted.

        TODO: Maybe it would make more sense to use _NonstandardHDU in this
        case?  Not sure...
        """

        return first(header.keys()) not in ('SIMPLE', 'XTENSION')

    @property
    def size(self):
        """
        Size (in bytes) of the data portion of the HDU.
        """

        size = 0
        naxis = self._header.get('NAXIS', 0)
        if naxis > 0:
            size = 1
            for idx in range(naxis):
                size = size * self._header['NAXIS' + str(idx + 1)]
            bitpix = self._header['BITPIX']
            gcount = self._header.get('GCOUNT', 1)
            pcount = self._header.get('PCOUNT', 0)
            size = abs(bitpix) * gcount * (pcount + size) // 8
        return size

    def filebytes(self):
        """
        Calculates and returns the number of bytes that this HDU will write to
        a file.
        """

        f = _File()
        # TODO: Fix this once new HDU writing API is settled on
        return self._writeheader(f)[1] + self._writedata(f)[1]

    def fileinfo(self):
        """
        Returns a dictionary detailing information about the locations
        of this HDU within any associated file.  The values are only
        valid after a read or write of the associated file with no
        intervening changes to the `HDUList`.

        Returns
        -------
        dict or None

           The dictionary details information about the locations of
           this HDU within an associated file.  Returns `None` when
           the HDU is not associated with a file.

           Dictionary contents:

           ========== ================================================
           Key        Value
           ========== ================================================
           file       File object associated with the HDU
           filemode   Mode in which the file was opened (readonly, copyonwrite,
                      update, append, ostream)
           hdrLoc     Starting byte location of header in file
           datLoc     Starting byte location of data block in file
           datSpan    Data size including padding
           ========== ================================================
        """

        if hasattr(self, '_file') and self._file:
            return {'file': self._file, 'filemode': self._file.mode,
                    'hdrLoc': self._header_offset, 'datLoc': self._data_offset,
                    'datSpan': self._data_size}
        else:
            return None

    def copy(self):
        """
        Make a copy of the HDU, both header and data are copied.
        """

        if self.data is not None:
            data = self.data.copy()
        else:
            data = None
        return self.__class__(data=data, header=self._header.copy())

    @deprecated('3.2', alternative='the ``.name`` attribute or `Header.set`',
                pending=True)
    def update_ext_name(self, value, comment=None, before=None,
                        after=None, savecomment=False):
        """
        Update the extension name associated with the HDU.

        If the keyword already exists in the Header, it's value and/or comment
        will be updated.  If it does not exist, a new card will be created
        and it will be placed before or after the specified location.
        If no ``before`` or ``after`` is specified, it will be appended at
        the end.

        Parameters
        ----------
        value : str
            Value to be used for the new extension name

        comment : str, optional
            To be used for updating, default=None.

        before : str or int, optional
            Name of the keyword, or index of the `Card` before which the new
            card will be placed in the Header.  The argument ``before`` takes
            precedence over ``after`` if both are specified.

        after : str or int, optional
            Name of the keyword, or index of the `Card` after which
            the new card will be placed in the Header

        savecomment : bool, optional
            When `True`, preserve the current comment for an existing
            keyword.  The argument ``savecomment`` takes precedence over
            ``comment`` if both specified.  If ``comment`` is not
            specified then the current comment will automatically be
            preserved.
        """

        if 'EXTNAME' in self._header and savecomment:
            comment = None

        self._header.set('EXTNAME', value, comment, before, after)
        # This may seem redundant, but the previous header.set call just
        # handles anyone who might use the before/after keywords to set the
        # position of the EXTNAME keyword.  Setting self.name = name does some
        # additional processing on the value such as handling
        # EXTENSION_NAME_CASE_SENSITIVE
        self.name = value

    @deprecated('3.2', alternative='the ``.ver`` attribute or `Header.set`',
                pending=True)
    def update_ext_version(self, value, comment=None, before=None,
                           after=None, savecomment=False):
        """
        Update the extension version associated with the HDU.

        If the keyword already exists in the Header, it's value and/or comment
        will be updated.  If it does not exist, a new card will be created
        and it will be placed before or after the specified location.
        If no ``before`` or ``after`` is specified, it will be appended at
        the end.

        Parameters
        ----------
        value : str
            Value to be used for the new extension version

        comment : str, optional
            To be used for updating; default=None.

        before : str or int, optional
            Name of the keyword, or index of the `Card` before which the new
            card will be placed in the Header.  The argument ``before`` takes
            precedence over ``after`` if both are specified.

        after : str or int, optional
            Name of the keyword, or index of the `Card` after which
            the new card will be placed in the Header.

        savecomment : bool, optional
            When `True`, preserve the current comment for an existing
            keyword.  The argument ``savecomment`` takes precedence over
            ``comment`` if both specified.  If ``comment`` is not
            specified then the current comment will automatically be
            preserved.
        """

        if 'EXTVER' in self._header and savecomment:
            comment = None

        self._header.set('EXTVER', value, comment, before, after)

    def _verify(self, option='warn'):
        errs = _ErrList([], unit='Card')

        is_valid = lambda v: v in [8, 16, 32, 64, -32, -64]

        # Verify location and value of mandatory keywords.
        # Do the first card here, instead of in the respective HDU classes, so
        # the checking is in order, in case of required cards in wrong order.
        if isinstance(self, ExtensionHDU):
            firstkey = 'XTENSION'
            firstval = self._extension
        else:
            firstkey = 'SIMPLE'
            firstval = True

        self.req_cards(firstkey, 0, None, firstval, option, errs)
        self.req_cards('BITPIX', 1, lambda v: (_is_int(v) and is_valid(v)), 8,
                       option, errs)
        self.req_cards('NAXIS', 2,
                       lambda v: (_is_int(v) and v >= 0 and v <= 999), 0,
                       option, errs)

        naxis = self._header.get('NAXIS', 0)
        if naxis < 1000:
            for ax in range(3, naxis + 3):
                self.req_cards('NAXIS' + str(ax - 2), ax,
                               lambda v: (_is_int(v) and v >= 0), 1, option,
                               errs)

            # Remove NAXISj cards where j is not in range 1, naxis inclusive.
            for keyword in self._header:
                if keyword.startswith('NAXIS') and len(keyword) > 5:
                    try:
                        number = int(keyword[5:])
                        if number <= 0 or number > naxis:
                            raise ValueError
                    except ValueError:
                        err_text = ("NAXISj keyword out of range ('%s' when "
                                    "NAXIS == %d)" % (keyword, naxis))

                        def fix(self=self, keyword=keyword):
                            del self._header[keyword]

                        errs.append(
                            self.run_option(option=option, err_text=err_text,
                                            fix=fix, fix_text="Deleted."))

        # Verify that the EXTNAME keyword exists and is a string
        if 'EXTNAME' in self._header:
            if not isinstance(self._header['EXTNAME'], string_types):
                err_text = 'The EXTNAME keyword must have a string value.'
                fix_text = 'Converted the EXTNAME keyword to a string value.'

                def fix(header=self._header):
                    header['EXTNAME'] = str(header['EXTNAME'])

                errs.append(self.run_option(option, err_text=err_text,
                                            fix_text=fix_text, fix=fix))

        # verify each card
        for card in self._header.cards:
            errs.append(card._verify(option))

        return errs

    # TODO: Improve this API a little bit--for one, most of these arguments
    # could be optional
    def req_cards(self, keyword, pos, test, fix_value, option, errlist):
        """
        Check the existence, location, and value of a required `Card`.

        Parameters
        ----------
        keyword : str
            The keyword to validate

        pos : int, callable
            If an ``int``, this specifies the exact location this card should
            have in the header.  Remember that Python is zero-indexed, so this
            means ``pos=0`` requires the card to be the first card in the
            header.  If given a callable, it should take one argument--the
            actual position of the keyword--and return `True` or `False`.  This
            can be used for custom evaluation.  For example if
            ``pos=lambda idx: idx > 10`` this will check that the keyword's
            index is greater than 10.

        test : callable
            This should be a callable (generally a function) that is passed the
            value of the given keyword and returns `True` or `False`.  This can
            be used to validate the value associated with the given keyword.

        fix_value : str, int, float, complex, bool, None
            A valid value for a FITS keyword to to use if the given ``test``
            fails to replace an invalid value.  In other words, this provides
            a default value to use as a replacement if the keyword's current
            value is invalid.  If `None`, there is no replacement value and the
            keyword is unfixable.

        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.

        errlist : list
            A list of validation errors already found in the FITS file; this is
            used primarily for the validation system to collect errors across
            multiple HDUs and multiple calls to `req_cards`.

        Notes
        -----
        If ``pos=None``, the card can be anywhere in the header.  If the card
        does not exist, the new card will have the ``fix_value`` as its value
        when created.  Also check the card's value by using the ``test``
        argument.
        """

        errs = errlist
        fix = None

        try:
            index = self._header.index(keyword)
        except ValueError:
            index = None

        fixable = fix_value is not None

        insert_pos = len(self._header) + 1

        # If pos is an int, insert at the given position (and convert it to a
        # lambda)
        if _is_int(pos):
            insert_pos = pos
            pos = lambda x: x == insert_pos

        # if the card does not exist
        if index is None:
            err_text = "'%s' card does not exist." % keyword
            fix_text = "Fixed by inserting a new '%s' card." % keyword
            if fixable:
                # use repr to accommodate both string and non-string types
                # Boolean is also OK in this constructor
                card = (keyword, fix_value)

                def fix(self=self, insert_pos=insert_pos, card=card):
                    self._header.insert(insert_pos, card)

            errs.append(self.run_option(option, err_text=err_text,
                        fix_text=fix_text, fix=fix, fixable=fixable))
        else:
            # if the supposed location is specified
            if pos is not None:
                if not pos(index):
                    err_text = ("'%s' card at the wrong place (card %d)." %
                                (keyword, index))

                    fix_text = ("Fixed by moving it to the right place "
                                "(card %d)." % insert_pos)

                    def fix(self=self, index=index, insert_pos=insert_pos):
                        card = self._header.cards[index]
                        del self._header[index]
                        self._header.insert(insert_pos, card)

                    errs.append(self.run_option(option, err_text=err_text,
                                fix_text=fix_text, fix=fix))

            # if value checking is specified
            if test:
                val = self._header[keyword]
                if not test(val):
                    err_text = ("'%s' card has invalid value '%s'." %
                                (keyword, val))
                    fix_text = "Fixed by setting a new value '%s'." % fix_value

                    if fixable:
                        def fix(self=self, keyword=keyword, val=fix_value):
                            self._header[keyword] = fix_value

                    errs.append(self.run_option(option, err_text=err_text,
                                fix_text=fix_text, fix=fix, fixable=fixable))

        return errs

    def add_datasum(self, when=None, blocking='standard',
                    datasum_keyword='DATASUM'):
        """
        Add the ``DATASUM`` card to this HDU with the value set to the
        checksum calculated for the data.

        Parameters
        ----------
        when : str, optional
            Comment string for the card that by default represents the
            time when the checksum was calculated

        blocking: str, optional
            "standard" or "nonstandard", compute sum 2880 bytes at a time, or
            not

        datasum_keyword : str, optional
            The name of the header keyword to store the datasum value in;
            this is typically 'DATASUM' per convention, but there exist
            use cases in which a different keyword should be used

        Returns
        -------
        checksum : int
            The calculated datasum

        Notes
        -----
        For testing purposes, provide a ``when`` argument to enable the comment
        value in the card to remain consistent.  This will enable the
        generation of a ``CHECKSUM`` card with a consistent value.
        """

        cs = self._calculate_datasum(blocking)

        if when is None:
            when = 'data unit checksum updated %s' % self._get_timestamp()

        self._header[datasum_keyword] = (str(cs), when)
        return cs

    def add_checksum(self, when=None, override_datasum=False,
                     blocking='standard', checksum_keyword='CHECKSUM',
                     datasum_keyword='DATASUM'):
        """
        Add the ``CHECKSUM`` and ``DATASUM`` cards to this HDU with
        the values set to the checksum calculated for the HDU and the
        data respectively.  The addition of the ``DATASUM`` card may
        be overridden.

        Parameters
        ----------
        when : str, optional
           comment string for the cards; by default the comments
           will represent the time when the checksum was calculated

        override_datasum : bool, optional
           add the ``CHECKSUM`` card only

        blocking: str, optional
            "standard" or "nonstandard", compute sum 2880 bytes at a time, or
            not

        checksum_keyword : str, optional
            The name of the header keyword to store the checksum value in; this
            is typically 'CHECKSUM' per convention, but there exist use cases
            in which a different keyword should be used

        datasum_keyword : str, optional
            See ``checksum_keyword``

        Notes
        -----
        For testing purposes, first call `add_datasum` with a ``when``
        argument, then call `add_checksum` with a ``when`` argument and
        ``override_datasum`` set to `True`.  This will provide consistent
        comments for both cards and enable the generation of a ``CHECKSUM``
        card with a consistent value.
        """

        if not override_datasum:
            # Calculate and add the data checksum to the header.
            data_cs = self.add_datasum(when, blocking,
                                       datasum_keyword=datasum_keyword)
        else:
            # Just calculate the data checksum
            data_cs = self._calculate_datasum(blocking)

        if when is None:
            when = 'HDU checksum updated %s' % self._get_timestamp()

        # Add the CHECKSUM card to the header with a value of all zeros.
        if datasum_keyword in self._header:
            self._header.set(checksum_keyword, '0' * 16, when,
                             before=datasum_keyword)
        else:
            self._header.set(checksum_keyword, '0' * 16, when)

        csum = self._calculate_checksum(data_cs, blocking,
                                        checksum_keyword=checksum_keyword)
        self._header[checksum_keyword] = csum

    def verify_datasum(self, blocking='standard'):
        """
        Verify that the value in the ``DATASUM`` keyword matches the value
        calculated for the ``DATASUM`` of the current HDU data.

        blocking : str, optional
            "standard" or "nonstandard", compute sum 2880 bytes at a time, or
            not

        Returns
        -------
        valid : int
           - 0 - failure
           - 1 - success
           - 2 - no ``DATASUM`` keyword present
        """

        if 'DATASUM' in self._header:
            datasum = self._calculate_datasum(blocking)
            if datasum == int(self._header['DATASUM']):
                return 1
            elif blocking == 'either':
                # i.e. standard failed,  try nonstandard
                return self.verify_datasum(blocking='nonstandard')
            else:
                # Failed with all permitted blocking kinds
                return 0
        else:
            return 2

    def verify_checksum(self, blocking='standard'):
        """
        Verify that the value in the ``CHECKSUM`` keyword matches the
        value calculated for the current HDU CHECKSUM.

        blocking : str, optional
            "standard" or "nonstandard", compute sum 2880 bytes at a time, or
            not

        Returns
        -------
        valid : int
           - 0 - failure
           - 1 - success
           - 2 - no ``CHECKSUM`` keyword present
        """

        if 'CHECKSUM' in self._header:
            if 'DATASUM' in self._header:
                datasum = self._calculate_datasum(blocking)
            else:
                datasum = 0
            checksum = self._calculate_checksum(datasum, blocking)
            if checksum == self._header['CHECKSUM']:
                return 1
            elif blocking == 'either':
                # i.e. standard failed,  try nonstandard
                return self.verify_checksum(blocking='nonstandard')
            else:
                # Failed with all permitted blocking kinds
                return 0
        else:
            return 2

    def _verify_checksum_datasum(self, blocking):
        """
        Verify the checksum/datasum values if the cards exist in the header.
        Simply displays warnings if either the checksum or datasum don't match.
        """

        # NOTE:  private data members _checksum and _datasum are
        # used by the utility script "fitscheck" to detect missing
        # checksums.

        if 'CHECKSUM' in self._header:
            self._checksum = self._header['CHECKSUM']
            self._checksum_comment = self._header.comments['CHECKSUM']
            if not self.verify_checksum(blocking):
                warnings.warn('Checksum verification failed for HDU %s.\n' %
                              ((self.name, self.ver),))
        else:
            self._checksum = None
            self._checksum_comment = None

        if 'DATASUM' in self._header:
            self._datasum = self._header['DATASUM']
            self._datasum_comment = self._header.comments['DATASUM']

            if not self.verify_datasum(blocking):
                warnings.warn('Datasum verification failed for HDU %s.\n' %
                              ((self.name, self.ver),))
        else:
            self._checksum = None
            self._checksum_comment = None
            self._datasum = None
            self._datasum_comment = None

    def _get_timestamp(self):
        """
        Return the current timestamp in ISO 8601 format, with microseconds
        stripped off.

        Ex.: 2007-05-30T19:05:11
        """

        return datetime.datetime.now().isoformat()[:19]

    def _calculate_datasum(self, blocking):
        """
        Calculate the value for the ``DATASUM`` card in the HDU.
        """

        if not self._data_loaded:
            # This is the case where the data has not been read from the file
            # yet.  We find the data in the file, read it, and calculate the
            # datasum.
            if self.size > 0:
                raw_data = self._get_raw_data(self._data_size, 'ubyte',
                                              self._data_offset)
                return self._compute_checksum(raw_data, blocking=blocking)
            else:
                return 0
        elif self.data is not None:
            return self._compute_checksum(self.data.view('ubyte'),
                                          blocking=blocking)
        else:
            return 0

    def _calculate_checksum(self, datasum, blocking,
                            checksum_keyword='CHECKSUM'):
        """
        Calculate the value of the ``CHECKSUM`` card in the HDU.
        """

        old_checksum = self._header[checksum_keyword]
        self._header[checksum_keyword] = '0' * 16

        # Convert the header to a string.
        s = str(self._header)

        # Calculate the checksum of the Header and data.
        cs = self._compute_checksum(np.fromstring(s, dtype='ubyte'), datasum,
                                    blocking=blocking)

        # Encode the checksum into a string.
        s = self._char_encode(~cs)

        # Return the header card value.
        self._header[checksum_keyword] = old_checksum

        return s

    def _compute_checksum(self, data, sum32=0, blocking="standard"):
        """
        Compute the ones-complement checksum of a sequence of bytes.

        Parameters
        ----------
        data
            a memory region to checksum

        sum32
            incremental checksum value from another region

        blocking
            "standard", "nonstandard", or "either"
            selects the block size on which to perform checksumming,
            originally the blocksize was chosen incorrectly.  "nonstandard"
            selects the original approach,  "standard" selects the
            interoperable blocking size of 2880 bytes.  In the context of
            _compute_checksum, "either" is synonymous with "standard".

        Returns
        -------
        ones complement checksum
        """

        blocklen = {'standard': 2880,
                    'nonstandard': len(data),
                    'either': 2880,  # do standard first
                    True: 2880}[blocking]

        sum32 = np.uint32(sum32)
        for i in range(0, len(data), blocklen):
            length = min(blocklen, len(data) - i)   # ????
            sum32 = self._compute_hdu_checksum(data[i:i + length], sum32)
        return sum32

    def _compute_hdu_checksum(self, data, sum32=0):
        """
        Translated from FITS Checksum Proposal by Seaman, Pence, and Rots.
        Use uint32 literals as a hedge against type promotion to int64.

        This code should only be called with blocks of 2880 bytes
        Longer blocks result in non-standard checksums with carry overflow
        Historically,  this code *was* called with larger blocks and for that
        reason still needs to be for backward compatibility.
        """

        u8 = np.uint32(8)
        u16 = np.uint32(16)
        uFFFF = np.uint32(0xFFFF)

        if data.nbytes % 2:
            last = data[-1]
            data = data[:-1]
        else:
            last = np.uint32(0)

        data = data.view('>u2')

        hi = sum32 >> u16
        lo = sum32 & uFFFF
        hi += np.add.reduce(data[0::2], dtype=np.uint64)
        lo += np.add.reduce(data[1::2], dtype=np.uint64)

        if (data.nbytes // 2) % 2:
            lo += last << u8
        else:
            hi += last << u8

        hicarry = hi >> u16
        locarry = lo >> u16

        while hicarry or locarry:
            hi = (hi & uFFFF) + locarry
            lo = (lo & uFFFF) + hicarry
            hicarry = hi >> u16
            locarry = lo >> u16

        return (hi << u16) + lo

    # _MASK and _EXCLUDE used for encoding the checksum value into a character
    # string.
    _MASK = [0xFF000000,
             0x00FF0000,
             0x0000FF00,
             0x000000FF]

    _EXCLUDE = [0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
                0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60]

    def _encode_byte(self, byte):
        """
        Encode a single byte.
        """

        quotient = byte // 4 + ord('0')
        remainder = byte % 4

        ch = np.array(
            [(quotient + remainder), quotient, quotient, quotient],
            dtype='int32')

        check = True
        while check:
            check = False
            for x in self._EXCLUDE:
                for j in [0, 2]:
                    if ch[j] == x or ch[j + 1] == x:
                        ch[j] += 1
                        ch[j + 1] -= 1
                        check = True
        return ch

    def _char_encode(self, value):
        """
        Encodes the checksum ``value`` using the algorithm described
        in SPR section A.7.2 and returns it as a 16 character string.

        Parameters
        ----------
        value
            a checksum

        Returns
        -------
        ascii encoded checksum
        """

        value = np.uint32(value)

        asc = np.zeros((16,), dtype='byte')
        ascii = np.zeros((16,), dtype='byte')

        for i in range(4):
            byte = (value & self._MASK[i]) >> ((3 - i) * 8)
            ch = self._encode_byte(byte)
            for j in range(4):
                asc[4 * j + i] = ch[j]

        for i in range(16):
            ascii[i] = asc[(i + 15) % 16]

        return decode_ascii(ascii.tostring()) class ExtensionHDU(_ValidHDU):
    """
    An extension HDU class.

    This class is the base class for the `TableHDU`, `ImageHDU`, and
    `BinTableHDU` classes.
    """

    _extension = ''

    @classmethod
    def match_header(cls, header):
        """
        This class should never be instantiated directly.  Either a standard
        extension HDU type should be used for a specific extension, or
        NonstandardExtHDU should be used.
        """

        raise NotImplementedError

    def writeto(self, name, output_verify='exception', clobber=False,
                checksum=False):
        """
        Works similarly to the normal writeto(), but prepends a default
        `PrimaryHDU` are required by extension HDUs (which cannot stand on
        their own).
        """

        from pyfits.hdu.hdulist import HDUList
        from pyfits.hdu.image import PrimaryHDU

        hdulist = HDUList([PrimaryHDU(), self])
        hdulist.writeto(name, output_verify, clobber=clobber,
                        checksum=checksum)

    def _verify(self, option='warn'):

        errs = super(ExtensionHDU, self)._verify(option=option)

        # Verify location and value of mandatory keywords.
        naxis = self._header.get('NAXIS', 0)
        self.req_cards('PCOUNT', naxis + 3, lambda v: (_is_int(v) and v >= 0),
                       0, option, errs)
        self.req_cards('GCOUNT', naxis + 4, lambda v: (_is_int(v) and v == 1),
                       1, option, errs)

        return errs
import contextlib
import csv
import os
import re
import sys
import textwrap
import warnings
import numpy as np
from numpy import char as chararray
from ..extern import six
from ..extern.six import string_types
from ..extern.six.moves import xrange as range
from ..column import (FITS2NUMPY, KEYWORD_NAMES, KEYWORD_TO_ATTRIBUTE,
                      ATTRIBUTE_TO_KEYWORD, TDEF_RE, Column, ColDefs,
                      _AsciiColDefs, _FormatP, _FormatQ, _makep,
                      _parse_tformat, _scalar_to_format, _convert_format,
                      _cmp_recformats, _get_index)
from ..fitsrec import FITS_rec, _get_recarray_field, _has_unicode_fields
from ..header import Header
from ..py3compat import ignored
from ..util import lazyproperty, _is_int, _str_to_num, _pad_length, deprecated
from .base import DELAYED, _ValidHDU, ExtensionHDU
        if self._data_loaded:
            del self.data

    def _update_column_removed(self, columns, col_idx):
        """
        Update the data upon removal of a column through the `ColDefs`
        interface.
        """

        # For now this doesn't do anything fancy--it just deletes the data
        # attribute so that it is forced to be recreated again.  It doesn't
        # change anything on the existing data recarray (this is also how this
        # worked before introducing the notifier interface)
        if self._data_loaded:
            del self.data


class _TableBaseHDU(ExtensionHDU, _TableLikeHDU):
    """
    FITS table extension base HDU class.
    """

    _manages_own_heap = False
    """
    This flag implies that when writing VLA tables (P/Q format) the heap
    pointers that go into P/Q table columns should not be reordered or
    rearranged in any way by the default heap management code.

    This is included primarily as an optimization for compressed image HDUs
    which perform their own heap maintenance.
    """

    def __init__(self, data=None, header=None, name=None, uint=False):
        """
        Parameters
        ----------
        header : Header instance
            header to be used

        data : array
            data to be used

        name : str
            name to be populated in ``EXTNAME`` keyword

        uint : bool, optional
            set to `True` if the table contains unsigned integer columns.
        """

        super(_TableBaseHDU, self).__init__(data=data, header=header,
                                            name=name)

        if header is not None and not isinstance(header, Header):
            raise ValueError('header must be a Header object.')
        self._uint = uint
        if data is DELAYED:
            # this should never happen
            if header is None:
                raise ValueError('No header to setup HDU.')

            # if the file is read the first time, no need to copy, and keep it
            # unchanged
            else:
                self._header = header
        else:
            # construct a list of cards of minimal header
            cards = [
                ('XTENSION',      '', ''),
                ('BITPIX',         8, 'array data type'),
                ('NAXIS',          2, 'number of array dimensions'),
                ('NAXIS1',         0, 'length of dimension 1'),
                ('NAXIS2',         0, 'length of dimension 2'),
                ('PCOUNT',         0, 'number of group parameters'),
                ('GCOUNT',         1, 'number of groups'),
                ('TFIELDS',        0, 'number of table fields')]

            if header is not None:
                # Make a "copy" (not just a view) of the input header, since it
                # may get modified.  the data is still a "view" (for now)
                hcopy = header.copy(strip=True)
                cards.extend(hcopy.cards)

            self._header = Header(cards)

            if isinstance(data, np.ndarray) and data.dtype.fields is not None:
                # self._data_type is FITS_rec.
                if isinstance(data, self._data_type):
                    self.data = data
                else:
                    # Just doing a view on the input data screws up unsigned
                    # columns, so treat those more carefully.
                    # TODO: I need to read this code a little more closely
                    # again, but I think it can be simplified quite a bit with
                    # the use of some appropriate utility functions
                    update_coldefs = {}
                    if 'u' in [data.dtype[k].kind for k in data.dtype.names]:
                        self._uint = True
                        bzeros = {2: np.uint16(2**15), 4: np.uint32(2**31),
                                  8: np.uint64(2**63)}

                        new_dtype = [
                            (k, data.dtype[k].kind.replace('u', 'i') +
                            str(data.dtype[k].itemsize))
                            for k in data.dtype.names]

                        new_data = np.zeros(data.shape, dtype=new_dtype)

                        for k in data.dtype.fields:
                            dtype = data.dtype[k]
                            if dtype.kind == 'u':
                                new_data[k] = data[k] - bzeros[dtype.itemsize]
                                update_coldefs[k] = bzeros[dtype.itemsize]
                            else:
                                new_data[k] = data[k]
                        self.data = new_data.view(self._data_type)
                        # Uck...
                        self.data._uint = True
                    else:
                        self.data = data.view(self._data_type)
                    for k in update_coldefs:

                        indx = _get_index(self.data.names, k)