# Path: crumbs/bam/flag.py
# def create_flag(bit_tags):
#     'It returns the integer corresponding to the bitwise or of the tags'
#     return reduce(or_, [SAM_FLAG_BITS[t] for t in bit_tags])
# 
# Path: crumbs/settings.py
# def get_setting(key):
#     'It returns the value for one setting'
#     return _settings[key]
# 
# Path: crumbs/utils/bin_utils.py
# def get_num_threads(threads):
#     """It returns num of threads to use in parallel.
# 
#     You can pass to the funaction the  memory you want to use each thread.
#     It calculates the number of treads
#     In megabytes
#     """
#     phisical_threads = os.sysconf('SC_NPROCESSORS_ONLN')
#     if not threads:
#         return 1
#     elif isinstance(threads, bool):
#         return phisical_threads
#     else:
#         return threads
# 
# Path: crumbs/utils/optional_modules.py
# MSG = 'A python package to run this executable is required,'
# BIO = 'biopython'
# BIO_BGZF = 'biopython with Bgzf support'
#     NCBIXML = create_fake_class(MSG + BIO)
#     NCBIWWW = create_fake_class(MSG + BIO)
# def create_fake_class(msg):
#         def __init__(self, *args, **kwargs):
# def create_fake_funct(msg):
#     def FakeRequiredfunct(*args, **kwargs):
#     class FakePythonRequiredClass(object):


import os.path
import shutil
import sys
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from array import array
from crumbs.bam.flag import create_flag
from crumbs.settings import get_setting
from crumbs.utils.bin_utils import get_num_threads
from crumbs.utils.optional_modules import (AlignmentFile, view, index, faidx,
                                           calmd)
def _calmd_bam(bam_fpath, reference_fpath, out_bam_fpath):
    out_fhand = open(out_bam_fpath, 'wb')
    for line in calmd(*["-bAr", bam_fpath, reference_fpath]):
        out_fhand.write(line)
    # out_fhand.write(pysam.calmd(*["-bAr", bam_fpath, reference_fpath]))
    out_fhand.flush()
    out_fhand.close()


def merge_sams(in_fpaths, out_fpath):
    picard_jar = get_setting("PICARD_JAR")

    cmd = ['java', '-jar', picard_jar, 'MergeSamFiles',
           'O={}'.format(out_fpath)]
    for in_fpath in in_fpaths:
        cmd.append('I={}'.format(in_fpath))
    stderr = NamedTemporaryFile(suffix='picard.stderr')
    stdout = NamedTemporaryFile(suffix='picard.stdout')
    try:
        check_call(cmd, stderr=stderr, stdout=stdout)
    except CalledProcessError:
        sys.stderr.write(open(stderr.name).read())
        sys.stdout.write(open(stdout.name).read())

QUAL_TO_SUBSTRACT = 30


def downgrade_read_edges(in_fpath, out_fpath, size,
                         qual_to_substract=QUAL_TO_SUBSTRACT):
    in_sam = AlignmentFile(in_fpath)

# Path: crumbs/bam/flag.py
# def create_flag(bit_tags):
#     'It returns the integer corresponding to the bitwise or of the tags'
#     return reduce(or_, [SAM_FLAG_BITS[t] for t in bit_tags])
# 
# Path: crumbs/settings.py
# def get_setting(key):
#     'It returns the value for one setting'
#     return _settings[key]
# 
# Path: crumbs/utils/bin_utils.py
# def get_num_threads(threads):
#     """It returns num of threads to use in parallel.
# 
#     You can pass to the funaction the  memory you want to use each thread.
#     It calculates the number of treads
#     In megabytes
#     """
#     phisical_threads = os.sysconf('SC_NPROCESSORS_ONLN')
#     if not threads:
#         return 1
#     elif isinstance(threads, bool):
#         return phisical_threads
#     else:
#         return threads
# 
# Path: crumbs/utils/optional_modules.py
# MSG = 'A python package to run this executable is required,'
# BIO = 'biopython'
# BIO_BGZF = 'biopython with Bgzf support'
#     NCBIXML = create_fake_class(MSG + BIO)
#     NCBIWWW = create_fake_class(MSG + BIO)
# def create_fake_class(msg):
#         def __init__(self, *args, **kwargs):
# def create_fake_funct(msg):
#     def FakeRequiredfunct(*args, **kwargs):
#     class FakePythonRequiredClass(object):


# Path: crumbs/bam/bam_tools.py
import os.path
import shutil
import sys
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from array import array
from crumbs.bam.flag import create_flag
from crumbs.settings import get_setting
from crumbs.utils.bin_utils import get_num_threads
from crumbs.utils.optional_modules import (AlignmentFile, view, index, faidx,
                                           calmd)

def _calmd_bam(bam_fpath, reference_fpath, out_bam_fpath):
    out_fhand = open(out_bam_fpath, 'wb')
    for line in calmd(*["-bAr", bam_fpath, reference_fpath]):
        out_fhand.write(line)
    # out_fhand.write(pysam.calmd(*["-bAr", bam_fpath, reference_fpath]))
    out_fhand.flush()
    out_fhand.close()


def merge_sams(in_fpaths, out_fpath):
    picard_jar = get_setting("PICARD_JAR")

    cmd = ['java', '-jar', picard_jar, 'MergeSamFiles',
           'O={}'.format(out_fpath)]
    for in_fpath in in_fpaths:
        cmd.append('I={}'.format(in_fpath))
    stderr = NamedTemporaryFile(suffix='picard.stderr')
    stdout = NamedTemporaryFile(suffix='picard.stdout')
    try:
        check_call(cmd, stderr=stderr, stdout=stdout)
    except CalledProcessError:
        sys.stderr.write(open(stderr.name).read())
        sys.stdout.write(open(stdout.name).read())

QUAL_TO_SUBSTRACT = 30


def downgrade_read_edges(in_fpath, out_fpath, size,
                         qual_to_substract=QUAL_TO_SUBSTRACT):
    in_sam = AlignmentFile(in_fpath)

    out_sam = AlignmentFile(out_fpath, 'wb', template=in_sam)