def Order4(r, grid=None, intify=False):
    """Returns (rxmin, rxmax, rymin, rymax)
    Arg: r      <- 4-tuple
         grid   <- to check bounds
         intify <- result items are integers
    """
    rx1, rx2, ry1, ry2 = r[0], r[1], r[2], r[3]
    if rx1 > rx2:
        rx1, rx2 = rx2, rx1
    if ry1 > ry2:
        ry1, ry2 = ry2, ry1
    rx1 = max(rx1, 0)
    ry1 = max(ry1, 0)
    if grid is not None:
        rx2 = min(rx2, len(grid) - 1)
        ry2 = min(ry2, len(grid[0]) - 1)
    if intify:
        rx1, rx2, ry1, ry2 = list(map(int, [rx1, rx2, ry1, ry2]))
    return rx1, rx2, ry1, ry2
