Reimplemented most of the same stuff in Python
Some tidying up