def clamp(value, lower=None, upper=None):
    """ Returns value no lower than lower and no greater than upper.
        Use None to clamp in one direction only. """
    if lower is not None:
        value = max(value, lower)
    if upper is not None:
        value = min(value, upper)
    return value