[#1597] Refactored for code clarity and improved error message.