docs: def subset_bamfile(sam, barcodes):
      """
      Subset a SAM/BAM file, keeping only alignments from given
      cellular barcodes
      """
      from pysam import AlignmentFile
  
      start_time = time.time()
  
      sam_file = open_bamfile(sam)
      out_file = AlignmentFile("-", "wh", template=sam_file)
      track = sam_file.fetch(until_eof=True)
  
      # peek at first alignment to determine the annotations
      queryalignment = track.next()
      annotations = detect_alignment_annotations(queryalignment)
      track = itertools.chain([queryalignment], track)
  
      re_string = construct_transformed_regex(annotations)
      parser_re = re.compile(re_string)
      barcodes = set(barcode.strip() for barcode in barcodes)
  
      for count, aln in enumerate(track, start=1):
          if count and not count % 1000000:
              logger.info("Processed %d alignments." % count)
  
          match = parser_re.match(aln.qname)
          tags = aln.tags
  
          if "cellular" in annotations:
              cb = match.group('CB')
              if cb in barcodes:
                  out_file.write(aln)