finished a bit of refactoring to make it a bit more readable