Code based on gist https://gist.github.com/emhart/1503428