Updated to be more careful about closing files