some refactoring and bugfixes.