added some error checking and comments