general refactoring and some small fixes