Bugfix and refactoring