Fork of defunkt's gist, with some additions.