##################################
#                                #
# Last modified 2018/05/25       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import math
from sets import Set
import h5py
import numpy as np    
import os

def getReverseComplement(preliminarysequence):
    
    DNA = {'A':'T','T':'A','G':'C','C':'G','N':'N','a':'t','t':'a','g':'c','c':'g','n':'n'}
    sequence=''
    for j in range(len(preliminarysequence)):
        sequence=sequence+DNA[preliminarysequence[len(preliminarysequence)-j-1]]
    return sequence

def run():

    if len(sys.argv) < 4:
        print 'usage: python %s 5mC.tombo.per_read_stats 6mA.tombo.per_read_stats genome.fa outfile_prefix [-m5C-only] [-m6A-only] [-CG-only] -GC-only] [-printContext]' % sys.argv[0]
        print '\tnote: the [-CG-only] and [-GC-only] options only apply if they [-m5C-only] has been specified'
        sys.exit(1)

    do5C = True
    do6A = True
    CGonly = False
    GConly = False

    doPrintContext = False
    if '-printContext' in sys.argv:
        doPrintContext = True

    if '-m5C-only' in sys.argv:
        do6A = False
        GConly = False
        CGonly = False
        print 'will only output m5C positions'
        if '-CG-only' in sys.argv:
            CGonly = True
            print 'will only output m5C positions in CpG context'
        if '-GC-only' in sys.argv:
            GConly = True
            print 'will only output m5C positions in GpC context'
        if GConly and CGonly:
            print 'incompatible options, exiting'
            sys.exit(1)

    if '-m6A-only' in sys.argv:
        do5C = False
        print 'will only output m6A positions'

    m5C = sys.argv[1]
    m6A = sys.argv[2]
    fasta = sys.argv[3]
    outprefix = sys.argv[4]

    GenomeDict={}
    sequence=''
    inputdatafile = open(fasta)
    for line in inputdatafile:
        if line[0]=='>':
            if sequence != '':
                GenomeDict[chr] = ''.join(sequence).upper()
            chr = line.strip().split('>')[1]
            sequence=[]
            Keep=False
            continue
        else:
            sequence.append(line.strip())
    GenomeDict[chr] = ''.join(sequence).upper()

    print 'finished inputting genomic sequence'

    ReadDict = {}

    fm5C = h5py.File(m5C, 'r')
    fm6A = h5py.File(m6A, 'r')

    if do5C:
        if doPrintContext:
            outfile = open(outprefix + '.GC_context_stats', 'w')
            outfile2 = open(outprefix + '.GC_context_stats_6mer', 'w')
        groupC = fm5C['Statistic_Blocks']
        for block in groupC.itervalues():
            reads =  block['read_ids']
            RIDtoReadNameDict = {}
            for rid in reads.attrs.iteritems():
                RIDtoReadNameDict[rid[1]] = rid[0]
            for BB in block.attrs.iteritems():
                if BB[0] == 'chrm':
                    chr = BB[1]
                if BB[0] == 'strand':
                    strand = BB[1]
                if BB[0] == 'start':
                    start = BB[1]
            print 'm5C', chr, start
            for (pos,ll,ridNum) in block['block_stats']:
                rid = RIDtoReadNameDict[ridNum]
                if ReadDict.has_key((chr,strand,rid)):
                    pass
                else:
                    ReadDict[(chr,strand,rid)] = []
                seq = GenomeDict[chr][pos-1:pos+2]
                seq1 = GenomeDict[chr][pos:pos+2]
                seq2 = GenomeDict[chr][pos-1:pos+1]
                if strand == '+':
                    if GConly:
                        if seq2 == 'GC':
                            ReadDict[(chr,strand,rid)].append((pos,ll))
                    elif CGonly:
                        if seq1 == 'CG':
                            ReadDict[(chr,strand,rid)].append((pos,ll))
                    else:
                        if seq1 == 'CG' or seq2 == 'GC':
                            ReadDict[(chr,strand,rid)].append((pos,ll))
                if strand == '-':
                    seq = getReverseComplement(seq)
                    seq1 = getReverseComplement(seq1)
                    seq2 = getReverseComplement(seq2)
                    if GConly:
                        if seq1 == 'GC':
                            ReadDict[(chr,strand,rid)].append((pos,ll))
                    elif CGonly:
                        if seq2 == 'CG':
                            ReadDict[(chr,strand,rid)].append((pos,ll))
                    else:
                        if seq2 == 'CG' or seq1 == 'GC':
                            ReadDict[(chr,strand,rid)].append((pos,ll))
                if doPrintContext:
                    outline = seq + '\t' + str(ll)
                    outfile.write(outline + '\n')
                    if 'GC' in GenomeDict[chr][pos-5:pos+5] or 'CG' in GenomeDict[chr][pos-5:pos+5]:
                        outline = 'CG_GC-6mer' + '\t' + str(ll)
                    else:
                        outline = 'no_CG_GC-6mer' + '\t' + str(ll)
                    outfile2.write(outline + '\n')
        if doPrintContext:
            outfile.close()
            outfile2.close()

        print 'finished processing 5mC file'

    if do6A:
        groupA = fm6A['Statistic_Blocks']
        for block in groupA.itervalues():
            reads =  block['read_ids']
            RIDtoReadNameDict = {}
            for rid in reads.attrs.iteritems():
                RIDtoReadNameDict[rid[1]] = rid[0]
            for BB in block.attrs.iteritems():
                if BB[0] == 'chrm':
                    chr = BB[1]
                if BB[0] == 'strand':
                    strand = BB[1]
                if BB[0] == 'start':
                    start = BB[1]
            print 'm6A', chr, start
            for (pos,ll,ridNum) in block['block_stats']:
                rid = RIDtoReadNameDict[ridNum]
                if ReadDict.has_key((chr,strand,rid)):
                    pass
                else:
                    ReadDict[(chr,strand,rid)] = []
                seq1 = GenomeDict[chr][pos:pos+1]
                if strand == '+':
                    if seq1 == 'A':
                        ReadDict[(chr,strand,rid)].append((pos,ll))
                if strand == '-':
                    if seq1 == 'T':
                        ReadDict[(chr,strand,rid)].append((pos,ll))
                ReadDict[(chr,strand,rid)].append((pos,ll))

        print 'finished processing 6mA file'

    reads = ReadDict.keys()
    reads.sort()

    outfile = open(outprefix + '.reads.tsv', 'w')

    for (chr,strand,rid) in reads:
        ReadDict[(chr,strand,rid)].sort()
        if len(ReadDict[(chr,strand,rid)]) == 0:
            print 'skipping:', (chr,strand,rid), ReadDict[(chr,strand,rid)]
            continue
        outline = chr + '\t' + str(ReadDict[(chr,strand,rid)][0][0]) + '\t' + str(ReadDict[(chr,strand,rid)][-1][0]) + '\t' + strand + '\t' + rid + '\t' + '.'
        Ps = ''
        LLs = ''
        for (pos,ll) in ReadDict[(chr,strand,rid)]:
            Ps = Ps + str(pos) + ','
            LLs = LLs + "{0:.2f}".format(ll) + ','
        outline = outline + '\t' + Ps[0:-1]
        outline = outline + '\t' + LLs[0:-1]
        outfile.write(outline + '\n')

    outfile.close()

    
run()
