cleanup and error checking