Extensive code refactoring