See the code in: https://gist.github.com/bshambaugh/0a22155760145fafc3ed79abe3c988a9
See the code in:
https://gist.github.com/bshambaugh/0a22155760145fafc3ed79abe3c988a9