import struct


def read_header(raw):
    """
    Reads the nes header and places the relevant data in a dictionary. The
    keys are the following:
        ID (string): This will always be 'NES'
        MAPPER (int): The nes mapper number.
        FOUR_SCREEN (bool): Does the cartridge support four screen?
        TRAINER (bool): Does the cartridge contain a 512 byte trainer?
        BATTER_BACK (bool): Is the cartridge battery backed?
        MIRRORING (string): Is the cartridge HORIZONTAL or VERTICAL mirrored?
        PLAY_CHOICE_10 (bool): Is the cartridge a play choice 10?
        VS_UNISYSTEM (bool): Is the cartridge a VS Unisystem game?
        NES_2.0 (bool): Is the header an iNES 2.0 header?

    Args:
        raw (string): The first 16 raw bytes from the .nes file

    Returns:
        dict: The key value pairs for the header information.
        int: The number of 16384 byte programming rom sections.
        int: The number of 4096 byte character rom sections.

    Raises:
        IOError: If the nes file does not start with NES.
    """
    header = dict()

    header['ID'] = raw[:3]

    if header['ID'] != 'NES':
        raise IOError('Unknown header type: ' + header['ID'])

    flags6 = struct.unpack('B', raw[6])[0]
    flags7 = struct.unpack('B', raw[7])[0]
    header['MAPPER'] = (flags6 >> 4) | (flags7 & 0xF0)
    header['FOUR_SCREEN'] = (flags6 & 0x08) != 0
    header['TRAINER'] = (flags6 & 0x04) != 0
    header['BATTERY_BACK'] = (flags6 & 0x02) != 0
    header['MIRRORING'] = 'HORIZONTAL' if (flags6 & 0x01) == 0 else 'VERTICAL'
    header['PLAY_CHOICE_10'] = (flags7 & 0x02) != 0
    header['VS_UNISYSTEM'] = (flags7 & 0x01) != 0
    header['NES_2.0'] = (flags7 & 0x08) == 0x08

    return header, struct.unpack('B', raw[4])[0], \
            struct.unpack('B', raw[5])[0] * 2