Finished most of the error handling and refactoring.