Whilst I've not subjected it to exhaustive testing, it did pass some simple doctests:

https://gist.github.com/funkybob/6332718