Refactored code for better robustness.