Clamps a double value to a given range.
@param x the value to clamp
@param min the minimum value of the range
@param max the maximum value of the range
@return the clamped value
Computes an index which wraps around a given maximum value.
For values >= 0, this is equals to val % max.
For values < 0, this is equal to max - (-val) % max