Refactored to be clearer and easier to apply
Refactored to use functions
Added performancing