Start of refactoring and optimization