Refactoring + bugfixing