nearly a complete rewrite