Refactored to aim for Python 3 support