Refactor and fix bug