Evolution of this gist https://gist.github.com/cra/ecb1ae49e06e79c13c80