# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):


import os
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import ri, load_qname_sidecar, parse_qname, score_alignment_error, tag_alignment

  :param bam_fp_l:
  :return:
  """
  bl = [bam_fp.fetch(until_eof=True) for bam_fp in bam_fp_l]
  while 1:
    rl = [next(bam_fp, None) for bam_fp in bl]
    if any(rl):
      for n, r in enumerate(rl):
        if r is None: continue
        if r.flag & 0x900 != 0: continue  # Not primary alignment
        yield n, r
    else:
      break


def main(bam_in_l, out_prefix, criterion, threshold, sidecar_fname=None):
  """

  :param bam_in_l:
  :param out_prefix:
  :param criterion: {'d_err', 'MQ', 'mapped', 'p_diff'}
  :param threshold:
  :param simulated:
  :param sidecar_fname
  :return:
  """
  assert len(bam_in_l) <= MAX_ORIGINS, "Can't do more than {} sets".format(MAX_ORIGINS)

  bam_fp_l = [pysam.AlignmentFile(bam_in) for bam_in in bam_in_l]

# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):


# Path: mitty/benchmarking/partition_bams.py
import os
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import ri, load_qname_sidecar, parse_qname, score_alignment_error, tag_alignment


  :param bam_fp_l:
  :return:
  """
  bl = [bam_fp.fetch(until_eof=True) for bam_fp in bam_fp_l]
  while 1:
    rl = [next(bam_fp, None) for bam_fp in bl]
    if any(rl):
      for n, r in enumerate(rl):
        if r is None: continue
        if r.flag & 0x900 != 0: continue  # Not primary alignment
        yield n, r
    else:
      break


def main(bam_in_l, out_prefix, criterion, threshold, sidecar_fname=None):
  """

  :param bam_in_l:
  :param out_prefix:
  :param criterion: {'d_err', 'MQ', 'mapped', 'p_diff'}
  :param threshold:
  :param simulated:
  :param sidecar_fname
  :return:
  """
  assert len(bam_in_l) <= MAX_ORIGINS, "Can't do more than {} sets".format(MAX_ORIGINS)

  bam_fp_l = [pysam.AlignmentFile(bam_in) for bam_in in bam_in_l]

  long_qname_table = load_qname_sidecar(sidecar_fname) if sidecar_fname else None