tested error case and refactored to clean up some logic