actually, the whole procedure, from lines 2094 to 2111, is repeated multiple times, can we abstract this as a function and pass in the file names as arguments?