added a bit of error checking and cleanup