Some cleanup regarding stream closing.

Removed code duplication.