refactored for compatibility with python 2.7.6 and 3.4