Refactored to be nicer
Added type checking where possible