Refactor to add python3 compatibility