refactoring and a few fix