Compression: Properly close gzip/deflate

Cleaned up version of #604 ready to merge.