def headers_to_dict(headers):
    """
    Converts a sequence of (name, value) tuples into a dict where if
    a given name occurs more than once its value in the dict will be
    a list of values.
    """
    hdrs = {}
    for h, v in headers:
        h = h.lower()
        if h in hdrs:
            if isinstance(hdrs[h], list):
                hdrs[h].append(v)
            else:
                hdrs[h] = [hdrs[h], v]
        else:
            hdrs[h] = v
    return hdrs