Move code to https://gist.github.com/iandexter/7476990