Refactoring and optimizing code (broken)