error checking and some cleanup