Add some comments, simplify some code, and fix a bug that caused rewriting