Tweaked and refactored some code