a bugfix, and some refactoring