Pretty much a complete rewrite