refactoring and bug fix
and more refactoring