almost complete rewrite