#! /opt/gensoft/exe/graph_coverage/0.2/venv/bin/python2.7
"""

"""
import matplotlib.pyplot as plt
import matplotlib
from optparse import OptionParser
import numpy
import os
import sys
import time

VERSION="0.2"

def plot_along_chr(mat, ax, ylim, window_len):
    size_mat = len(mat)
    if window_len == 1 and size_mat >= 2000000 :
        window_len = size_mat / 1000000 # integer division
    axe_x    = range(0, size_mat, window_len)
    axe_y    = range(0, size_mat, window_len)
    for idx in xrange(1, len(axe_x)+1):
        axe_y[idx] = sum( mat[ axe_x[idx-1]:axe_x[idx] ], 0 ) / window_len
        if axe_y[idx] > ylim:
            axe_y[idx] = ylim
            


if __name__ == '__main__':

    """ Main function, deals with arguments and launch program """
    
    parser = OptionParser(version="%prog 0.1")
    parser.add_option("-f", dest="files", action="append", default=None,
                      type="string",
                      help="coverage file (can be used multiple times)")
    parser.add_option("-n", dest="names", action="append", default=None,
                      type="string",
                      help="strain name corresponding to the coverage file. \
                      Can be used multiple times with the same order as -f")
    parser.add_option("-l", dest="file_list", default=None, type="string",
                      help="File containing a list of path to the coverage files.")
    parser.add_option("-i", dest="name_file", default=None, type="string",
                      help="File containing a list of strain in the same order \
                      as in the file given for -l")
    parser.add_option("-y", dest="ylim", default=sys.maxint, type="int",
                      help="maximum value for the y axis")
    parser.add_option("-w", dest="win_len", default=1, type="int",
                      help="window size for the average computation [1]")
    parser.add_option("-p", dest="position_col", default=1, type="int",
                      help="index of the column containing the position [1] \
                      in the coverage file(s) (index begins at 1)")
    parser.add_option("-d", dest="depth_col", default=2, type="int",
                      help="index of the column containing the coverage [2] \
                      in the coverage file(s) (index begins at 1)")
    parser.add_option("-s", dest="separator", default="tab", type="string",
                      help="column separator used in the coverage file(s) tab,\
                       comma, semicolon, blank or multiblank [tab]")
    parser.add_option("-e", dest="extra_info", action="append", default=[],
                      type="string",
                      help="String existing in some/each line(s) of the depth file \
                      but that must be removed. Can be used multiple times.")
    
    if not sys.argv[1:] :
        sys.argv.append('-h')

    prog_name = os.path.basename(sys.argv[0])
    (options, args) = parser.parse_args()

    if options.win_len:
        win_len = int(options.win_len)
        
    if options.ylim:
        ylim = int(options.ylim)

    separator_dict = {'tab'        : "\t",
                      'blank'      : "\s",
                      'multiblank' : None,
                      'comma'      : ",",
                      'semicolon'  : ";"}
    try:
        separator = separator_dict[options.separator]
    except KeyError, msg:
        parser.error("%sInvalid separator.%s" %(os.linesep, os.linesep))

    pos_col, depth_col = options.position_col - 1, options.depth_col - 1

    file_list = []
    if options.files and options.file_list:
        parser.error("%sPlease provide either -l or -f, not both. %s" \
                     %(os.linesep, os.linesep))
    elif options.files:
        file_list.extend(options.files)
    elif options.file_list:
        with open(options.file_list,"r") as in_fh:
            for line in in_fh:
                filename = line.rstrip('\r\n')
                filename = filename.strip()
                filename = filename.replace('"','')
                filename = filename.replace("'","")
                if not filename or filename.startswith('#'):
                    continue
                file_list.append(filename)
    else:
        parser.error("%sNo -f nor -l option detected. Please provide one. %s" \
                     %(os.linesep, os.linesep))

    nb_err = 0    
    for filename in file_list:
        if not os.access(filename, os.R_OK):
            print >> sys.stderr, "%sFile %s is not readable or reachable%s" \
                  %(os.linesep, filename, os.linesep)
            nb_err += 1
    if nb_err:
        parser.error("%sProblem to access %d files%s" %(os.linesep, nb_err,
                                                        os.linesep))

    name_list = []    
    if options.names and options.name_file:
        parser.error("%sPlease provide either -n or -i, not both.%s" \
                     %(os.linesep, os.linesep))
    elif options.names:
        name_list.extend(options.names)
    elif options.name_file:
        with open(options.name_file,"r") as in_fh:
            for line in in_fh:
                name = line.rstrip('\r\n')
                name = name.strip()
                name = name.replace('"','')
                name = name.replace("'","")
                if not name or name.startswith('#'):
                    continue
                name_list.append(name)
    else:
        parser.error("%sNo -n nor -i option detected. Please provide one.%s" \
                     %(os.linesep, os.linesep))

    if len(name_list) != len(file_list):
        parser.error("%sNumber of strain names (%d) and number of \
depth files (%d) are different%s" \
                     %( os.linesep, len(name_list), len(file_list), os.linesep ))


    label_size = 15 - len(file_list)
    
    
    fig, axes = plt.subplots(nrows=len(file_list), ncols=1, sharex=True,
                             sharey=True, squeeze=True)

    for i, filename in enumerate(file_list):
        name         = name_list[i]
        axe_x, axe_y = [0], [0]
        nb_slice     = 0
        idx          = 0
        mean_cov     = 0
        t1 = time.time()
        with open(filename,"r") as cov_fh :
            print >>sys.stdout, "Loading file %s" %filename
            line = cov_fh.readline()
            while line :
                # clean line
                line = line.rstrip('\r\n')
                line = line.replace('"','')
                line = line.replace("'","")
                for strng in options.extra_info:
                    line = line.replace(strng,'')
                if not line or line.startswith('#'):
                    line = cov_fh.readline()
                    continue
                if not separator:
                    line = line.strip()
                elts = line.split(separator)
                try:
                    pos, depth = int( elts[pos_col] ), float( elts[depth_col] )
                except IndexError:
                    print >>sys.stderr, "line '%s' ignored: doesn't contain \
2 columns with separator %s" \
                          %(line, pos_col+1, depth_col+1, options.separator)
                    line = cov_fh.readline()
                    continue
                except ValueError:
                    print >>sys.stderr, "line '%s' ignored: one of the 2 columns \
 (%d, %d) doesn't contain an integer/ a float respectively" \
                          %(line, pos_col+1, depth_col+1)
                    line = cov_fh.readline()
                    continue
                mean_cov += depth
                idx      += 1
                if(idx == win_len):
                    mean_cov /= float(win_len)
                    axe_x.append(pos)
                    if mean_cov > ylim:
                        axe_y.append(ylim)
                    else:
                        axe_y.append(mean_cov)
                    idx      = 0
                    mean_cov = 0
                line = cov_fh.readline()

        if isinstance(axes, matplotlib.axes.Axes) :
            ax = axes
        else:
            ax = axes[i:i+1][0]
        ax.grid(True)
        ax.plot(axe_x, axe_y)
        ax.set_xlabel(name, fontsize=15)
        ax.set_ylabel('Read coverage', fontsize=label_size)
        plt.setp(ax.get_yticklabels(), size=label_size)
        plt.setp(ax.get_xticklabels(), size=label_size,rotation=30,ha='right')
        plt.tight_layout()
    fig.canvas.draw()
    plt.show()
