Fix an error message and add a few more safety checks.