Refactored code from Chris repo