Refactoring giant function