code refactoring and bugfixes