nearly complete rewrite