Refactoring and bugfixing