some optimization and refactoring