Fix #615 by opening the output stream only if needed