Refactored for use with Python 3 as well as Python2.6+