refactor code and fix bug