updated for python2, some refactoring