fixed the main loop exiting too soon; added more error chekcing