Refactoring and bugfixing.