
    HR-e>             	          d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 ddlmZ ddlmZmZmZmZ ddlmZ ddlmZmZmZmZmZ d	Z ej         ed
                    Z e ee e dd                              Z!dZ"ej#        Z#g dZ$ G d d          Z%e j&        j'        (                    e%           e j&        j)        (                    e%            G d d          Z* G d d          Z+ G d de j&        j,                  Z- G d d          Z. G d de.          Z/ G d de.          Z0d Z1d Z2d"d Z3d! Z4dS )#    N)
isiterable)AstropyUserWarning   )parse_header)KEYWORD_LENGTH	UNDEFINEDCard_pad)_File)decode_asciiencode_asciifileobj_closedfileobj_is_binary	path_likei@  zA(?:(?P<valid>END {77}) *)|(?P<invalid>END$|END {0,76}[^A-Z0-9_-])       zPEND                                                                             )HeaderzHeader.commentszHeader.fromtextfilezHeader.totextfilez
Header.setzHeader.updatec                      e Zd ZdZg dfdZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zed             Zed             Zed             Zej        d             ZedGd            ZedHd            Zed             Zed             Zed             ZdHdZdIdZedJd            ZdKdZd Z dJd Z!d! Z"d" Z#edLd$            Z$dLd%Z%dMd&Z&d' Z'd( Z(d) Z)d* Z*d+ Z+dLd,Z,d- Z-dNd.Z.	 	 	 	 	 	 	 dOd/Z/d0 Z0dPd1Z1dQd2Z2dKd3Z3dJd4Z4dPd5Z5dPd6Z6dRd7Z7d8 Z8ed9             Z9ed:             Z:d; Z;d< Z<d= Z=dSd>Z>dTd?Z?d@ Z@dA ZAdB ZBdC ZCdD ZDdE ZEdPdFZFd#S )Ur   a  
    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 Astropy documentation for more details on working with headers.

    Notes
    -----
    Although FITS keywords must be exclusively upper case, retrieving an item
    in a `Header` object is case insensitive.
    Fc                 ,   |                                   t          |t                    r|r|                                }|j        }n)t          |t
                    r|                                }|D ]}|                     |d           d| _        dS )a=  
        Construct a `Header` from an iterable and/or text file.

        Parameters
        ----------
        cards : list of `Card`, optional
            The cards to initialize the header with. Also allowed are other
            `Header` (or `dict`-like) objects.

            .. versionchanged:: 1.2
                Allowed ``cards`` to be a `dict`-like object.

        copy : bool, optional

            If ``True`` copies the ``cards`` if they were another `Header`
            instance.
            Default is ``False``.

            .. versionadded:: 1.3
        TendFN)	clear
isinstancer   copycardsdictitemsappend	_modified)selfr   r   cards       6lib/python3.11/site-packages/astropy/io/fits/header.py__init__zHeader.__init__`   s    * 	

eV$$ 	" %

KEEt$$ 	"KKMME 	( 	(DKK$K''''    c                 *    t          | j                  S N)len_cardsr    s    r"   __len__zHeader.__len__   s    4;r$   c              #   0   K   | j         D ]}|j        V  d S r&   r(   keywordr    r!   s     r"   __iter__zHeader.__iter__   s2      K 	 	D,	 	r$   c                     || j         v s	|| j        v rdS 	 |                     |           n# t          t          f$ r Y dS w xY wdS )NTF)_keyword_indices_rvkc_indices
_cardindexKeyError
IndexErrorr    r-   s     r"   __contains__zHeader.__contains__   sj    d+++w$:L/L/L
 4	OOG$$$$*% 	 	 	55	ts   , A Ac                     t          |t                    r*                     d  j        |         D                       S                      |          r4                      fd                     |          D                       S t          |t                    rS|                                }|                                t          v r$|                                }t           |          S t          |t                    r	|d         }n|} j                             |                   }|j        ||j        k    r|j        S |j        }|t"          k    rd S |S )Nc                 6    g | ]}t          j         |          S  r   .0cs     r"   
<listcomp>z&Header.__getitem__.<locals>.<listcomp>   s     "J"J"JA49Q<<"J"J"Jr$   c                 N    g | ]!}t          j         j        |                   "S r:   )r   r(   )r=   idxr    s     r"   r?   z&Header.__getitem__.<locals>.<listcomp>   s*    QQQ4;s+,,QQQr$   r   )r   slice	__class__r(   _haswildcard_wildcardmatchstrstripupper_commentary_keywords_HeaderCommentaryCardstupler3   field_specifier
rawkeywordrawvaluevaluer   )r    keyr-   r!   rO   s   `    r"   __getitem__zHeader.__getitem__   sU   c5!! 	9>>"J"JS9I"J"J"JKKKs## 		9>>QQQQ8K8KC8P8PQQQ   S!! 	9))++Cyy{{222iikk-dC888c5!! 	!fGGG{4??3//0+4?0J0J = 
I4r$   c                    |                      |||           rd S t          |t                    rot          |          dk    rt	          d          t          |          dk    r|d         d }}|t
          }n(t          |          dk    r|\  }}|t
          }|d}nd }d }t          |t          j                  r| j        |         }n5t          |t                    r | j        | 	                    |                   }|t
          }|r"||_
        |||_        |j        r	d| _        d S d S |                     |||f           d S )N   zA 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.r   r    T)
_set_slicer   rK   r'   
ValueErrorr   numbersIntegralr(   r3   rO   commentr   _update)r    rP   rO   rY   r!   s        r"   __setitem__zHeader.__setitem__   sk   ??3t,, 	FeU## 	5zzA~~ D  
 5zzQ!&q4w=%EUq!&w=%E? GGc7+,, 	5;s#DDU## 	5;ts334D=E 		0DJ"&~ &!%& &
 LL#ug./////r$   c                    t          |t                    s|                     |          rt          |t                    rKt          |                    t          |                      }|j        r|j        dk     rt          |          }n|                     |          }t          |          D ]}| |= d S t          |t                    r_t          j        |          }| j        }|| j        vr| j        }||vrt          d| d          t          ||                   D ]}| |= d S |                     |          }| j        |         }|j        }| j        |= t          j        |          }| j        |         }|                    |           |s| j        |= |j        6| j        |j                 }|                    |           |s| j        |j        = |                     |d           d| _        d S )Nr   	Keyword '' not found.F)	incrementT)r   rB   rD   rangeindicesr'   stepreversedrE   rF   r	   normalize_keywordr1   r2   r4   r3   r(   r-   removerL   rM   _updateindicesr   )r    rP   ra   rA   r!   r-   s         r"   __delitem__zHeader.__delitem__   s   c5!! "	T%6%6s%;%; "	 #u%% 3SYY!7!78 8 01&w//G--c22((  IIFS!! 	(--C+G$///,'!! <3<<<===--  IIFooc""{3,K(11'0s 	/%g. +(9GNN3 8&t7 	C5111r$   c                 2    |                      ddd          S )N
Fsependcardpaddingtostringr)   s    r"   __repr__zHeader.__repr__  s    }}ue}DDDr$   c                 *    |                                  S r&   rn   r)   s    r"   __str__zHeader.__str__      }}r$   c                 B    t          |           t          |          k    S )zg
        Two Headers are equal only if they have the exact same string
        representation.
        rF   r    others     r"   __eq__zHeader.__eq__   s    
 4yyCJJ&&r$   c                 \    |                      d          }|                    |           |S )NF)rG   )r   extend)r    rw   temps      r"   __add__zHeader.__add__'  s,    yyuy%%Er$   c                 0    |                      |           | S r&   )rz   rv   s     r"   __iadd__zHeader.__iadd__,  s    Er$   c                 *    |                                  S r&   )r/   r)   s    r"   _ipython_key_completions_z Header._ipython_key_completions_0  rs   r$   c                      t          |           S )z
        The underlying physical cards that make up this Header; it can be
        looked at, but it should not be modified directly.
        )_CardAccessorr)   s    r"   r   zHeader.cards3  s     T"""r$   c                      t          |           S )aS  
        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'

        )_HeaderCommentsr)   s    r"   commentszHeader.comments;  s     t$$$r$   c                 p    t          d | j        D                       }|r
d| j        d<   | j        d         S )z
        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.
        c              3   $   K   | ]}|j         V  d S r&   )r   r<   s     r"   	<genexpr>z#Header._modified.<locals>.<genexpr>S  s$      >>QQ[>>>>>>r$   Tr   )anyr(   __dict__)r    modified_cardss     r"   r   zHeader._modifiedL  sE     >>$+>>>>> 	. *.DM+&}[))r$   c                     || j         d<   d S )Nr   r   )r    vals     r"   r   zHeader._modified[  s    %(k"""r$   rT   c                    g }t          |                              t                    }t          |t                    r6d}d}t
                              d          }|                    d          }d}nd}d}t
          }d}d	}	g }
|	t          |          k     r|r|	t          j	        z   }n7	 |
                    ||	          }n# t          $ r t          |          }Y nw xY w||	|         }|t          |          z   }	|
r^|d
d         |k    r|
                    |           |                    t          j        |                    |
                               |r
||k    rg }
nLn4|                    |          d	                                         |k    rg }
n|g}
|	t          |          k     |
r:|                    t          j        |                    |
                               |                     |          S )a  
        Creates an HDU header from a byte string containing the entire header
        data.

        Parameters
        ----------
        data : str or bytes
           String or bytes containing the entire header.  In the case of bytes
           they will be decoded using latin-1 (only plain ASCII characters are
           allowed in FITS headers but latin-1 allows us to retain any invalid
           bytes that might appear in malformatted FITS files).

        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).  In general this is only used in cases where a header was
            printed as text (e.g. with newlines after each card) and you want
            to create a new `Header` from it by copy/pasting.

        Examples
        --------
        >>> from astropy.io.fits import Header
        >>> hdr = Header({'SIMPLE': True})
        >>> Header.fromstring(hdr.tostring()) == hdr
        True

        If you want to create a `Header` from printed text it's not necessary
        to have the exact binary structure as it would appear in a FITS file,
        with the full 80 byte card length.  Rather, each "card" can end in a
        newline and does not have to be padded out to a full card length as
        long as it "looks like" a FITS header:

        >>> hdr = Header.fromstring("""\
        ... SIMPLE  =                    T / conforms to FITS standard
        ... BITPIX  =                    8 / array data type
        ... NAXIS   =                    0 / number of array dimensions
        ... EXTEND  =                    T
        ... """, sep='\n')
        >>> hdr['SIMPLE']
        True
        >>> hdr['BITPIX']
        8
        >>> len(hdr)
        4

        Returns
        -------
        `Header`
            A new `Header` instance.
        s   CONTINUEs   ENDasciilatin1r$   CONTINUEENDrT   r   N   )setissubsetVALID_HEADER_CHARSr   bytesEND_CARDencoder'   r	   lengthindexrV   r   
fromstringjoinsplitrstrip
_fromcards)clsdatark   r   require_full_cardlengthr   r   end_cardemptyrA   imageend_idx
next_images                r"   r   zHeader.fromstring_  s    h  #&c(("3"34F"G"GdE"" 	 #HCw//H**X&&CEE!HCHE CIIoo& (+("jjc22GG! ( ( (!$iiGGG( c'k*JCHH$C Abqb>X--LL,,,T_UZZ->->??@@@& ))E * ##C((+2244;;ELE7 CIIoo<  	=LLE):):;;<<<~~e$$$s   -C C C Tc                    d}t          t                    rEt          j                                      |rt          d          nt          d          d}	 t                    }fd}|                     |||||          d         |r                                 S S # |r                                 w w xY w)a}  
        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
            `OSError` 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.
        Fr   )encodingrbTc              3   H   K   	                      |           }|r|V  nd S r&   )read)nbytesr   fileobjs     r"   
block_iterz#Header.fromfile.<locals>.block_iter
  s:      "<<//D "



r$   r   )	r   r   ospath
expanduseropenr   _from_blocksclose)r   r   rk   rl   rm   
close_file	is_binaryr   s    `      r"   fromfilezHeader.fromfile  s    B 
gy)) 	 g((11G .w:::w--J	 )'22I     ##J	3QQRST   z   s   2B) )Cc                 P    |             }t          |          D ]\  }}|j                            |           t          j        |j                  }|j        |                             |           |j        %|j        |j	                                     |           d|_
        |S NF)	enumerater(   r   r	   rd   r-   r1   rL   r2   rM   r   )r   r   headerrA   r!   r-   s         r"   r   zHeader._fromcards  s    "5)) 	B 	BICM  &&&,T\::G#G,33C888#/$T_5<<SAAA r$   c                    t          |          }t          j        t          |          z   } ||          }	 t	          |          }	n# t
          $ r t                      w xY w|st          |	          }	g }
d}d}	 |                     |	|          \  }}	|
	                    t          |	                     |rn:	 t	          |          }	n# t
          $ r d}Y nw xY w|	sd}n|st          |	          }	xd                    |
          }t          ||||           |s|r|rt          d          ||                     ||          fS )a_  
        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.
        FTrT   )check_block_sizezHeader missing END card.rk   )_block_sizer	   r   r'   nextStopIterationEOFErrorr   _find_end_cardr   r   r   _check_paddingOSErrorr   )r   r   r   rk   rl   rm   actual_block_sizeclenblocksblockread_blocksis_eof	end_found
header_strs                 r"   r   zHeader._from_blocks%  s     (,,{SXX%-..	LLEE 	 	 	**	  	( !''E		,"11%>>Iu|E22333 V       ,$U++)	,, WW[))
z#4fwWWWW 	6V 	6 	6 45553>>*#>>>>>s   A A!;C CCc                    t                               |          D ]%}|                                |z  dk    r|                    d          r|                                }||dz   ||z   dz
                                           }|rPt          |                              d          }t          j        d	                    |          t                     n#t          j        dt           dt                     |d|         t          t                    z   ||t          t                    z   d         z   }d	|fc S d
|fS )z
        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.
        r   invalid   ubz]Unexpected bytes trailing END keyword: {}; these bytes will be replaced with spaces on write.zMissing 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 z bytes.NTF)HEADER_END_REfinditerstartgroupr   reprlstripwarningswarnformatr   
BLOCK_SIZEr   r   r'   )r   r   card_lenmooffsettrailings         r"   r   zHeader._find_end_cardk  sl     ((// $	 $	B xxzzH$)) xx	""  !fx.?!.C!CDKKMM #H~~44T::HMGGMvhGWGW*    MS?IS S S +	   '6'N"8,,-FS]]24456  ;e|r$   c                 Z   g }| j         D ]P}t          |          }|r=|                    |dt          j                            |t          j        d         }|=Q|                    |          }|r||t          d          z   z  }|r"|dt          t          |                    z  z  }|S )a  
        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
        -------
        str
            A string representing a FITS header.
        Nr    )	r(   rF   r   r	   r   r   r
   _pad_lengthr'   )r    rk   rl   rm   linesr!   ss          r"   ro   zHeader.tostring  s    8 K 	% 	%DD		A  %Q}}-...dkmm$  % HHUOO 	#tE{{""A 	+{3q66****Ar$   c                 z   t          |          }t          |t                    st          |d|          }	 |                     |||          }t	          |          }|rVt          |          |z  dk    r@t          d                    t          |          |z
  t          z   t                              |	                                 |
                    |                    d                     |	                                 |r|                                 dS dS # |r|                                 w w xY w)a  
        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 : path-like or file-like, 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

        overwrite : bool, optional
            If ``True``, overwrite the output file if it exists. Raises an
            ``OSError`` if ``False`` and the output file exists. Default is
            ``False``.
        ostream)mode	overwriterj   r   z6Header size ({}) is not a multiple of block size ({}).r   N)r   r   r   ro   r   r'   r   r   r   flushwriter   r   )	r    r   rk   rl   rm   r   r   r   r   s	            r"   tofilezHeader.tofile  s8   @ $G,,
'5)) 	JG)yIIIG	 ]]sGW]MMF +C 0 0 3v;;)::a??LSSF&77*Dj    MMOOOMM&--00111MMOOO     z   s   CD! !D:c                 4    |                      |d|d          S )a  
        Read a header from a simple text file or file-like object.

        Equivalent to::

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

        See Also
        --------
        fromfile
        ri   Frj   )r   )r   r   rl   s      r"   fromtextfilezHeader.fromtextfile  s     ||Gw|NNNr$   c                 :    |                      |d|d|           dS )a  
        Write the header as text to a file or a file-like object.

        Equivalent to::

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

        See Also
        --------
        tofile
        ri   F)rk   rl   rm   r   N)r   )r    r   rl   r   s       r"   
totextfilezHeader.totextfile  s4     	w 	 	
 	
 	
 	
 	
r$   c                     g | _         t          j        t                    | _        t          j        t                    | _        dS )z3
        Remove all cards from the header.
        N)r(   collectionsdefaultdictlistr1   r2   r)   s    r"   r   zHeader.clear  s7      + 7 = =(4T::r$   c                 z    |                      d | j        D                       }|r|                                 |S )a   
        Make a copy of the :class:`Header`.

        .. versionchanged:: 1.3
            `copy.copy` and `copy.deepcopy` on a `Header` will call this
            method.

        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.
        c              3   >   K   | ]}t          j         |          V  d S r&   r;   )r=   r!   s     r"   r   zHeader.copy.<locals>.<genexpr>;  s*      EETYt__EEEEEEr$   )rC   r(   rG   )r    rG   tmps      r"   r   zHeader.copy'  s@    ( nnEEEEEEE 	IIKKK
r$   c                 *    |                                  S r&   r;   r)   s    r"   __copy__zHeader.__copy__@      yy{{r$   c                 *    |                                  S r&   r;   )r    argskwargss      r"   __deepcopy__zHeader.__deepcopy__C  r   r$   Nc                      |             }t          |t                    s|f}|D ]}|                    |f|z              |S )au  
        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.
        )r   rK   r   )r   iterablerO   drP   s        r"   fromkeyszHeader.fromkeysF  sW    . CEE%'' 	HE 	% 	%CHHcVe^$$$$r$   c                 F    	 | |         S # t           t          f$ r |cY S w xY w)a~  
        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: str, number, complex, bool, or ``astropy.io.fits.card.Undefined``
            The value associated with the given keyword, or the default value
            if the keyword is not in the header.
        r4   r5   r    rP   defaults      r"   getz
Header.getd  s:    (	9*% 	 	 	NNN	s   
   c                    t          |          t          k    rAt          j                            |          r"|| j        vrt          |||          }|j        }n|}|t          vre|| v ra|| j        |         }|| |         }||f| |<   ||;| j	        | 
                    |                   }|                     |||d           dS dS |||                     |||f||           dS ||f| |<   dS )a  
        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 Astropy v0.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.

        NT)beforeafterreplacer  r  )r'   r   r	   _keywd_FSC_REmatchr1   r-   rI   r   r(   r3   _relativeinsert)	r    r-   rO   rY   r  r  new_cardnew_keywordr!   s	            r"   r   z
Header.set}  s6   z LLN**"((11 +t444GUG44H"*KK!K222{d7J7J-0}W"G,DM!U%6{4??7#;#;<$$T&t$TTTTT &7%6 5#4  '5'!:6QV WWWWW"G,DMMMr$   c              #   b   K   | j         D ]$}|j        |j        t          k    rdn|j        fV  %dS )zLike :meth:`dict.items`.N)r(   r-   rO   r   r.   s     r"   r   zHeader.items  sM      K 	P 	PD,
i(?(?TZOOOOO	P 	Pr$   c              #   0   K   | j         D ]}|j        V  dS )zv
        Like :meth:`dict.keys`--iterating directly over the `Header`
        instance has the same behavior.
        Nr,   r.   s     r"   keyszHeader.keys  s4      
 K 	 	D,	 	r$   c              #   T   K   | j         D ]}|j        t          k    rdn|j        V  dS )zLike :meth:`dict.values`.N)r(   rO   r   r.   s     r"   valueszHeader.values  sF      K 	B 	BD*	11$$tzAAAA	B 	Br$   c                 &   t          |          dk    rt          dt          |                     t          |          dk    rd}n|d         }	 | |         }n3# t          t          f$ r t          |          dk    r
|d         cY S  w xY w| |= |S )z
        Works like :meth:`list.pop` if no arguments or an index argument are
        supplied; otherwise works like :meth:`dict.pop`.
        rS   z-Header.pop expected at most 2 arguments, got r   r   )r'   	TypeErrorr4   r5   )r    r   rP   rO   s       r"   popz
Header.pop  s    
 t99q==WCPTIIWWXXXt99>>CCq'C	IEE*% 	 	 	4yyA~~Aw	
 Is   A ,B	Bc                     	 t          |                                           \  }}n# t          $ r t          d          w xY w| |= ||fS )z Similar to :meth:`dict.popitem`.zHeader is empty)r   r   r   r4   )r    kvs      r"   popitemzHeader.popitem  s\    	.

%%DAqq 	. 	. 	.,---	.G!ts	   $' Ac                 P    	 | |         S # t           t          f$ r || |<   Y nw xY w|S )z#Similar to :meth:`dict.setdefault`.r  r  s      r"   
setdefaultzHeader.setdefault  sC    	 9*% 	  	  	 DIII	 s   
 ##c                     |r	|d         }nd} fd}|nWt          |t                    r!|j        D ]}                     |           n!t	          |d          r'|                                D ]\  }} |||           nt	          |d          r*|                                D ]} ||||                    nt          |          D ]\  }}t          |t                    r                     |           0t          |t                    r:dt          |          cxk     rdk    r n n                     t          |            t          d                    |                    |r                     |           dS dS )	a  
        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})

        .. warning::
            As this method works similarly to `dict.update` it is very
            different from the ``Header.update()`` method in Astropy v0.1.
            Use of the old API was
            **deprecated** for a long time and is now removed. Most uses of the
            old API can be replaced as follows:

            * Replace ::

                  header.update(keyword, value)

              with ::

                  header[keyword] = value

            * Replace ::

                  header.update(keyword, value, comment=comment)

              with ::

                  header[keyword] = (value, comment)

            * Replace ::

                  header.update(keyword, value, before=before_keyword)

              with ::

                  header.insert(before_keyword, (keyword, value))

            * Replace ::

                  header.update(keyword, value, after=after_keyword)

              with ::

                  header.insert(after_keyword, (keyword, value),
                                after=True)

            See also :meth:`Header.set` which is a new method that provides an
            interface similar to the old ``Header.update()`` and may help make
            transition a little easier.

        r   Nc                     t          |t                    st          | |          }n=dt          |          cxk     rdk    rn nt          | f|z    }nt	          d| z                                |           d S )Nr   rS   zHeader 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.)r   rK   r	   r'   rV   rZ   )r  r  r!   r    s      r"   update_from_dictz'Header.update.<locals>.update_from_dictV  s    a'' 
AqzzSVVqqdQh( A DEE   LLr$   r   r  r   r   zHeader update sequence item #{} 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.)r   r   r   rZ   hasattrr   r  r   r	   rK   r'   rV   r   update)	r    r   r   rw   r%  r!   r  r  rA   s	   `        r"   r'  zHeader.update  s   H  	GEEE	 	 	 	 	 =v&& 	 # #T""""#UG$$ 	 ' '1  A&&&&'UF## 	ZZ\\ . .  E!H----. 'u--  	TdD)) 
LL&&&&e,, !c$ii2D2D2D2D12D2D2D2D2DLLt----$@ AGs	    	 KK	  	 r$   c                 "   t          |t                    rt          |          }ngt          |t                    r
t          | }nH|t                      }n7t          |t                    s"t	          d                    |                    |s	|j        rd}|r2| j                            |           t          | j                  dz
  }nt          | j                  dz
  }|dk    r/| j        |         j        r|dz  }|dk    r| j        |         j        |sQ|j
        t          vrC|dk    r=| j        |         j
        t          v r$|dz  }|dk    r| j        |         j
        t          v $|dz  }| j                            ||           |                     |           t          j        |j
                  }| j        |                             |           |j        %| j        |j                                     |           |s|s-|j
        t          v r| j        |                                          |rP|                                 r<|                     t          t          |                    t          j        z             d| _        dS )a<  
        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.

        NzgThe value appended to a Header must be either a keyword or (keyword, value, [comment]) tuple; got: {!r}Tr   r   )r   rF   r	   rK   rV   r   is_blankr(   r   r'   r-   rI   insertrf   rd   r1   rL   r2   rM   sort_countblanks
_useblanksr   r   )r    r!   	useblanksbottomr   rA   r-   s          r"   r   zHeader.append  s   D dC   
	::DDe$$ 	;DD\66DDD$'' 	??Evd||  
  	t} 	C 	%Kt$$$dk""Q&CCdk""Q&C((t{3/8(q ((t{3/8(  dl2FFFQhh4;s#3#;?S#S#S1HC Qhh4;s#3#;?S#S#S 1HCKsD)))$$$(66g&--c222+t/66s;;; 	?  6dl.BBB%g.33555  ?T..00 ? CII$+ =>>>r$   c	                 @   |                      |          }	|r|	                                 t          |           r| j        d         j        }
nd}
g }t          |	j                  D ]\  }}|j        }|t          vr|r|s|| v r|rx|dk    rF|rD|dk    r|
dk    s|dk    r |
dk    r| d= |                     d|           [|j	        |j
        f| |<   m|| v r|j	        |j
        f| |<   |                    |           |                    |           |s|rP|| v rL|j        r|                    |           | |         D ]}||j	        k    r n|                    |           |                    |           |D ]}|                     ||||           dS )a  
        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 supersedes 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 ``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.
        r   NSIMPLEXTENSION)r.  r/  r   )rC   rG   r'   r(   r-   r   r   rI   r*  rO   rY   r   r)  )r    r   rG   uniquer'  update_firstr.  r/  r   r{   firstextend_cardsrA   r!   r-   rO   s                   r"   rz   zHeader.extend  s'   l ~~e$$ 	JJLLLt99 	KN*EEE "4:.. #	. #	.IClG222 .& .W__ .axxLx $x//EZ4G4G#z11ex6G6G $Q KK40000-1Z,FDMM D)-T\(BW$++D1111 ''---- .f .'T//} !$++D111 !%g 2 2 DJ..!E / %++D111 ''----  	K 	KDKK	&cKJJJJ	K 	Kr$   c                     t          j        |          }|| j        vrt          d|d          t	          | j        |                   S )a  
        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  not found.)r	   rd   r1   r4   r'   r6   s     r"   countzHeader.countE  sT     (11 $///<g<<<===4(1222r$   c                    |d}|t          | j                  }||k     rd}nd}t          j        |          }t	          |||          D ].}| j        |         j                                        |k    r|c S /t          d|d          )a  
        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

        Nr   r  r   zThe keyword z is not in the  header.)r'   r(   r	   rd   r`   r-   rH   rV   )r    r-   r   stoprb   norm_keywordrA   s          r"   r   zHeader.indexY  s    $ =E<t{##D%<<DDD-g66d++ 	P 	PC{3'--//<??


 @ NGNNNOOOr$   c                 $   t          |t          j                  s|                     |          }n|}|r |dk    rt	          | j                  }n|dz  }|t	          | j                  k    r|                     |d           dS t          |t                    rt          |          }nVt          |t                    r
t          | }n7t          |t                    s"t          d                    |                    | j                            ||           |j        }|dk     r"|t	          | j                  dz
  z  }|dk     rd}|                     |           t          j        |          }| j        |                             |           t	          | j        |                   }|dk    rU|t"          vr-t%          j        d                    |          t(                     | j        |                                          |j        ;| j        |j                 }|                    |           |                                 |r<|                     t	          t          |                    t          j        z             d| _        dS )	a  
        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`.
        r  r   Tr   NziThe value inserted into a Header must be either a keyword or (keyword, value, [comment]) tuple; got: {!r}r   zKA {!r} keyword already exists in this header.  Inserting duplicate keyword.)r   rW   rX   r3   r'   r(   r   rF   r	   rK   rV   r   r*  r-   rf   rd   r1   rI   r   r   r   r+  rL   r2   rM   r-  r   r   )	r    rP   r!   r.  r  rA   r-   r:  rvkc_indicess	            r"   r*  zHeader.insert~  sx   4 #w/00 	
 //#&&CCC 	byy$+&&q#dk"""" KK$K'''FdC   	::DDe$$ 	;DDD$'' 	??Evd||  
 	3%%%, 773t{##a''CQww 	C   (11g&--c222D)'233199222))/&  
 !'*//111+-do>L$$$ 	;OOCD		NNdk9:::r$   c                     t          j        |          }|| j        v rB| | j        |         d         = |r(|| j        v r!| | j        |         d         = || j        v dS dS dS |st          d| d          dS )a  
        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.

        ignore_missing : bool, optional
            When True, ignores missing keywords.  Otherwise, if the keyword
            is not present in the header a KeyError is raised.

        remove_all : bool, optional
            When True, all instances of keyword will be removed.
            Otherwise only the first instance of the given keyword is removed.

        r   r]   r^   N)r	   rd   r1   r4   )r    r-   ignore_missing
remove_alls       r"   re   zHeader.remove  s    & (11d+++T*73A67 @!666T27;A>? !66666@ @66 	><w<<<===	> 	>r$   c                    t          j        |          }t          j        |          }|dk    rt          d          |t          v s	|t          v r"|t          v r	|t          v st          d          n|s|| v rt          d| d          |                     |          }| j        |         }| |= |                     |||j        |j        f           dS )a  
        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
            `ValueError` is raised.
        r   zCan not rename to CONTINUEz=Regular and commentary keys can not be renamed to each other.zIntended keyword z already exists in header.N)	r	   rd   rV   rI   r   r(   r*  rO   rY   )r    
oldkeyword
newkeywordforceoldnewrA   r!   s           r"   rename_keywordzHeader.rename_keyword  s    " $Z00$Z00*9:::&&&#1E*E*E///C;O4O4O S   5P  	R3$;;PPPPQQQjjoo{3IC#tz4<899999r$   c                 8    |                      d|||           dS )a%  
        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`
        HISTORYr  N_add_commentaryr    rO   r  r  s       r"   add_historyzHeader.add_history  '     	YfEJJJJJr$   c                 8    |                      d|||           dS )a  
        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`
        COMMENTr  NrL  rN  s       r"   add_commentzHeader.add_comment/  rP  r$   c                 8    |                      d|||           dS )a!  
        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`
        rT   r  NrL  rN  s       r"   	add_blankzHeader.add_blank@  s'     	RvUCCCCCr$   c           	         |                      dd          }|                      dd          }t          |          D ],}|                     dt          |dz             z   d           -dD ]>}t          |          D ],}|                     |t          |dz             z   d           -?dD ]}|                     |d           d	S )
z
        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.
        NAXISr   TFIELDSr   T)rA  )
TFORMTSCALTZEROTNULLTTYPETUNITTDISPTDIMTHEAPTBCOL)r1  r2  BITPIXrW  EXTENDPCOUNTGCOUNTGROUPSBSCALEBZEROrX  N)r	  r`   re   rF   )r    naxistfieldsrA   names        r"   rG   zHeader.stripQ  s     !$$((9a((<< 	E 	ECKK#cAg,,.tKDDDD
 	F 	FD W~~ F FD3sQw<</EEEEF
 	3 	3D KKTK2222	3 	3r$   c                      t          |           S zX
        Return the size (in bytes) of the data portion following the `Header`.
        _hdr_data_sizer)   s    r"   	data_sizezHeader.data_size      
 d###r$   c                 4    | j         }|t          |          z   S zr
        Return the size (in bytes) of the data portion following the `Header`
        including padding.
        rq  r   r    sizes     r"   data_size_paddedzHeader.data_size_padded       ~k$''''r$   c                    |\  }}}|                                                                 }|                    d          r
|dd         }|t          vrK|| j        v rB| j        |         d         }| j        |         }||_        |||_        |j        r	d| _        dS dS |t          v r| 	                    ||          }|| j        v r_| 
                    |t          |           dz
  d          }|p|p| }t          |          D ]}	|                     |dz   |	| 	           dS |D ]}	|                     |	d
           dS |                     |           dS )as  
        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.
        z	HIERARCH 	   Nr   Tr   r  )r   r<  )r.  )r/  )rG   rH   
startswithrI   r1   r(   rO   rY   r   _splitcommentaryr   r'   rc   r*  r   )
r    r!   r-   rO   rY   rA   existing_cardr   isblankr>   s
             r"   rZ   zHeader._update  s    #' --//''))k** 	"abbkG...7d>S3S3S'03C K,M"'M"(/%& &!%& &,,,))'599E$///jjD		ABjGG&:%:7;!% E EAKKa7{KDDDDE E  0 0AKK$K////0 0 KKr$   c                    t          |t                    r|}d}nt          |t          j                  rL|dk     r|t	          | j                  z  }|dk     s|t	          | j                  k    rt          d          |S t          |t                    r|S t          |t                    rct	          |          dk    s;t          |d         t                    r t          |d         t          j                  st          d          |\  }}nt          d          t          j        |          }| j                            |d          }|rL|sJt	          |          t          k    sd|v rt          d	|d
          | j                            |d          }|st          d	|d
          	 ||         S # t          $ r$ t          dt	          |           d|d          w xY w)z@Returns an index into the ._cards list given a valid lookup key.r   zHeader index out of range.rS   r   zSTuple indices must be 2-tuples consisting of a keyword string and an integer index.zAHeader indices must be either a string, a 2-tuple, or an integer.N.r8  r9  zThere are only r   z cards in the header.)r   rF   rW   rX   r'   r(   r5   rB   rK   rV   r	   rd   r1   r	  r   r4   r2   )r    rP   r-   nra   s        r"   r3   zHeader._cardindex  s+   
 c3 	GAAW-.. 	Qwws4;'''Qww#T[!1!111 !=>>>JU## 	JU## 	CA!#a&#.. !#a&'*:;;  !;   JGQQS   (11 '++GT:: 	@7 	@7||n,,w@'@@@AAA ,00$?? 	><g<<<===	1: 	 	 	Q#g,,QQQQQ  	s   3F; ;.G)c                     |dk     r|t          | j                  z  }| j        |         j        }t          j        |          }| j        |                             |          }||fS )ax  
        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.
        r   )r'   r(   r-   r	   rd   r1   r   )r    rA   r-   repeats       r"   _keyword_from_indexzHeader._keyword_from_index  se     773t{###C+c"*(11&w/55c::r$   c                     |n fd}|rt                      |j                  } |            }|t           j                  k    r|t           j                  dz
  k    rdS ||dz
  k    rdS n
|||k    rdS  |=  |            }|d         t          v r0t                               |d         |d                             }	n|g}	|	D ]}
                     ||
           dS )z
        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.
        Nc                      t          t          j                  rt          j                  k    s                              } n} | dz  } | S )Nr   )r   rW   rX   r'   r(   r3   )rA   r  insertionkeyr    s    r"   get_insertion_idxz1Header._relativeinsert.<locals>.get_insertion_idx  sX    <)9::# C$4$444ool33"~qJr$   r   r   )r3   r-   r'   r(   rI   rc   r}  r*  )r    r!   r  r  r  r  old_idxinsertion_idxrA   r   r>   r  s   ` `        @r"   r  zHeader._relativeinsert  sX    > LL!L	 	 	 	 	 	 	  	
 oodl33G--//MDK 0 000WDK@P@PST@T5T5T !ma///F 0"w-'?'?W  !!7***T2247DGDDEEEEFE 	  	 AKKQ	  	 r$   c                     |t          | j                  k    rdS |rdnd}| j        | j        fD ]D}|                                D ]-}t          |          D ]\  }}||k    r||xx         |z  cc<   .EdS )z
        For all cards with index above idx, increment or decrement its index
        value in the keyword_indices dict.
        Nr   r  )r'   r(   r1   r2   r  r   )r    rA   r_   
index_setsra   jdxkeyword_indexs          r"   rf   zHeader._updateindicesA  s    
 T[!!!!F"*AA	0$2DE 	2 	2J%,,.. 2 2*3G*<*< 2 2&C$++	122	2 	2r$   c                     t          dt          | j                            D ]}| j        |          j        s|dz
  c S dS )z;Returns the number of blank cards at the end of the Header.r   r   )r`   r'   r(   r)  r    rA   s     r"   r,  zHeader._countblanksR  sP    C,,-- 	 	C;t$- Qwqr$   c                 Z    t          |          D ]}| j        d         j        r| d=  d S d S )Nr  )r`   r(   r)  )r    r:  _s      r"   r-  zHeader._useblanksY  sB    u 	 	A{2' HH		 	r$   c                 f    t          |t                    o|                    d          pd|v pd|v S )z?Return `True` if the input keyword contains a wildcard pattern....*?)r   rF   endswithr6   s     r"   rD   zHeader._haswildcard`  s<    '3'' 
U##Gsg~G	
r$   c                    |                     dd                               dd          }|                     dd          dz   }t          j        |t          j                  j        fdt          | j                  D             S )	z
        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
        r  z.*r  r  r  z\S*$c                 :    g | ]\  }} |j                   |S r:   )r-   )r=   ir!   match_patterns      r"   r?   z)Header._wildcardmatch.<locals>.<listcomp>r  s.    WWWga==;V;VWWWWr$   )r  recompileIr  r   r(   )r    patternr  s     @r"   rE   zHeader._wildcardmatchf  sz     //#u--55c4@@//%0036
7BD117WWWW4;!7!7WWWWr$   c                    t          |t                    s|                     |          rt          |t                    r*t          |                    t          |                     }n|                     |          }t          |t                    st          |          s"t          j
        |t          |                    }t          ||          D ]
\  }}|||<   dS dS )zT
        Used to implement Header.__setitem__ and CardAccessor.__setitem__.
        TF)r   rB   rD   r`   ra   r'   rE   rF   r   	itertoolsr  zip)r    rP   rO   targetra   rA   r   s          r"   rU   zHeader._set_slicet  s     c5!! 	T%6%6s%;%; 	#u%% 3S[[!9!9:--c22%%% >Z->-> >!(G==// " "S!s4ur$   c           	      P   t           j        t          z
  }t          |          }t	          |          |k    rt          ||          g}n]d}g }|t	          |          k     rF|                    t          |||||z                                 ||z  }|t	          |          k     F|S )a*  
        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.
        r   )r	   r   r   rF   r'   r   )r    r-   rO   maxlenvaluestrr   rA   s          r"   r}  zHeader._splitcommentary  s     ~-u::x==F""'5))*EE CEH%%T'8C#,4F+GHHIIIv H%% r$   c                 P    |||                      ||f||           dS || |<   dS )z
        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.
        Nr  )r  )r    rP   rO   r  r  s        r"   rM  zHeader._add_commentary  sA     !2  #ufE JJJJJDIIIr$   rT   )rT   TT)rT   TTF)F)FFr&   )NNNN)NTFF)TFFFTFF)NN)TF)rT   NN)NNFT)G__name__
__module____qualname____doc__r#   r*   r/   r7   rQ   r[   rg   rp   rr   rx   r|   r~   r   propertyr   r   r   setterclassmethodr   r   r   r   r   ro   r   r   r   r   r   r   r   r  r	  r   r   r  r  r  r   r"  r'  r   rz   r:  r   r*  re   rI  rO  rS  rU  rG   rq  rx  rZ   r3   r  r  rf   r,  r-  rD   rE   rU   r}  rM  r:   r$   r"   r   r   7   sz       & &P  e ! ! ! !F           >(0 (0 (0T8 8 8tE E E  ' ' '  
     # # X# % % X%  * * X* ) ) ) r% r% r% [r%h A  A  A  [A F 
 
 [
 C? C? [C?J . . [.`* * * *X4  4  4  4 l O O O [O
 
 
 
"; ; ;   2        [:   2T- T- T- T-lP P P
  B B B
  .     p  p  p dW W W Wx kK kK kK kKZ3 3 3(#P #P #P #PJ^ ^ ^ ^@> > > >8": ": ": ":HK K K K"K K K K"D D D D"13 13 13f $ $ X$ ( ( X(' ' 'R5 5 5n  $9  9  9  9 v2 2 2 2"    
 
 
X X X  (  4     r$   r   c                   &    e Zd ZdZddZd Zd ZdS )_DelayedHeaderz
    Descriptor used to create the Header object from the header string that
    was stored in HDU._header_str when parsing the file.
    Nc                     	 |j         d         S # t          $ rb |j        't                              |j                  }d |_        n%t          dt          |          j         d          ||j         d<   |cY S w xY w)N_header'z#' object has no attribute '_header')r   r4   _header_strr   r   AttributeErrortyper  )r    objownerhdrs       r"   __get__z_DelayedHeader.__get__  s    	<	** 
	 
	 
	*''88"&$OS		*OOO   '*CL#JJJ
	s    A)A;:A;c                     ||j         d<   d S Nr  r   )r    r  r   s      r"   __set__z_DelayedHeader.__set__  s    "%Yr$   c                     |j         d= d S r  r   )r    r  s     r"   
__delete__z_DelayedHeader.__delete__  s    L###r$   r&   )r  r  r  r  r  r  r  r:   r$   r"   r  r    sP         
   & & &$ $ $ $ $r$   r  c                       e Zd ZdZd Zd ZdS )_BasicHeaderCardsa&  
    This class allows to access cards with the _BasicHeader.cards attribute.

    This is needed because during the HDU class detection, some HDUs uses
    the .cards interface.  Cards cannot be modified here as the _BasicHeader
    object will be deleted once the HDU object is created.

    c                     || _         d S r&   )r   r    r   s     r"   r#   z_BasicHeaderCards.__init__  s    r$   c                     | j         j        |         }	 | j         j        |         S # t          $ r: | j         j        |         }t          j        |          }|| j         j        |<   |cY S w xY wr&   )r   _keysr(   r4   
_raw_cardsr	   r   r    rP   cardstrr!   s       r"   rQ   z_BasicHeaderCards.__getitem__  sy     k$	;%c** 	 	 	k,S1G?7++D&*DKs#KKK		s   & AA*)A*N)r  r  r  r  r#   rQ   r:   r$   r"   r  r    s<               r$   r  c                   r    e Zd ZdZd Zd Zd Zd Zd Ze	d             Z
e	d             Zed	             Zd
S )_BasicHeaderaT  This class provides a fast header parsing, without all the additional
    features of the Header class. Here only standard keywords are parsed, no
    support for CONTINUE, HIERARCH, COMMENT, HISTORY, or rvkc.

    The raw card images are stored and parsed only if needed. The idea is that
    to create the HDU objects, only a small subset of standard cards is needed.
    Once a card is parsed, which is deferred to the Card class, the Card object
    is kept in a cache. This is useful because a small subset of cards is used
    a lot in the HDU creation process (NAXIS, XTENSION, ...).

    c                     || _         t          |                                          | _        i | _        t          |           | _        d| _        d S r   )r  r   r  r  r(   r  r   r   )r    r   s     r"   r#   z_BasicHeader.__init__  sC    %**,,''
 't,,
r$   c                     t          |t          j                  r| j        |         }	 | j        |         j        S # t          $ r5 | j        |         }t          j	        |          x| j        |<   }|j        cY S w xY wr&   )
r   rW   rX   r  r(   rO   r4   r  r	   r   r  s       r"   rQ   z_BasicHeader.__getitem__  s    c7+,, 	"*S/C	;s#)) 	 	 	oc*G&*og&>&>>DKt:		s   ; <A:9A:c                 *    t          | j                  S r&   )r'   r  r)   s    r"   r*   z_BasicHeader.__len__  s    4?###r$   c                 *    t          | j                  S r&   )iterr  r)   s    r"   r/   z_BasicHeader.__iter__  s    DO$$$r$   c                 6    | j                             |          S r&   )r  r   r6   s     r"   r   z_BasicHeader.index  s    z(((r$   c                      t          |           S rn  ro  r)   s    r"   rq  z_BasicHeader.data_size  rr  r$   c                 4    | j         }|t          |          z   S rt  ru  rv  s     r"   rx  z_BasicHeader.data_size_padded!  ry  r$   c                 &   d}t          |t                    rt          |d          }d}	 t          |          \  }}t	          |t
          d           | | |          f|r|                                 S S # |r|                                 w w xY w)zThe main method to parse a FITS header from a file. The parsing is
        done with the parse_header function implemented in Cython.
        Fr   T)r   rF   r   r   r   r   r   )r   r   r   r   r   s        r"   r   z_BasicHeader.fromfile*  s    
 
gs## 	7D))GJ	  ,W 5 5J:z5999ss5zz)   z   s   4A7 7BN)r  r  r  r  r#   rQ   r*   r/   r   r  rq  rx  r  r   r:   r$   r"   r  r    s        
 

 
 

 
 
$ $ $% % %) ) ) $ $ X$ ( ( X(     [     r$   r  c                   B    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )r   ao  
    This is a generic class for wrapping a Header in such a way that you can
    use the header's slice/filtering capabilities to return a subset of cards
    and do something with them.

    This is sort of the opposite notion of the old CardList class--whereas
    Header used to use CardList to get lists of cards, this uses Header to get
    lists of cards.
    c                     || _         d S r&   )r  r  s     r"   r#   z_CardAccessor.__init__I  s    r$   c                 T    d                     d | j        j        D                       S )Nri   c              3   4   K   | ]}t          |          V  d S r&   )r   r<   s     r"   r   z)_CardAccessor.__repr__.<locals>.<genexpr>M  s(      >>Qa>>>>>>r$   )r   r  r(   r)   s    r"   rp   z_CardAccessor.__repr__L  s(    yy>>$,*=>>>>>>r$   c                 4    t          | j        j                  S r&   )r'   r  r(   r)   s    r"   r*   z_CardAccessor.__len__O  s    4<&'''r$   c                 4    t          | j        j                  S r&   )r  r  r(   r)   s    r"   r/   z_CardAccessor.__iter__R  s    DL'(((r$   c                     t          |          rt          |t                    rt          |           dk    r|g}ndS t	          d t          j        | |          D                       S )Nr   Fc              3   (   K   | ]\  }}||k    V  d S r&   r:   )r=   abs      r"   r   z'_CardAccessor.__eq__.<locals>.<genexpr>^  s*      IIda16IIIIIIr$   )r   r   rF   r'   allr  zip_longestrv   s     r"   rx   z_CardAccessor.__eq__U  sl     %   	Juc$:$: 	4yyA~~uIIi&;D%&H&HIIIIIIr$   c                     | |k     S r&   r:   rv   s     r"   __ne__z_CardAccessor.__ne__`  s    EM""r$   c                     t          |t                    s| j                            |          r |                     | j        |                   S | j                            |          }| j        j        |         S r&   )r   rB   r  rD   rC   r3   r(   )r    itemrA   s      r"   rQ   z_CardAccessor.__getitem__c  si    dE"" 	6dl&?&?&E&E 	6>>$,t"4555l%%d++|"3''r$   c                    t          |t                    s| j                            |          rt          |t                    r*t	          |                    t          |                      }n| j                            |          }t          |t                    st          |          s"t          j        |t          |                    }t          ||          D ]
\  }}|| |<   dS dS )z
        Helper for implementing __setitem__ on _CardAccessor subclasses; slices
        should always be handled in this same way.
        TF)r   rB   r  rD   r`   ra   r'   rE   rF   r   r  r  r  )r    r  rO   ra   rA   r   s         r"   	_setslicez_CardAccessor._setslicej  s    
 dE"" 		dl&?&?&E&E 		$&& <c$ii!8!89,55d;;%%% >Z->-> >!(G==//    SS		4ur$   N)r  r  r  r  r#   rp   r*   r/   rx   r  rQ   r  r:   r$   r"   r   r   =  s           ? ? ?( ( () ) )	J 	J 	J# # #( ( (    r$   r   c                   4     e Zd ZdZd Zd Z fdZd Z xZS )r   aa  
    A class used internally by the Header class for the Header.comments
    attribute access.

    This object can be used to display all the keyword comments in the Header,
    or look up the comments on specific keywords.  It allows all the same forms
    of keyword lookup as the Header class itself, but returns comments instead
    of values.
    c              #   :   K   | j         j        D ]}|j        V  d S r&   )r  r(   rY   r.   s     r"   r/   z_HeaderComments.__iter__  s5      L' 	 	D,	 	r$   c                     t           | j        j        D ]$}t          t	          |j                            %d                    fd| j        j        D                       S )z9Returns a simple list of all keywords and their comments.ri   c              3   \   K   | ]&}d                      |j        |j                  V  'dS )z{:>{len}}  {})r'   N)r   r-   rY   )r=   r>   keyword_lengths     r"   r   z+_HeaderComments.__repr__.<locals>.<genexpr>  sP       
 
 ""19ai^"LL
 
 
 
 
 
r$   )r   r  r(   maxr'   r-   r   )r    r!   r  s     @r"   rp   z_HeaderComments.__repr__  sz    'L' 	D 	DD T\1B1BCCNNyy 
 
 
 
\(
 
 
 
 
 	
r$   c                     t                                          |          }t          |t                    r|S |j        S )z
        Slices and filter strings return a new _HeaderComments containing the
        returned cards.  Otherwise the comment of a single card is returned.
        )superrQ   r   r   rY   )r    r  rC   s     r"   rQ   z_HeaderComments.__getitem__  s;    
 ww""4((dO,, 	K|r$   c                     | j                             |||           rdS | j                             |          }| j         |         }||f| j         |<   dS )z
        Set/update the comment on specified card or cards.

        Slice/filter updates work similarly to how Header.__setitem__ works.
        N)r  rU   r3   )r    r  rY   rA   rO   s        r"   r[   z_HeaderComments.__setitem__  s_     <""4$77 	F l%%d++S!"G,Sr$   )	r  r  r  r  r/   rp   rQ   r[   __classcell__rC   s   @r"   r   r   |  so           
 
 
	 	 	 	 	- - - - - - -r$   r   c                   B     e Zd ZdZd	 fd	Zd Zd Zd Zd Zd Z	 xZ
S )
rJ   z
    This is used to return a list-like sequence over all the values in the
    header for a given commentary keyword, such as HISTORY.
    rT   c                    t                                          |           || _        | j                            | j                  | _        t          | j                                      | j                  | _        d S r&   )	r  r#   _keywordr  r:  _countrB   ra   _indices)r    r   r-   rC   s      r"   r#   z_HeaderCommentaryCards.__init__  s`       l((77dk**224;??r$   c                 8    t          t          | j                   S r&   )r'   r`   r  r)   s    r"   r*   z_HeaderCommentaryCards.__len__  s    5$-()))r$   c              #   X   K   t          | j         D ]}| j        | j        |f         V  d S r&   )r`   r  r  r  r  s     r"   r/   z_HeaderCommentaryCards.__iter__  sC      $-( 	5 	5C,s344444	5 	5r$   c                 @    d                     d | D                       S )Nri   c              3   4   K   | ]}t          |          V  d S r&   ru   )r=   xs     r"   r   z2_HeaderCommentaryCards.__repr__.<locals>.<genexpr>  s(      ..AQ......r$   )r   r)   s    r"   rp   z_HeaderCommentaryCards.__repr__  s#    yy........r$   c                 z   t          |t                    rA|                     | j        | j                  }|                    | j                  |_        |S t          |t          j	                  st          | j         d          t          t          | j                   |         }| j        | j        |f         S )Nz index must be an integer)r   rB   rC   r  r  ra   r  r  rW   rX   rV   r   r`   )r    rA   r  s      r"   rQ   z"_HeaderCommentaryCards.__getitem__  s    c5!! 	Jt|T];;AT[11AJHC!122 	JHHHIII5$-())#.|T]C011r$   c                 d    | j                             |||           rdS || j         | j        |f<   dS )z
        Set the value of a specified commentary card or cards.

        Slice/filter updates work similarly to how Header.__setitem__ works.
        N)r  rU   r  )r    r  rO   s      r"   r[   z"_HeaderCommentaryCards.__setitem__  s@     <""455 	F /4dmT*+++r$   r  )r  r  r  r  r#   r*   r/   rp   rQ   r[   r  r  s   @r"   rJ   rJ     s         
@ @ @ @ @ @* * *5 5 5/ / /	2 	2 	24 4 4 4 4 4 4r$   rJ   c                 `    t           t          |           t           t          j        z  dz
  z  z   S )zg
    Determine the size of a FITS header block if a non-blank separator is used
    between cards.
    r   )r   r'   r	   r   r   s    r"   r   r     s&    
 SZ4;%>%BCDDr$   c                 6    t           | t           z  z
  t           z  S )z?Bytes needed to pad the input stringlen to the next FITS block.)r   )	stringlens    r"   r   r     s    )j01Z??r$   Tc                    | r| d         dk    rs|rA|                      d          dk    r(t          j        dt                     t	                      t          j        dt                     |                     dd           |rJt          |           |z  dk    r6t          |           |z
  t          z   }t          dt           d	|           d S d S )
Nr   rT   zhUnexpected extra padding at the end of the file.  This padding may not be preserved when saving changes.zHeader block contains null bytes instead of spaces for padding, and is not FITS-compliant. Nulls may be replaced with spaces upon writing.r   r   zHeader size is not multiple of z: )	rG   r   r   r   r   r  r'   r   rV   )r   
block_sizer   r   
actual_lens        r"   r   r     s     *jn,, 	*j&&t,,22MD"  
 **
 M5 #	   tS))) WS__z9a?? __z1J>
U:UUUUVVVW W??r$   c                 D   d}|                      dd          }|dk    rd}t          |          D ] }|| dt          |dz             z            z  }!| d         }|                      dd          }|                      dd          }t          |          |z  ||z   z  dz  }|S )z@Calculate the data size (in bytes) following the given `Header`.r   rW  r   rc  rf  re  r   )r	  r`   rF   abs)r   rw  rj  rA   bitpixgcountpcounts          r"   rp  rp  	  s    DJJw""Eqyy<< 	9 	9C&3sQw<<!788DD!Ha((Ha((6{{V#v}5:Kr$   r  )5r   r   r  rW   r   r  r   astropy.utilsr   astropy.utils.exceptionsr   _utilsr   r!   r   r   r	   r
   filer   utilr   r   r   r   r   r   r  r   r   mapchrr`   r   r   rI   __doctest_skip__r   abcMutableSequenceregisterMutableMappingr  r  Mappingr  r   r   rJ   r   r   r   rp  r:   r$   r"   <module>r     s3             				 				  $ $ $ $ $ $ 7 7 7 7 7 7             7 7 7 7 7 7 7 7 7 7 7 7                    
 
LUVV  SS%%d"3"34455 0    v v v v v v v vr;   ( ( 0 0 0   ' ' / / /$ $ $ $ $ $ $ $8       8N  N  N  N  N ;?* N  N  N b< < < < < < < <~1- 1- 1- 1- 1-m 1- 1- 1-h.4 .4 .4 .4 .4] .4 .4 .4bE E E@ @ @
W W W W>    r$   