https://gist.github.com/marcgg/733592#file-gistfile1-rb