Refactored to try and avoid memory leak