ported to python and made a lot nicer