Bugfix and some refactoring