Improved error handling (see #2), ensured clean shutdown, and added more informative output