Moved error checking to the top of the function and moved the close() call