refactored to make more robust