big rewrite, tests passing again