def clamp(x, ab):
    (a, b) = ab
    return max(a, min(b, x))


def rescale(x, from_limits, to_limits):
    (a, b) = from_limits
    x_0_1 = (x - a) / (b - a)

    (c, d) = to_limits
    return c + (d - c) * x_0_1