reduce branching by taking the file handling logic outside