Python 3 compatibility modifications (not done yet) and some tidying up