clean and rewrite some code