Fixed bugs when closing files