Python 3 support and refactoring