#!/usr/bin/env python
#
# File: tfam_order.py\
#


##
# Order the output of "vtools phenotype --out familyID sample_name FatherID MotherID Sex Status"
# by the order of sample_name in "Sample names are exported to export.tfam" (the order of tped)
##


import os
import sys


def correct_order(vtools_tfam, error_tfam, right_tfam):
    order = []
    with open(vtools_tfam) as f:
        for line in f:
            order.append(line.split()[1])

    sid2pheno = {}
    with open(error_tfam) as f:
        for line in f:
            sid = line.split()[1]
            sid2pheno[sid] = line #.rstrip()

    ofile = open(right_tfam, 'w')
    for s in order:
        ofile.write(sid2pheno[s])
    ofile.close()


if __name__ == '__main__':
    correct_order(sys.argv[1], sys.argv[2], sys.argv[3])
