##################################
#                                #
# Last modified 2019/05/10       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import math
import os
from sets import Set

def run():

    if len(sys.argv) < 5:
        print 'usage: python %s input fieldID old_to_new fieldID1 fieldID2' % sys.argv[0]
        print '\tthe script can read compressed input files'
        print '\tuse - for stdin'
        print '\tthe script will print to stdout by default'
        sys.exit(1)

    datafilename = sys.argv[1]
    fieldID = int(sys.argv[2])
    oldtonew = sys.argv[3]
    O2NfieldID1 = int(sys.argv[4])
    O2NfieldID2 = int(sys.argv[5])

    O2NDict = {}

    if oldtonew.endswith('.bz2'):
        cmd = 'bzip2 -cd ' + oldtonew
    elif oldtonew.endswith('.gz'):
        cmd = 'gunzip -c ' + oldtonew
    else:
        cmd = 'cat ' + oldtonew
    p = os.popen(cmd, "r")
    line = 'line'
    while line != '':
        line = p.readline()
        if line == '':
            break
        fields = line.strip().split('\t')
        O2NDict[fields[O2NfieldID1]] = fields[O2NfieldID2]

    doStdIn = False
    if datafilename != '-':
        if datafilename.endswith('.bz2'):
            cmd = 'bzip2 -cd ' + datafilename
        elif datafilename.endswith('.gz'):
            cmd = 'gunzip -c ' + datafilename
        else:
            cmd = 'cat ' + datafilename
        p = os.popen(cmd, "r")
    else:
        doStdIn = True
    line = 'line'
    while line != '':
        if doStdIn:
            line = sys.stdin.readline()
        else:
            line = p.readline()
        if line == '':
            break
        fields = line.strip().split('\t')
        if line.startswith('#'):
            print line.strip()
            continue
        outline = ''
        for ID in range(fieldID):
            outline = outline + fields[ID] + '\t'
        outline = outline + O2NDict[fields[fieldID]] + '\t'
        for ID in range(fieldID+1,len(fields)):
            outline = outline + fields[ID] + '\t'
        print outline.strip()
        
run()

