Some refactoring and bugfixing