Refactor and fix some bug