Cleanup and improve error reporting