Added more error checking to help ensure correct results