added some error checking and refactored