Almost a complete rewrite.