More refactoring, some optimization