cleanup and refactor error handling