Backport to python 2.6 and a lot of restructuring