Ported over from my Gist

https://gist.github.com/JamesMGreene/4371789