#!/usr/bin/env python
"""
epic-preprocess
Filter/convert the alignent file

(Visit github.com/endrebak/epic for examples and help.)

Usage:
    epic-convert [--min=MIN] [--max=MAX] [--pe=PE] FILE
    epic-convert --help

Arguments:
    FILE              alignment file
    -M MIN --min MIN  min length of reads [default: 24]
    -m MAX --max MAX  max length of reads [default: 35]
    -q Q --minqual Q  minimum quality of reads [default: 50]
    -p PE --pe PE     paired-ends (bam only) [default: False]

Options:
    -h --help                 show this help message
"""

import logging
from subprocess import Popen, PIPE

from docopt import docopt

args = docopt(__doc__)

from epic.config import logging_settings


def preprocess_bed(args):

    pass


if __name__ == '__main__':

    alignment_file = args["FILE"]
    min_length, max_length = int(args["--min"]), int(args["--max"])
    paired_end = args["--pe"]

    commands = ["bamToBed -i {}"]
    command = "|".join(commands).format(alignment_file)
    proc = Popen(command, shell=True, stdout=PIPE, universal_newlines=True)

    for line in proc.stdout:
        chromosome, start, end, name, score, strand = line.strip().split()
        start, end = int(start), int(end)
        length = end - start
        if (length <= max_length) and (length >= min_length):
            print(line.strip())
