lots of refactoring
more refactoring and migration to Python 3.x