I updated the code to work better, and it's also more readable.

https://gist.github.com/8e6c52930c8bb11fac7c