Code refactoring, code cleanup, minor bugfixes