Mostly complete rewrite

Mostly complete rewrite