add flush and move close() statements