starting to re-organinze code from the gist that was published:

https://gist.github.com/skratchdot/797af25cec75c43ee056