Much needed code refactoring