some refactoring to prepare to Python 3 transition (also added some tests)