Code refactoring + bugfixes