refactored file handling