refactor and bug fix