refactored file writing