Use on.exit() for closing connections and restoring options in write.mon.complete() and format.header().