Code ported and updated to Python 3.