some code cleanup and guarantee file closing