Refactoring for python 3 compatibility