added some error checking and other modifications