#!/usr/bin/python3
'''
Convert inparalog data to alignment format.
Note that this will lead to a loss in information.
The original BRH wrt which the inparalog was defined is not retained.
Pipeline usage: MERGEINPAR (louvain)
'''
from __future__ import print_function

import re

def print_inpars(key,inpar,matchinpar):
    if len(inpar)==0: return
    allinp=inpar.split(',')
    defeval=0.0
    defpid=100.0
    for inp in allinp:
        inparvals=matchinpar.match(inp)
        ngroups=inparvals.lastindex
        startA=int(inparvals.group(3))
        endA=int(inparvals.group(4))
        startB=None
        endB=None
        score=1000.0
        pid=defpid
        if ngroups==6:
            score=float(inparvals.group(2))
            startB=int(inparvals.group(5))
            endB=int(inparvals.group(6))
        else:
            pid=float(inparvals.group(2))

        # print output line:
        # A B score eval pid stA ndA [stB ndB]
        outstr='%s %s %.2f %.4e %.2f %d %d'%(key,inparvals.group(1),score,defeval,pid,startA,endA)
        if startB is not None:
            outstr='%s %d %d'%(outstr,startB,endB)
        print(outstr)
        
def read_data(filename):
    matchsingle=re.compile( r'(.*):{(.*)}' )
    matchpair=re.compile( r'(.*):{(.*)}\s+(.*):{(.*)}' )
    matchsingleinpar=re.compile( r'(.*)\((.*);(.*);(.*)\)' )
    matchpairinpar=re.compile( r'(.*)\((.*);(.*);(.*);(.*);(.*)\)' )
    matchline=None
    matchinpar=None
    issingle=False
    with open(filename) as fh:
        for line in fh:
            line = line.strip().rstrip('\n')
            if len(line)>0 and line[0] not in '#':
                elems = line.split()
                n=len(elems)
                if not (n==1 or n==2):
                    continue

                keyB=None
                inpB=None
                if n==1:
                    matchline=matchsingle
                    matchinpar=matchsingleinpar
                    issingle=True
                elif n==2:
                    matchline=matchpair
                    matchinpar=matchpairinpar
                else:
                    continue

                matches=matchline.match(line)
                keyA=matches.group(1)
                inpA=matches.group(2)
                keyB=None
                inpB=None

                if not issingle:
                    keyB=matches.group(3)
                    inpB=matches.group(4)
###                ngroups=matches.lastindex

                print_inpars(keyA,inpA,matchinpar)
                if keyB is not None:
                    print_inpars(keyB,inpB,matchinpar)


print('error: NEEDS REWRITE FOR NEW INPARALOG FORMAT!!!!')

sys.exit(255)



import argparse

parser = argparse.ArgumentParser(description='Extract inparalogs for a single species')
parser.add_argument('-f', '--file', dest='filename',
                  help='inparalog file', metavar='FILE', required=True)

options = parser.parse_args()

read_data(options.filename)
