applied modulo and allocation optimizations, added test