minor rewrite for Python 3 support. Some other fixes in corresponding files.