code: def alignment_to_reads(
      sam_merged,
      output_dir,
      parameters=DEFAULT_PARAMETERS,
      save_memory=True,
      *bin_fasta
  ):
      def get_file_string(file_thing):
          try:
              file_string = file_thing.name
          except AttributeError:
              file_string = str(file_thing)
          return file_string
      bin_chunks = set()
      for bin_file in bin_fasta:
          for record in SeqIO.parse(bin_file, "fasta"):
              bin_chunks.add((get_file_string(bin_file), record.id))
      chunk_size = int(parameters["chunk_size"])
      mapq_threshold = int(parameters["mapq_threshold"])
      def read_name(read):
          return read.query_name.split()[0]
      def get_base_name(bin_file):
          base_name = ".".join(os.path.basename(bin_file).split(".")[:-1])
          output_path = os.path.join(
              output_dir, "{}.readnames".format(base_name)
          )
          return output_path
      if save_memory:
          opened_files = dict()
      else:
          read_names = dict()
      with pysam.AlignmentFile(sam_merged, "rb") as alignment_merged_handle:
          for (my_read_name, alignment_pool) in itertools.groupby(
              alignment_merged_handle, read_name
          ):
              for my_alignment in alignment_pool:
                  relative_position = my_alignment.reference_start
                  contig_name = my_alignment.reference_name
                  chunk_position = relative_position // chunk_size
                  chunk_name = "{}_{}".format(contig_name, chunk_position)
                  quality_test = my_alignment.mapping_quality > mapq_threshold
                  for bin_file in bin_fasta:
                      chunk_tuple = (bin_file, chunk_name)
                      if chunk_tuple in bin_chunks and quality_test:
                          if save_memory:
                              output_path = get_base_name(bin_file)
                              try:
                                  output_handle = opened_files[bin_file]
                              except KeyError:
                                  output_handle = open(output_path, "w")
                                  opened_files[bin_file] = output_handle
                              output_handle.write("@{}\n".format(my_read_name))
                          else:
                              try:
                                  read_names[my_read_name].append(bin_file)
                              except KeyError:
                                  read_names[my_read_name] = [bin_file]
      for file_handle in opened_files.values():
          file_handle.close()
      if save_memory:
          return opened_files.keys()
      else:
          return read_names