# Path: mitty/lib/bedfile.py
# def read_bed(bed_fname):
#   return list(map(lambda x: (x[0], int(x[1]), int(x[2])), map(lambda x: x.split(), open(bed_fname, 'r').readlines())))


import logging
import time
import pysam
from mitty.lib.bedfile import read_bed
      # lv -> (pos, ref, alt)
      if g:
        if (lv[0] == _v.pos) & (lv[1] == _v.ref) & (lv[2] == alt):
          is_duplicate = True
          logger.debug(
            'Duplicate line {}:{} {} -> {}'.format(_v.contig, _v.pos, _v.ref, _v.alts))
          break
    return is_duplicate


def prepare_variant_file(fname_in, sample, bed_fname, fname_out, write_mode='w'):
  """Prepare a variant file with only the given sample, complex and illegal variant calls
  filtered out, and restricted to the given bed file

  :param fname_in:
  :param sample:
  :param bed_fname:
  :param fname_out:
  :return: - output is to file
  """
  logger.debug('Starting filtering ...')
  t0 = time.time()

  mode = 'rb' if fname_in.endswith('bcf') else 'r'
  vcf_in = pysam.VariantFile(fname_in, mode)
  vcf_in.subset_samples([sample])
  vcf_out = pysam.VariantFile(fname_out, mode=write_mode, header=vcf_in.header)
  processed_cnt, exclude_cnt, include_cnt = 0, 0, 0
  contig_dict = set()


# Path: mitty/lib/bedfile.py
# def read_bed(bed_fname):
#   return list(map(lambda x: (x[0], int(x[1]), int(x[2])), map(lambda x: x.split(), open(bed_fname, 'r').readlines())))


# Path: mitty/lib/vcfio.py
import logging
import time
import pysam
from mitty.lib.bedfile import read_bed

      # lv -> (pos, ref, alt)
      if g:
        if (lv[0] == _v.pos) & (lv[1] == _v.ref) & (lv[2] == alt):
          is_duplicate = True
          logger.debug(
            'Duplicate line {}:{} {} -> {}'.format(_v.contig, _v.pos, _v.ref, _v.alts))
          break
    return is_duplicate


def prepare_variant_file(fname_in, sample, bed_fname, fname_out, write_mode='w'):
  """Prepare a variant file with only the given sample, complex and illegal variant calls
  filtered out, and restricted to the given bed file

  :param fname_in:
  :param sample:
  :param bed_fname:
  :param fname_out:
  :return: - output is to file
  """
  logger.debug('Starting filtering ...')
  t0 = time.time()

  mode = 'rb' if fname_in.endswith('bcf') else 'r'
  vcf_in = pysam.VariantFile(fname_in, mode)
  vcf_in.subset_samples([sample])
  vcf_out = pysam.VariantFile(fname_out, mode=write_mode, header=vcf_in.header)
  processed_cnt, exclude_cnt, include_cnt = 0, 0, 0
  contig_dict = set()


  for region in read_bed(bed_fname):