make file closing more robust