Add conditional closing and releasing and more debugging