Fix to close leaking file handles