an almost complete rewrite.