function b = moduloRange(a, range)
%MODULORANGE Modulo in a given range.
%   B = MODULORANGE(A, [MINVALUE MAXVALUE]) returns the input value A
%   modulo in the given range. I.e.
%   B = mod(A - MINVALUE, (MAXVALUE - MINVALUE)) + MINVALUE

%   Author: Damien Teney

assert(numel(range) == 2);
minValue = range(1);
maxValue = range(2);
assert(minValue < maxValue);

b = mod(a - minValue, (maxValue - minValue)) + minValue;

% Correct numerical errors
b(b >= maxValue) = b(b >= maxValue) - eps(b(b >= maxValue));
b(b <  minValue) = b(b <  minValue) + eps(b(b >= maxValue));
