Rewrite, more correct, with better error handling.