import re


def parse_port_name(name):
    """
    Parses a port name. Returns the base name, cell index and bit index.

    >>> parse_port_name("A_PORT")
    ('A_PORT', None, None)
    >>> parse_port_name("A_PORT_0")
    ('A_PORT', 0, None)
    >>> parse_port_name("A_PORT_b31")
    ('A_PORT', None, 31)
    >>> parse_port_name("A_PORT_0_b15")
    ('A_PORT', 0, 15)
    """

    # A multi-bit port
    m = re.match(r"(?P<name>.*)(_b(?P<bit>[0-9]+))$", name)
    if m is not None:
        port = m.group("name")
        bit = int(m.group("bit"))
    else:
        port = name
        bit = None

    # A port of a sub-cell
    m = re.match(r"(?P<name>.*)(_(?P<cell>[0-9]+))$", port)
    if m is not None:
        return m.group("name"), int(m.group("cell")), bit

    return port, None, bit