some cleanup and improved exception handling