def replace_vol(img, vol, center, vol_as_mask=None):
    """Replace a volume within an image, centering on the given coordinates 
    and cropping the input volume to fit.

    Args:
        img: Image as a Numpy array into which ``vol`` will be placed. 
            ``img`` will be updated in-place.
        vol: Volume to place in ``img``.
        center: Coordinates of the center of volume, given in z,y,x order.
        vol_as_mask: If ``vol`` should be taken as a mask, where only 
            its True values will replace the corresponding pixels in 
            ``img``, assign this value to the mask locations. Defaults to 
            None, in which case the entire ``vol`` will be assigned.

    Returns:
        ``img`` with ``vol`` centered on ``center``.
    """
    dims = vol.ndim
    slices_img = []
    slices_vol = []
    for i in range(dims):
        start_vol = 0
        stop_vol = int(vol.shape[i])
        # center volumes with odd-numbered length, and skew slightly 
        # toward lower values for even-numbered length
        start = int(center[i] - vol.shape[i] // 2)
        stop = start + stop_vol
        # ensure that slices do not exceed bounds of img, also cropping 
        # volume if so
        if start < 0:
            start_vol = abs(start)
            start = 0
        if stop >= img.shape[i]:
            stop_vol -= stop - img.shape[i]
            stop = img.shape[i]
        slices_img.append(slice(start, stop))
        slices_vol.append(slice(start_vol, stop_vol))
    if vol_as_mask is not None:
        # replace vol as a mask
        img[tuple(slices_img)][vol[tuple(slices_vol)]] = vol_as_mask
    else:
        # replace complete vol
        img[tuple(slices_img)] = vol[tuple(slices_vol)]
    return img