Refactoring but the program is bugged