Refactored to try and speed up