Refactored code, removed some duplication