Some cleanup and better error handling.