Refactoring the rewriting code