untested rewrite of code to look better. derived from https://gist.github.com/bardiharborow/6943476