Added shutdown hooks to make sure files flushed and closed.