Almost a complete rewrite