based on gist from  https://gist.github.com/710577