import re


def get_aperture_coeffs_in_header(head):
    """Get coefficients of each aperture from the FITS header.

    Args:
        head (:class:`astropy.io.fits.Header`): Header of FITS file.

    Returns:
        *dict*: A dict containing coefficients for each aperture and each channel.
    """

    coeffs = {}
    for key, value in head.items():
        exp = '^GAMSE TRACE CHANNEL [A-Z] APERTURE \d+ COEFF \d+$'
        if re.match(exp, key) is not None:
            g = key.split()
            channel  = g[3]
            aperture = int(g[5])
            icoeff   = int(g[7])
            if (channel, aperture) not in coeffs:
                coeffs[(channel, aperture)] = []
            if len(coeffs[(channel, aperture)]) == icoeff:
                coeffs[(channel, aperture)].append(value)
    return coeffs