Refactored for increased robustness and performance