#! /usr/bin/env python
from optparse import OptionParser
import tarfile
import os
import re
import shutil
import subprocess

SMART_PATH = "%s/SMART" % os.environ["REPET_PATH"]

def toTar(tarFileName, directory):
    fileName = os.path.splitext(tarFileName)[0]
    fileNameBaseName = os.path.basename(fileName)
    tfile = tarfile.open(fileName + ".tmp.tar", "w")
    list = os.listdir(directory)
    for file in list:
        if re.search(str(fileNameBaseName), file):
            tfile.add(file)
    os.system("mv %s %s" % (fileName + ".tmp.tar", options.outTarFileName))
    tfile.close()
    

if __name__ == "__main__":
    
    # parse command line
    description = "Get Read Distribution v1.0.1: Plot the number of identical reads and give the most represented. [Category: Visualization]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input",     dest="inputFileName",  action="store",               type="string", help="input file sequence [compulsory] [format: file in sequence format given by -f]")
    parser.add_option("-f", "--format",    dest="format",         action="store",               type="string", help="format of the file [compulsory] [format: sequence file format]")
    parser.add_option("-n", "--number",    dest="number",         action="store", default=None, type="int",    help="keep the best n    [format: int]")
    parser.add_option("-p", "--percent",   dest="percent",        action="store", default=None, type="float",  help="keep the best n\% [format: float]")
    parser.add_option("-o", "--output",    dest="outTarFileName", action="store",               type="string", help="output file [compulsory] [format: zip]")

    (options, args) = parser.parse_args()


    absPath = os.getcwd()
    print "the current path is :", absPath
    directory = "/tmp/wrappGetReadDistribution"
    print "the dir path is :", directory
    if not os.path.exists(directory):
        os.makedirs(directory)
    os.chdir(directory)
    if options.inputFileName != None and options.format != None and options.outTarFileName != None:
        outputFileName = os.path.splitext(os.path.basename(options.outTarFileName))[0]
        cmd = "python %s/Java/Python/getReadDistribution.py -i %s -f %s -o %s -D %s" % (SMART_PATH, options.inputFileName, options.format, outputFileName, directory)
    if options.number != None :
        cmd += " -n %s" % options.number
    if options.percent != None :
        cmd += " -p %s" % options.percent
    print "cmd is: ", cmd    
    status = subprocess.call(cmd, shell=True)
    if status != 0:
            raise Exception("Problem with the execution of command!")
    toTar(options.outTarFileName, directory)
    shutil.rmtree(directory)
    
