Major fixing of more consistent write stream states.

More testing needed to ensure that it is really working.