Added comments and cleaned up error handling.