Here's a gist, I draw your attention to the comment on line 27.

https://gist.github.com/kastiglione/c943117c15f0254e71c4