Correctly close the file handle if there's an error writing.

Fixes #51.