Refactored code for Python 3