refactoring and some issues fixed