Refactored and commented for a bit of a cleaner look