import codecs


def format_txt_answers(path):
    """
    Converts the text file with the gold answers into a list of tuples
    (question_id, right_answer_id)

    Args
    
    path (string): Path the text file containing the gold answers

    """

    with codecs.open(path) as f:
        lines = f.readlines()
        
    head_line = lines[0]
    content_lines = lines[1:]
    
    d_columns = {}
    d_columns_content = {}
    
    for j,key in enumerate(head_line.split()):
        if key not in d_columns:
            d_columns[key] = []
            d_columns_content[key] = []
        d_columns[key].append(j)
    
    RC_key = "RC"
    v_keys = [key for key in d_columns if key.startswith("V")]
    v_keys.sort(reverse=True)
    V_key = v_keys[0]
    
    v_rc_indexes = zip([index for index in d_columns[V_key]], [index for index in d_columns[RC_key]]) 
    
    template =[]
    for iv,irc in v_rc_indexes:
        #print iv,irc, content_lines[0].split(), len(content_lines[0].split())
        question_ids = [line.split()[iv] for line in content_lines]  
        answer_ids = [line.split()[irc] for line in content_lines]  
        
        if len(question_ids) != len(answer_ids):
            raise ValueError("question_ids and answer_ids vectors should have the same length, but they do not")
        else:
            template.extend(zip(question_ids, answer_ids))

    return template