more refactoring and a few bugfixes