refactoring  and bug fix