Refactored for better performance and features.