some refactoring and fixes.