rewrite codes, clean up