refactor and optimize some codes