Did a lot of refactoring, now it's only 85 lines long and more readable than ever