Refactored function merge_files()