Added closing of files where possible