refactor and fix bug