Improve error handling and state machine usage