Rewrite whole program into a more tidy way