refactoring and some fixes