Rewrite

I think this is good enough to merge with master now.