Ported some code to Python3, created tests, optimized.