Add safe "close" function