2.7 backport

May have some stuff missing.
Seems to work well under python2.7 from wheezy though.