Rewrite some files and fix bugs