Code refactoring, minor fixes