refactored file read and write