'Ensures that the Bam file contents are sorted.  This function is called
on an output dataset after the content is initially generated.'

def groom_dataset_content(self, file_name):

    if (not self.dataset_content_needs_grooming(file_name)):
        return
    tmp_dir = tempfile.mkdtemp()
    tmp_sorted_dataset_file_name_prefix = os.path.join(tmp_dir, 'sorted')
    stderr_name = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix='bam_sort_stderr').name
    samtools_created_sorted_file_name = ('%s.bam' % tmp_sorted_dataset_file_name_prefix)
    command = ('samtools    sort    %s    %s' % (file_name, tmp_sorted_dataset_file_name_prefix))
    proc = subprocess.Popen(args=command, shell=True, cwd=tmp_dir, stderr=open(stderr_name, 'wb'))
    exit_code = proc.wait()
    stderr = open(stderr_name).read().strip()
    if stderr:
        if (exit_code != 0):
            shutil.rmtree(tmp_dir)
            raise Exception(('Error    Grooming    BAM    file    contents:    %s' % stderr))
        else:
            print(stderr)
    shutil.move(samtools_created_sorted_file_name, file_name)
    os.unlink(stderr_name)
    os.rmdir(tmp_dir)
