##################################
#                                #
# Last modified 2018/06/13       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import os
import string
import numpy as np

def run():

    if len(sys.argv) < 2:
        print 'usage: python %s motifs.meme outfile' % sys.argv[0]
        sys.exit(1)

    MEME = sys.argv[1]
    outfilename = sys.argv[2]

    outfile = open(outfilename,'w')

    linelist = open(MEME)
    InMotif = False
    outline = ''
    for line in linelist:
        if line.startswith('ALPHABET'):
            continue
        if line.strip() == '':
            continue
        if line.startswith('MOTIF '):
            if outline != '':
                outline = outline + '\t' + str(bits)
                outfile.write(outline + '\n')
            InMotif = True
            motifID = line.strip().split(' ')[1]
            motifName = line.strip().split(' ')[2]
            outline = motifID + '\t' + motifName
            bits = 0
            continue
        if line.startswith('URL '):
            InMotif = False
            continue
        if InMotif:
            if line.startswith('letter-probability'):
                continue
            newline = line.strip()
            while '  ' in newline:
                newline = newline.replace('  ',' ')
            fields = newline.strip().split(' ')
            b = 2
            for f in fields:
                fb = float(f)
                if fb == 0:
                    pass
                else:      
                    b = b - (-fb*np.log2(fb))
            bits += b

    outline = outline + '\t' + str(bits)
    outfile.write(outline + '\n')

run()

