Bugfixing and refactoring