Fixing lots of bugs in rewrite