Refactored code and a bit of cleanup