def extract_bval(in_dwi, in_bval, b=0, out_file=None):
    """
    Writes an image containing only the volumes with b-value specified at
    input
    """
    import numpy as np
    import nibabel as nb
    import os.path as op
    if out_file is None:
        fname, ext = op.splitext(op.basename(in_dwi))
        if ext == '.gz':
            fname, ext2 = op.splitext(fname)
            ext = ext2 + ext
        out_file = op.abspath('%s_tsoi%s' % (fname, ext))
    im = nb.load(in_dwi)
    dwidata = im.get_data()
    bvals = np.loadtxt(in_bval)
    if b == 'diff':
        selection = np.where(bvals != 0)
    elif b == 'nodiff':
        selection = np.where(bvals == 0)
    else:
        selection = np.where(bvals == b)
    extdata = np.squeeze(dwidata.take(selection, axis=3))
    hdr = im.header.copy()
    hdr.set_data_shape(extdata.shape)
    nb.Nifti1Image(extdata, im.affine, hdr).to_filename(out_file)
    return out_file
