better file handling logic