Did a bit of refactoring for readability, might have made it faster or found a bug