Moved flush() call to ensure no crashing occurs