bugfix and minor refactoring