code: def _split_by_ready_regions(ext, file_key, dir_ext_fn):
      
      def _sort_by_size(region_w_bams):
          region, _ = region_w_bams
          _, start, end = region
          return end - start
      def _assign_bams_to_regions(data):
          """Ensure BAMs aligned with input regions, either global or individual.
          """
          for i, region in enumerate(data["region"]):
              work_bams = []
              for xs in data["region_bams"]:
                  if len(xs) == 1:
                      work_bams.append(xs[0])
                  else:
                      work_bams.append(xs[i])
              for work_bam in work_bams:
                  assert os.path.exists(work_bam), work_bam
              yield region, work_bams
      def _do_work(data):
          if "region" in data:
              name = data["group"][0] if "group" in data else data["description"]
              out_dir = os.path.join(data["dirs"]["work"], dir_ext_fn(data))
              out_file = os.path.join(out_dir, "%s%s" % (name, ext))
              assert isinstance(data["region"], (list, tuple))
              out_parts = []
              for r, work_bams in sorted(_assign_bams_to_regions(data), key=_sort_by_size, reverse=True):
                  out_region_dir = os.path.join(out_dir, r[0])
                  out_region_file = os.path.join(out_region_dir,
                                                 "%s-%s%s" % (name, pregion.to_safestr(r), ext))
                  out_parts.append((r, work_bams, out_region_file))
              return out_file, out_parts
          else:
              return None, []
      return _do_work
docs: Organize splits based on regions generated by parallel_prep_region.
  
      Sort splits so largest regions analyzed first, avoiding potentially lagging runs
      at end.