def bounding_box(bw, bh, w, h):
    """
    Returns a tuple (new_width, new_height) which has the property
    that it fits within box_width and box_height and has (close to)
    the same aspect ratio as the original size
    """
    new_width, new_height = w, h
    if bw and new_width > bw:
        new_width = bw
        new_height = new_width / (float(w) / h)
    if bh and new_height > bh:
        new_height = bh
        new_width = new_height * (float(w) / h)
    return new_width, new_height
