added error catching and some cleanup