import re


def readLinking(goldStdFile):
    """
    Reads a file containing Entity Linking output according to the KBP 2013 format.
    Each line in the systeming output file consists of 2 or 3 fields:
      mention_id KB_ID (optional confidence, default is 1.0)
    Each line in the gold standard file may contain 2 or more than 3 fields, but we ignore all but the first 2 fields:
      mention_id KB_ID
    
    Do NOT change IDs in any way (i.e., do not Uppercase all IDs)
    Returns a pair of dictionaries:
        linking: KB_ID -> set of query_IDs
        el2kbid: query_ID -> list of pairs of KB_ID (or NIL ID) and confidence, highest confidence first
    """
    linking = dict()
    el2kbid = dict()
    for line in open(goldStdFile):
        d = re.split("\s+", line.strip())
        if len(d)<2:
            continue
        mention = d[0]
        kb_id   = d[1]
        if(len(d)==3):  # a system linking
            conf = d[2]
        else:
            conf = 1.0 

        if mention in el2kbid.keys():  # more than one link for this mention; put the earliest highest confidence link in front, and add additional links to back of list
            links = el2kbid[mention]   # list of (kb_id,conf) tuples
            bestlink, bestconf = links[0]
            if conf > bestconf:
                links.insert(0, (kb_id, conf))
            else:
                links.append((kb_id, conf))
        else:
            el2kbid[mention] = [(kb_id, conf)]
            

        if kb_id in linking.keys():
            linking[kb_id].add(mention) 
        else:
            linking[kb_id] = set([mention])  

    return (linking, el2kbid)