#!/usr/bin/env python
# Time-stamp: <2012-06-06 15:41:18 Tao Liu>

"""Description: MACS 2 main executable

Copyright (c) 2008,2009 Yong Zhang, Tao Liu <taoliu@jimmy.harvard.edu>
Copyright (c) 2010,2011 Tao Liu <taoliu@jimmy.harvard.edu>

This code is free software; you can redistribute it and/or modify it
under the terms of the Artistic License (see the file COPYING included
with the distribution).

@status: release candidate
@version: $Id$
@author:  Yong Zhang, Tao Liu
@contact: taoliu@jimmy.harvard.edu
"""

# ------------------------------------
# python modules
# ------------------------------------

import os
import sys
import logging
import time
from subprocess import Popen,PIPE
#from optparse import OptionParser
import gzip
import argparse as ap

# ------------------------------------
# own python modules
# ------------------------------------
from MACS2.OptValidator import opt_validate
from MACS2.OutputWriter import *
from MACS2.cProb import binomial_cdf_inv
from MACS2.cPeakModel import PeakModel,NotEnoughPairsException
from MACS2.cPeakDetect import PeakDetect
from MACS2.Constants import *
# ------------------------------------
# Main function
# ------------------------------------
def main():
    """The Main function/pipeline for MACS.
    
    """
    # Parse options...
    argparser = prepare_argparser()
    args = argparser.parse_args()
    subcommand  = args.subcommand_name
    if subcommand == "callpeak":
        from MACS2.callpeak import run
        run( args )
    elif subcommand == "bdgpeakcall":
        from MACS2.bdgpeakcall import run
        run( args )
    elif subcommand == "bdgbroadcall":
        from MACS2.bdgbroadcall import run
        run( args )
    elif subcommand == "bdgcmp":
        from MACS2.bdgcmp import run
        run( args )
    elif subcommand == "randsample":
        from MACS2.randsample import run
        run( args )
    elif subcommand == "filterdup":
        from MACS2.filterdup import run
        run( args )
    elif subcommand == "bdgdiff":
        from MACS2.bdgdiff import run
        run( args )

def prepare_argparser ():
    """Prepare optparser object. New options will be added in this
    function first.
    
    """
#     usage = """%(prog)s [-h] [--version] COMMAND
    
# Please specify a command from the following list:
# {callpeak,filterdup,bdgpeakcall,bdgcmp,randsample,bdgdiff,bdgbroadcall}
    
# Type %(prog)s -h to see a summary of available commands.
# """
    description = "%(prog)s -- Model-based Analysis for ChIP-Sequencing"
    epilog = "For command line options of each command, type: %(prog)s COMMAND -h"
    #Check community site: http://groups.google.com/group/macs-announcement/
    #Source code: https://github.com/taoliu/MACS/"
    # top-level parser
    argparser = ap.ArgumentParser( description = description, epilog = epilog ) #, usage = usage )
    argparser.add_argument("--version", action="version", version="%(prog)s "+MACS_VERSION)
    subparsers = argparser.add_subparsers( dest = 'subcommand_name' ) #help="sub-command help")
    
    # command for 'callpeak'
    add_callpeak_parser( subparsers )
    # command for 'bdgpeakcall'
    add_bdgpeakcall_parser( subparsers )
    
    # command for 'bdgbroadcall'
    add_bdgbroadcall_parser( subparsers )
    
    # command for 'bdgcmp'
    add_bdgcmp_parser( subparsers )
    
    # command for 'randsample'
    add_randsample_parser( subparsers )
    
    # command for 'filterdup'
    add_filterdup_parser( subparsers )
    
    # command for 'bdgdiff'
    add_bdgdiff_parser( subparsers )    
    
    return argparser

def add_callpeak_parser( subparsers ):
    """Add main function 'peak calling' argument parsers.
    """
    argparser_callpeak = subparsers.add_parser("callpeak", help="Main MACS2 Function: Call peaks from alignment results.")
    
    # group for input files
    group_input = argparser_callpeak.add_argument_group( "Input files arguments" )
    group_input.add_argument( "-t", "--treatment", dest = "tfile", type = str, required = True, nargs = "+",
                              help = "ChIP-seq treatment file. If multiple files are given as '-t A B C', then they will all be read and combined. REQUIRED." )
    group_input.add_argument( "-c", "--control", dest = "cfile", type = str, nargs = "*",
                                    help = "Control file. If multiple files are given as '-c A B C', then they will all be read and combined.")
    group_input.add_argument( "-f", "--format", dest = "format", type = str,
                              choices = ("AUTO", "BAM", "SAM", "BED", "ELAND",
                                         "ELANDMULTI", "ELANDEXPORT", "BOWTIE",
                                          "BAMPE"),
                              help = "Format of tag file, \"AUTO\", \"BED\" or \"ELAND\" or \"ELANDMULTI\" or \"ELANDEXPORT\" or \"SAM\" or \"BAM\" or \"BOWTIE\" or \"BAMPE\". The default AUTO option will let MACS decide which format the file is. Please check the definition in 00README file if you choose ELAND/ELANDMULTI/ELANDEXPORT/SAM/BAM/BOWTIE. DEFAULT: \"AUTO\"",
                              default = "AUTO" )
    group_input.add_argument( "-g", "--gsize", dest = "gsize", type = str, default = "hs",
                              help = "Effective genome size. It can be 1.0e+9 or 1000000000, or shortcuts:'hs' for human (2.7e9), 'mm' for mouse (1.87e9), 'ce' for C. elegans (9e7) and 'dm' for fruitfly (1.2e8), Default:hs" )
    group_input.add_argument( "--keep-dup", dest = "keepduplicates", type = str, default = "1",
                              help = "It controls the MACS behavior towards duplicate tags at the exact same location -- the same coordination and the same strand. The default 'auto' option makes MACS calculate the maximum tags at the exact same location based on binomal distribution using 1e-5 as pvalue cutoff; and the 'all' option keeps every tags. If an integer is given, at most this number of tags will be kept at the same location. Default: 1" )
    
    # group for output files
    group_output = argparser_callpeak.add_argument_group( "Output arguments" )
    group_output.add_argument( "-n", "--name", dest = "name", type = str,
                               help = "Experiment name, which will be used to generate output file names. DEFAULT: \"NA\"", 
                               default = "NA" )
    group_output.add_argument( "-B", "--bdg", dest = "store_bdg", action = "store_true",
                               help = "Whether or not to save extended fragment pileup, and local lambda tracks (two files) at every bp into a bedGraph file. DEFAULT: False",
                               default = False )
    group_output.add_argument( "--verbose", dest = "verbose", type = int, default = 2,
                               help = "Set verbose level of runtime message. 0: only show critical message, 1: show additional warning message, 2: show process information, 3: show debug messages. DEFAULT:2" )
    group_output.add_argument( "--trackline", dest="trackline", action="store_true", default = False,
                               help = "Tells MACS to include trackline with bedGraph files. To include this trackline while displaying bedGraph at UCSC genome browser, can show name and description of the file as well. However my suggestion is to convert bedGraph to bigWig, then show the smaller and faster binary bigWig file at UCSC genome browser, as well as downstream analysis. Require -B to be set. Default: Not include trackline." )
    
    group_output.add_argument( "--SPMR", dest = "do_SPMR", action = "store_true", default = False,
                               help = "If True, MACS will save signal per million reads for fragment pileup profiles. Require -B to be set. Default: False" )    
    # group for bimodal
    group_bimodal = argparser_callpeak.add_argument_group( "Shifting model arguments" )
    group_bimodal.add_argument( "-s", "--tsize",  dest = "tsize", type = int, default = None,
                                help = "Tag size. This will overide the auto detected tag size. DEFAULT: Not set")
    group_bimodal.add_argument( "--bw", dest = "bw", type = int, default = 300,
                                help = "Band width for picking regions to compute fragment size. This value is only used while building the shifting model. DEFAULT: 300")
    group_bimodal.add_argument( "-m", "--mfold", dest = "mfold", type = int, default = [5,50], nargs = 2,
                                help = "Select the regions within MFOLD range of high-confidence enrichment ratio against background to build model. Fold-enrichment in regions must be lower than upper limit, and higher than the lower limit. Use as \"-m 10 30\". DEFAULT:5 50" )
    
    group_bimodal.add_argument( "--fix-bimodal", dest = "onauto", action = "store_true",
                                help = "Whether turn on the auto pair model process. If set, when MACS failed to build paired model, it will use the nomodel settings, the '--shiftsize' parameter to shift and extend each tags. Not to use this automate fixation is a default behavior now. DEFAULT: False",
                                default = False )
    group_bimodal.add_argument( "--nomodel", dest = "nomodel", action = "store_true",
                                help = "Whether or not to build the shifting model. If True, MACS will not build model. by default it means shifting size = 100, try to set shiftsize to change it. DEFAULT: False",
                                default = False )
    group_bimodal.add_argument( "--shiftsize", dest = "shiftsize", type = int, default = 100,
                                help = "The arbitrary shift size in bp. When nomodel is true, MACS will use this value as 1/2 of fragment size. DEFAULT: 100 " )
    
    # General options.
    group_callpeak = argparser_callpeak.add_argument_group( "Peak calling arguments" )    
    p_or_q_group = group_callpeak.add_mutually_exclusive_group()
    p_or_q_group.add_argument( "-q", "--qvalue", dest = "qvalue", type = float, default = 0.05,
                               help = "Minimum FDR (q-value) cutoff for peak detection. DEFAULT: 0.05. -q and -p are mutually exclusive." )
    p_or_q_group.add_argument( "-p", "--pvalue", dest = "pvalue", type = float,
                               help = "Pvalue cutoff for peak detection. DEFAULT: not set. -q and -p are mutually exclusive. If pvalue cutoff is set, qvalue will not be calculated and reported as -1 in the final .xls file." )
    # about scaling
    group_callpeak.add_argument( "--to-large", dest = "tolarge", action = "store_true", default = False,
                                help = "When set, scale the small sample up to the bigger sample. By default, the bigger dataset will be scaled down towards the smaller dataset, which will lead to smaller p/qvalues and more specific results. Keep in mind that scaling down will bring down background noise more. DEFAULT: False" )
    group_callpeak.add_argument( "--down-sample", dest = "downsample", action = "store_true", default = False,
                                 help = "When set, random sampling method will scale down the bigger sample. By default, MACS uses linear scaling. Warning: This option will make your result unstable and irreproducible since each time, random reads would be selected. Consider to use 'randsample' script instead. <not implmented>If used together with --SPMR, 1 million unique reads will be randomly picked.</not implemented> Caution: due to the implementation, the final number of selected reads may not be as you expected! DEFAULT: False" )
    
    group_callpeak.add_argument( "--nolambda", dest = "nolambda", action = "store_true",
                                 help = "If True, MACS will use fixed background lambda as local lambda for every peak region. Normally, MACS calculates a dynamic local lambda to reflect the local bias due to potential chromatin structure. ",
                                 default = False )
    group_callpeak.add_argument( "--slocal", dest = "smalllocal", type = int, default = 1000,
                                 help = "The small nearby region in basepairs to calculate dynamic lambda. This is used to capture the bias near the peak summit region. Invalid if there is no control data. If you set this to 0, MACS will skip slocal lambda calculation. *Note* that MACS will always perform a d-size local lambda calculation. The final local bias should be the maximum of the lambda value from d, slocal, and llocal size windows. DEFAULT: 1000 " )
    group_callpeak.add_argument( "--llocal", dest = "largelocal", type = int, default = 10000,
                                 help = "The large nearby region in basepairs to calculate dynamic lambda. This is used to capture the surround bias. If you set this to 0, MACS will skip llocal lambda calculation. *Note* that MACS will always perform a d-size local lambda calculation. The final local bias should be the maximum of the lambda value from d, slocal, and llocal size windows. DEFAULT: 10000." )
    group_callpeak.add_argument( "--shift-control", dest = "shiftcontrol", action = "store_true", default = False,
                                 help = "When set, control tags will be shifted just as ChIP tags according to their strand before the extension of d, slocal and llocal. By default, control tags are extended centered at their current positions regardless of strand. You may consider to turn this option on while comparing two ChIP datasets of different condition but the same factor. DEFAULT: False" )
    group_callpeak.add_argument( "--half-ext", dest = "halfext", action = "store_true", default = False,
                                 help = "When set, MACS extends 1/2 d size for each fragment centered at its middle point. DEFAULT: False" )
    group_callpeak.add_argument( "--broad", dest = "broad", action = "store_true",
                                 help = "If set, MACS will try to call broad peaks by linking nearby highly enriched regions. The linking region is controlled by another cutoff through --linking-cutoff. The maximum linking region length is 4 times of d from MACS. DEFAULT: False", default = False )
    group_callpeak.add_argument( "--broad-cutoff", dest = "broadcutoff", type = float, default = 0.1,
                                 help = "Cutoff for broad region. This option is not available unless --broad is set. If -p is set, this is a pvalue cutoff, otherwise, it's a qvalue cutoff. DEFAULT: 0.1 " )
    group_callpeak.add_argument( "--call-summits", dest="call_summits", action="store_true",
                         help="If set, MACS will use a more sophisticated approach to find all summits in each enriched peak region. DEFAULT: False",default=False)
    
    return

def add_filterdup_parser( subparsers ):
    argparser_filterdup = subparsers.add_parser( "filterdup",
                                                 help = "Remove duplicate reads at the same position, then convert acceptable format to BED format." )
    argparser_filterdup.add_argument( "-t", dest = "tfile", type = str, required = True,
                                      help = "Sequencing alignment file. REQUIRED." )
    argparser_filterdup.add_argument( "-o", dest = "outputfile", type = str,
                                      help = "Output BED file name. If not specified, will write to standard output. DEFAULT: stdout",
                                      default = "stdout" )
    argparser_filterdup.add_argument( "-f", "--format", dest = "format", type = str,
                                      choices=("AUTO","BAM","SAM","BED","ELAND","ELANDMULTI","ELANDEXPORT","BOWTIE"),
                                      help = "Format of tag file, \"AUTO\", \"BED\" or \"ELAND\" or \"ELANDMULTI\" or \"ELANDEXPORT\" or \"SAM\" or \"BAM\" or \"BOWTIE\". The default AUTO option will let '%(prog)s' decide which format the file is. Please check the definition in 00README file if you choose ELAND/ELANDMULTI/ELANDEXPORT/SAM/BAM/BOWTIE. DEFAULT: \"AUTO\"",
                                      default = "AUTO" )
    argparser_filterdup.add_argument( "-g", "--gsize", dest = "gsize", type = str, default = "hs",
                                      help = "Effective genome size. It can be 1.0e+9 or 1000000000, or shortcuts:'hs' for human (2.7e9), 'mm' for mouse (1.87e9), 'ce' for C. elegans (9e7) and 'dm' for fruitfly (1.2e8), DEFAULT:hs" )
    argparser_filterdup.add_argument( "-s", "--tsize", dest = "tsize", type = int,
                                      help = "Tag size. This will overide the auto detected tag size. DEFAULT: Not set" )
    argparser_filterdup.add_argument( "-p", "--pvalue", dest = "pvalue", type = float,
                                      help = "Pvalue cutoff for binomial distribution test. DEFAULT:1e-5" )
    argparser_filterdup.add_argument( "--keep-dup", dest = "keepduplicates", type = str, default = "auto",
                                      help = "It controls the '%(prog)s' behavior towards duplicate tags at the exact same location -- the same coordination and the same strand. The default 'auto' option makes '%(prog)s' calculate the maximum tags at the exact same location based on binomal distribution using given -p as pvalue cutoff; and the 'all' option keeps every tags (useful if you only want to convert formats). If an integer is given, at most this number of tags will be kept at the same location. Default: auto" )
    argparser_filterdup.add_argument( "--verbose", dest = "verbose", type = int, default = 2,
                                      help = "Set verbose level. 0: only show critical message, 1: show additional warning message, 2: show process information, 3: show debug messages. If you want to know where are the duplicate reads, use 3. DEFAULT:2" )
    return

def add_bdgpeakcall_parser( subparsers ):
    """Add function 'peak calling on bedGraph' argument parsers.
    """    
    argparser_bdgpeakcall = subparsers.add_parser( "bdgpeakcall",
                                                   help = "Call peaks from bedGraph output." )
    argparser_bdgpeakcall.add_argument( "-i", "--ifile", dest = "ifile", type = str, required = True,
                                        help = "MACS score in bedGraph. REQUIRED" )
    argparser_bdgpeakcall.add_argument( "-c", "--cutoff" , dest = "cutoff", type = float,
                                        help = "Cutoff depends on which method you used for score track. If the file contains pvalue scores from MACS2, score 5 means pvalue 1e-5. DEFAULT: 5", default = 5 )
    argparser_bdgpeakcall.add_argument( "-l", "--min-length", dest = "minlen", type = int,
                                       help = "minimum length of peak, better to set it as d value. DEFAULT: 200", default = 200 )
    argparser_bdgpeakcall.add_argument( "-g", "--max-gap", dest = "maxgap", type = int,
                                       help = "maximum gap between significant points in a peak, better to set it as tag size. DEFAULT: 30", default = 30 )
    argparser_bdgpeakcall.add_argument( "-o", "--o-prefix", dest = "oprefix", default = "peak", type = str,
                                        help = "output file prefix, DEFAULT: peak" )
    argparser_bdgpeakcall.add_argument( "--call-summits", dest="call_summits", action="store_true",
                         help="If set, MACS will use a more sophisticated approach to find all summits in each enriched peak region. DEFAULT: False",default=False)
    argparser_bdgpeakcall.add_argument("--no-trackline", dest="trackline", action="store_false", default=True,
                         help="Tells MACS not to include trackline with bedGraph files. The trackline is required by UCSC.")
    return

def add_bdgbroadcall_parser( subparsers ):
    """Add function 'broad peak calling on bedGraph' argument parsers.
    """
    argparser_bdgbroadcall = subparsers.add_parser( "bdgbroadcall",
                                                    help = "Call broad peaks from bedGraph output." )
    argparser_bdgbroadcall.add_argument( "-i", "--ifile", dest = "ifile" , type = str, required = True,
                                         help = "MACS score in bedGraph. REQUIRED" )
    argparser_bdgbroadcall.add_argument( "-c", "--cutoff-peak", dest = "cutoffpeak", type = float,
                                         help = "Cutoff for peaks depending on which method you used for score track. If the file contains qvalue scores from MACS2, score 2 means qvalue 0.01. DEFAULT: 2",
                                         default = 2 )
    argparser_bdgbroadcall.add_argument( "-C", "--cutoff-link", dest = "cutofflink", type = float,
                                         help = "Cutoff for linking regions/low abundance regions depending on which method you used for score track. If the file contains qvalue scores from MACS2, score 1 means qvalue 0.1, and score 0.3 means qvalue 0.5. DEFAULT: 1", default = 1 )
    argparser_bdgbroadcall.add_argument( "-l", "--min-length", dest = "minlen", type = int,
                                         help = "minimum length of peak, better to set it as d value. DEFAULT: 200", default = 200 )
    argparser_bdgbroadcall.add_argument( "-g", "--lvl1-max-gap", dest = "lvl1maxgap", type = int,
                                         help = "maximum gap between significant peaks, better to set it as tag size. DEFAULT: 30", default = 30 )
    argparser_bdgbroadcall.add_argument( "-G", "--lvl2-max-gap", dest = "lvl2maxgap", type = int,
                                         help = "maximum linking between significant peaks, better to set it as 4 times of d value. DEFAULT: 800", default = 800)
    argparser_bdgbroadcall.add_argument( "-o", "--o-prefix", dest = "oprefix", default = "peak", type = str,
                                         help = "output file prefix, DEFAULT: peak" )
    return
    
def add_bdgcmp_parser( subparsers ):
    """Add function 'peak calling on bedGraph' argument parsers.
    """
    argparser_bdgcmp = subparsers.add_parser( "bdgcmp",
                                              help = "Deduct noise by comparing two signal tracks in bedGraph." )
    argparser_bdgcmp.add_argument( "-t", "--tfile", dest = "tfile", type = str, required = True,
                                   help = "Treatment bedGraph file, e.g. *_treat_pileup.bdg from MACSv2. REQUIRED")
    argparser_bdgcmp.add_argument( "-c", "--cfile", dest = "cfile", type = str, required = True,
                                   help = "Control bedGraph file, e.g. *_control_lambda.bdg from MACSv2. REQUIRED")
    argparser_bdgcmp.add_argument( "-T", "--tdepth", dest = "tdepth", type = float, default = 1.0,
                                   help = "The sequencing depth in million for treatment bedGraph file. e.g. If bedGraph is generated by MACS2 with --SPMR option, you can set 1.0 here. If bedGraph is generated by MACS2 without --SPMR option, you can set it as the depth of smaller/larger sample according to your MACS2 setting. If you don't want any normalization on sequencing depth, please set both -T and -C as 1.0. DEFAULT: 1.0")
    argparser_bdgcmp.add_argument( "-C", "--cdepth", dest = "cdepth", type = float, default = 1.0,
                                   help = "The sequencing depth in million for control bedGraph file. e.g. If bedGraph is generated by MACS2 with --SPMR option, you can set 1.0 here. If bedGraph is generated by MACS2 without --SPMR option, you can set it as the depth of smaller/larger sample according to your MACS2 setting. If you don't want any normalization on sequencing depth, please set both -T and -C as 1.0. DEFAULT: 1.0")                                   
    argparser_bdgcmp.add_argument( "-p", "--pseudocount", dest = "pseudocount", type = float, default = 0.0,
                                   help = "The pseudocount used for calculating logLR, logFE or FE. The count will be applied after normalization of sequencing depth. DEFAULT: 0.0, no pseudocount is applied.")     
    argparser_bdgcmp.add_argument( "-o", "--output", dest = "ofile", type = str, required = True,
                                   help = "The output bedGraph file to write scores. REQUIRED" )
    argparser_bdgcmp.add_argument( "-m", "--method", dest = "method", type = str,
                                   choices = ( "ppois", "qpois", "subtract", "logFE", "FE", "logLR" ),
                                   help = "Method to use while calculating a score in any bin by comparing treatment value and control value. Available choices are: ppois, qpois, subtract, logFE, and logLR,. They represent Poisson Pvalue (-log10(pvalue) form) using control as lambda and treatment as observation, q-value through a BH process for poisson pvalues, subtraction from treatment, linear scale fold enrichment, log10 fold enrichment, log10 likelihood between ChIP-enriched model and open chromatin model (with or without pseudocount). Default option is ppois.",default="ppois")
    return
    
def add_randsample_parser( subparsers ):
    argparser_randsample = subparsers.add_parser( "randsample",
                                                  help = "Randomly sample number/percentage of total reads." )
    argparser_randsample.add_argument( "-t", dest = "tfile", type = str, required = True,
                                       help = "Sequencing alignment file. REQUIRED." )
    p_or_n_group = argparser_randsample.add_mutually_exclusive_group( required = True )
    p_or_n_group.add_argument( "-p", "--percentage", dest = "percentage", type = float,
                               help = "Percentage of tags you want to keep. Input 80.0 for 80%%. This option can't be used at the same time with -n/--num. REQUIRED")
    p_or_n_group.add_argument( "-n", "--number", dest = "number", type = float,
                               help = "Number of tags you want to keep. Input 8000000 or 8e+6 for 8 million. This option can't be used at the same time with -p/--percent. Note that the number of tags in output is approximate as the number specified here. REQUIRED" )
    argparser_randsample.add_argument( "-o", dest = "outputfile", type = str,
                                      help = "Output BED file name. If not specified, will write to standard output. DEFAULT: stdout",
                                      default = None)
    argparser_randsample.add_argument( "-s", "--tsize", dest = "tsize", type = int, default = None,
                                       help = "Tag size. This will overide the auto detected tag size. DEFAULT: Not set")
    argparser_randsample.add_argument( "-f", "--format", dest = "format", type = str,
                                       choices=("AUTO","BAM","SAM","BED","ELAND","ELANDMULTI","ELANDEXPORT","BOWTIE"),                                       
                                       help = "Format of tag file, \"AUTO\", \"BED\" or \"ELAND\" or \"ELANDMULTI\" or \"ELANDEXPORT\" or \"SAM\" or \"BAM\" or \"BOWTIE\". The default AUTO option will %(prog)s decide which format the file is. Please check the definition in 00README file if you choose ELAND/ELANDMULTI/ELANDEXPORT/SAM/BAM/BOWTIE. DEFAULT: \"AUTO\"",
                                       default = "AUTO" )
    argparser_randsample.add_argument( "--verbose", dest = "verbose", type = int, default = 2,
                                       help = "Set verbose level. 0: only show critical message, 1: show additional warning message, 2: show process information, 3: show debug messages. If you want to know where are the duplicate reads, use 3. DEFAULT:2" )
    return
    
def add_bdgdiff_parser( subparsers ):
    argparser_bdgdiff = subparsers.add_parser( "bdgdiff",
                                               help = "Differential peak detection based on peakcalls and bedGraph tracks." )
    argparser_bdgdiff.add_argument( "--bed1",dest = "peak1", type = str, required = True,
                                    help = "Peak regions of condition 1. REQUIRED" )
    argparser_bdgdiff.add_argument( "--bed2", dest = "peak2", type = str, required = True,
                                    help = "Peak regions of condition 2. REQUIRED" )
    argparser_bdgdiff.add_argument( "--t1", dest = "t1bdg", type = str, required = True,
                                    help = "MACS pileup bedGraph for condition 1. REQUIRED" )
    argparser_bdgdiff.add_argument( "--t2", dest="t2bdg", type = str, required = True,
                                    help = "MACS pileup bedGraph for condition 2. REQUIRED" )
    argparser_bdgdiff.add_argument( "-C", "--cutoff", dest = "cutoff", type = float,
                                    choices = ( 0.05, 0.01 ),
                                    help = "Cutoff for GFOLD. Can only be 0.05, or 0.01. DEFAULT: 0.01", default = 0.01 )
    argparser_bdgdiff.add_argument( "-o", "--o-prefix", dest = "oprefix", default = "diffpeak", type = str,
                                    help = "output file prefix, DEFAULT: diffpeak" )
    return

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.stderr.write("User interrupt me! ;-) Bye!\n")
        sys.exit(0)
