Refactored thanks to some great input