First bunch of fixes for Python 3 compatibility. Still supports Python 2.6