move file-saving to within loop