First version, based on my Gist