Code refactoring. Bugfixes