Minor bugfixing and refactoring