Close on error

Properly close files in case of error.