Rearrange logic to make next commit clearer.
Implement error handling.