def calc_subimage_size(image_x_size, image_y_size, num_x, num_y, margin=0):
    """Given an image of size image_x_size by image_y_size pixels,
    calculate how many pixels each subimage would be, if we want to
    divide it into a grid of size num_x by num_y subimages.

    Args:
        image_x_size (int): The width of the original image in pixels.
        image_y_size (int): The width of the original image in pixels.
        num_x (int): The number of columns of subimages you want.
        num_y (int): The number of rows of subimages you want.
        margin (int): The number of pixels of margins around all edges
                      of the original image which should be discounted.

    Returns:
        (sub_x_size, sub_y_size, x_offset, y_offset)
        sub_x_size (int): How many pixels wide each subimage should be.
        sub_y_size (int): How many pixels tall each subimage should be.
        x_offset (int): The offset from the left edge of the original
                        image to the first column of subimages.
        y_offset (int): The offset from the top edge of the original
                        image to the first row of subimages.

    Usage examples:

    Here we say that our original image is 30 by 30 pixels, and we
    want to make a grid of 6 columns and 6 rows, with no margin.
    The function tells us that we will be able to make a grid where
    each subimage is 5 by 5 pixels, and that there is no offset
    (because we didn't specify a margin):

    >>> calc_subimage_size(image_x_size=30, image_y_size=30,
    ...     num_x=6, num_y=6)
    (5, 5, 0, 0)

    Now we have an original image of 30 by 20 pixels, and we want
    to have a grid with 5 columns and 2 rows, and a margin on each
    side of the original image of 2 pixels.

    >>> calc_subimage_size(image_x_size=30, image_y_size=20,
    ...     num_x=5, num_y=2, margin=2)
    (5, 8, 3, 2)

    >>> calc_subimage_size(image_x_size=200, image_y_size=100,
    ...     num_x=10, num_y=5, margin=20)
    (16, 12, 20, 20)
    """
    sub_x_size = int((image_x_size - margin * 2) / num_x)
    sub_y_size = int((image_y_size - margin * 2) / num_y)
    x_offset = int((image_x_size - margin) % num_x / 2) + margin
    y_offset = int((image_y_size - margin) % num_y / 2) + margin
    return sub_x_size, sub_y_size, x_offset, y_offset
