added error checking and fixed bugs