import re


def split_verilog_ports(code):
    """
    Splits assignments of individual nets to wide cell ports into assignments
    of those nets to 1-bit wide cell ports. Effectively splits cell ports as
    well.
    """

    def sub_func(match):
        port = match.group("port")
        conn = match.group("conn").strip().replace("\n", "")

        # Get individual signals
        signals = [s.strip() for s in conn.split(",")]

        # Format new port connections
        conn = []
        for i, signal in enumerate(signals):
            j = len(signals) - 1 - i
            conn.append(".\\{}[{}] ({} )".format(port, j, signal))

        conn = ", ".join(conn)
        return conn

    code = re.sub(
        r"\.(?P<port>\S+)\s*\(\s*{(?P<conn>[^}]+)}\s*\)",
        sub_func,
        code,
        flags=re.DOTALL
    )
    return code