cleanup and some error checking