added some error checking and fixed minor bugs