refactoring the core logic of rewrite_tag.