Port most of the code to Python3 compatible.