# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
#     samFlag = int(samFields.flag)
#     # Only create a BED entry if the read was aligned
#     if (not (samFlag & 0x0004)) and samFields.pos:
#             name = samFields.qname
#             seq = name.split("-")[1]
#             chrom = samFields.rname
#             start = str(int(samFields.pos))
#             end = str(int(samFields.pos) + len(seq) - 1)
#             strand = getStrand(samFlag)
#             # Write out the BED entry
#             return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" %  (chrom, start, end, name, strand))
#     else:
#             return False
# 
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
#     try:
#         return subprocess.check_output(["which", cmd]).strip()
#     except subprocess.CalledProcessError:
#         return None
# 
# def run(cmd, data=None, checks=None, region=None, log_error=True,
#         log_stdout=False):
#     """Run the provided command, logging details and checking for errors.
#     """
#     try:
#         logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
#         _do_run(cmd, checks, log_stdout)
#     except:
#         if log_error:
#             logger.info("error at command")
#         raise


from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools
    """get all sequences from on cluster"""
    seqs1 = data[c1]['seqs']
    seqs2 = data[c2]['seqs']
    seqs = list(set(seqs1 + seqs2))
    names = []
    for s in seqs:
        if s in seqs1 and s in seqs2:
            names.append("both")
        elif s in seqs1:
            names.append(c1)
        else:
            names.append(c2)
    return seqs, names

def get_precursors_from_cluster(c1, c2, data):
    loci1 = data[c1]['loci']
    loci2 = data[c2]['loci']
    return {c1:loci1, c2:loci2}

def map_to_precursors(seqs, names, loci, out_file, args):
    """map sequences to precursors with razers3"""
    with make_temp_directory() as temp:
        pre_fasta = os.path.join(temp, "pre.fa")
        seqs_fasta = os.path.join(temp, "seqs.fa")
        out_sam = os.path.join(temp, "out.sam")
        pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
        out_precursor_file = out_file.replace("tsv", "fa")
        seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)

        # print(open(pre_fasta).read().split("\n")[1])

# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
#     samFlag = int(samFields.flag)
#     # Only create a BED entry if the read was aligned
#     if (not (samFlag & 0x0004)) and samFields.pos:
#             name = samFields.qname
#             seq = name.split("-")[1]
#             chrom = samFields.rname
#             start = str(int(samFields.pos))
#             end = str(int(samFields.pos) + len(seq) - 1)
#             strand = getStrand(samFlag)
#             # Write out the BED entry
#             return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" %  (chrom, start, end, name, strand))
#     else:
#             return False
# 
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
#     try:
#         return subprocess.check_output(["which", cmd]).strip()
#     except subprocess.CalledProcessError:
#         return None
# 
# def run(cmd, data=None, checks=None, region=None, log_error=True,
#         log_stdout=False):
#     """Run the provided command, logging details and checking for errors.
#     """
#     try:
#         logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
#         _do_run(cmd, checks, log_stdout)
#     except:
#         if log_error:
#             logger.info("error at command")
#         raise


# Path: seqcluster/libs/read.py
from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools

    """get all sequences from on cluster"""
    seqs1 = data[c1]['seqs']
    seqs2 = data[c2]['seqs']
    seqs = list(set(seqs1 + seqs2))
    names = []
    for s in seqs:
        if s in seqs1 and s in seqs2:
            names.append("both")
        elif s in seqs1:
            names.append(c1)
        else:
            names.append(c2)
    return seqs, names

def get_precursors_from_cluster(c1, c2, data):
    loci1 = data[c1]['loci']
    loci2 = data[c2]['loci']
    return {c1:loci1, c2:loci2}

def map_to_precursors(seqs, names, loci, out_file, args):
    """map sequences to precursors with razers3"""
    with make_temp_directory() as temp:
        pre_fasta = os.path.join(temp, "pre.fa")
        seqs_fasta = os.path.join(temp, "seqs.fa")
        out_sam = os.path.join(temp, "out.sam")
        pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
        out_precursor_file = out_file.replace("tsv", "fa")
        seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)

        # print(open(pre_fasta).read().split("\n")[1])

        if find_cmd("razers3"):