##################################
#                                #
# Last modified 2017/12/11       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import os
import string

def run():

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

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

    outfile = open(outfilename,'w')

    linelist = open(MEME)
    InMotif = False
    for line in linelist:
        if line.startswith('ALPHABET'):
            continue
        if line.strip() == '':
            continue
        if line.startswith('MOTIF '):
            InMotif = True
            motifID = line.strip().split(' ')[1]
            motifName = line.strip().split(' ')[2]
            outline = '>' + motifID + '_' + motifName + '\t' + motifID + '_' + motifName + '/meme\t0'
            outfile.write(outline + '\n')
            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(' ')
            outline = ''
            for f in fields:
                 outline = outline + f.strip() + '\t'
            outfile.write(outline.strip() + '\n')

run()

