#!/usr/bin/python3

# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orthologer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orthologer.  If not, see <http://www.gnu.org/licenses/>.
'''
Join different map files.
Pipeline usage: -
'''
from __future__ import print_function
#
# This tool relabels entries in a cluster file.
#
import argparse

def readMap( fname, swap ):
    fsh  = open(fname,mode='r')

    labelMap = {}
    # read map
    for rawline in fsh.readlines():
        line = rawline.strip().rstrip('\n')
        if len(line)==0: continue
        if line[0]=='#': continue
        # split line in:
        #   <id> <orig id>
        elems=line.split()
        if not len(elems)==2: continue
        if swap:
            labelMap[elems[1]]=elems[0]
        else:
            labelMap[elems[0]]=elems[1]

    return labelMap

def joinMaps(fA,fB):
    mapA=readMap(fA,False)
    mapB=readMap(fB,True)
    for keyA in mapA:
        val=mapA[keyA]
        if val in mapB:
            trg=mapB[val]
            print(('%s %s')%(keyA,trg))

#-----------------------------------------------------------------
# MAIN


parser = argparse.ArgumentParser(description='Prepare fasta file')

parser.add_argument('-A', '--mapA',     dest='mapA',       help='gene map file <X,Y>',      metavar='FILE', required=True)
parser.add_argument('-B', '--mapB',     dest='mapB',       help='gene map file <Z,Y>',      metavar='FILE', required=True)

parser.add_argument('-s', '--swap',    dest='swap',      help='swap mapping given by gene map file', action='store_true', default=False)

options = parser.parse_args()

# open fasta file and read data
joinMaps( options.mapA, options.mapB )
