import re


def parseLinkHeader(header):
    """
    Parses a link header. The results will be key'd by the value of "rel".
    Link: <http://json-ld.org/contexts/person.jsonld>; \
      rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json"
    Parses as: {
      'http://www.w3.org/ns/json-ld#context': [
          {
            target: http://json-ld.org/contexts/person.jsonld, 
            type: 'application/ld+json'
          }
      ]
    }
    If there is more than one "rel" with the same IRI, then entries in the
    resulting map for that "rel" will be lists.
    :param header: the link header to parse.
    :return: the parsed result.
    """
    rval = {}
    # split on unbracketed/unquoted commas
    entries = re.findall(r'(?:<[^>]*?>|"[^"]*?"|[^,])+', header)
    if not entries:
        return rval
    r_link_header = r'\s*<([^>]*?)>\s*(?:;\s*(.*))?'
    for entry in entries:
        match = re.search(r_link_header, entry)
        if not match:
            continue
        match = match.groups()
        result = {'target': match[0]}
        params = match[1]
        r_params = r'(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)'
        matches = re.findall(r_params, params)
        for match in matches:
            result[match[0]] = match[2] if match[1] is None else match[1]
        rel = result.get('rel', '')
        if isinstance(rval.get(rel), list):
            rval[rel].append(result)
        else:
            rval[rel] = [result,]
    return rval