Refactored some code, removed duplicates