Copy over much of the implementation from the gist

https://gist.github.com/kezabelle/9481971