Refactored, and better error handling.