import re


def read_header(ds):
    """Read a RAMSES output header file."""

    folder = './'
    iout = int(str(ds)[-5:])

    hname = '{0}/output_{1:05d}/header_{1:05d}.txt'.format(folder, iout)
    with open(hname, 'r') as hfile:
        htxt = hfile.read()
    header_re = re.compile("Total number of particles\s+([0-9]+)\s+"
                           "Total number of dark matter particles\s+([0-9]+)\s+"
                           "Total number of star particles\s+([0-9]+)\s+"
                           "Total number of sink particles\s+([0-9]+)\s*"
                           "Particle fields\s+([\w ]+)")
    match = header_re.search(htxt.strip())
    header = {'total': 0, 'DM': 0, 'stars': 0, 'sinks': 0, 'fields': []}
    if match:
        ntot, ndm, nstar, nsink, fields = match.groups()
        header['total'] = int(ntot)
        header['DM'] = int(ndm)
        header['stars'] = int(nstar)
        header['sinks'] = int(nsink)
        # Format fields
        if 'tform' in fields:
            fields = fields.replace('tform', 'epoch')
        if 'metal' in fields:
            fields = fields.replace('metal', 'metals')
        if 'iord' in fields:
            fields = fields.replace('iord', 'id')
        header['fields'] = fields.split()

    return header