Refactored placement of defer for file close