Code refactoring and bugfixing