Almost complete rewrite based on feedback and code from zahlman