more efficient rewriting (not perfect though)