'Creates the index for the BAM file.'

def set_meta(self, dataset, overwrite=True, **kwd):

    index_file = dataset.metadata.bam_index
    if (not index_file):
        index_file = dataset.metadata.spec['bam_index'].param.new_file(dataset=dataset)
    stderr_name = tempfile.NamedTemporaryFile(prefix='bam_index_stderr').name
    command = ['samtools', 'index', dataset.file_name, index_file.file_name]
    exit_code = subprocess.call(args=command, stderr=open(stderr_name, 'wb'))
    if (exit_code == (-6)):
        dataset_symlink = os.path.join(os.path.dirname(index_file.file_name), ('__dataset_%d_%s' % (dataset.id, os.path.basename(index_file.file_name))))
        os.symlink(dataset.file_name, dataset_symlink)
        try:
            command = ['samtools', 'index', dataset_symlink]
            exit_code = subprocess.call(args=command, stderr=open(stderr_name, 'wb'))
            shutil.move((dataset_symlink + '.bai'), index_file.file_name)
        except Exception as e:
            open(stderr_name, 'ab+').write(('Galaxy    attempted    to    build    the    BAM    index    with    samtools    1.0+    but    failed:    %s\n' % e))
            exit_code = 1
        finally:
            os.unlink(dataset_symlink)
    stderr = open(stderr_name).read().strip()
    if stderr:
        if (exit_code != 0):
            os.unlink(stderr_name)
            raise Exception(('Error    Setting    BAM    Metadata:    %s' % stderr))
        else:
            print(stderr)
    dataset.metadata.bam_index = index_file
    os.unlink(stderr_name)
    try:
        bam_file = pysam.AlignmentFile(dataset.file_name, mode='rb', index_filename=index_file.file_name)
        dataset.metadata.reference_names = list(bam_file.references)
        dataset.metadata.reference_lengths = list(bam_file.lengths)
        dataset.metadata.bam_header = bam_file.header
        dataset.metadata.read_groups = [read_group['ID'] for read_group in dataset.metadata.bam_header.get('RG', []) if ('ID' in read_group)]
        dataset.metadata.sort_order = dataset.metadata.bam_header.get('HD', {}).get('SO', None)
        dataset.metadata.bam_version = dataset.metadata.bam_header.get('HD', {}).get('VN', None)
    except:
        pass
