Fixes and optimizations

Fixed the previous non-working commit.
Tried to optimize the speed: the modulo seemed to be very slow.
Not tested, I would recommend using the version 2 commits ago because
it is tested and working.