Shell Script - Rearrange Header and Data of different versions of Text file based on a Master File

I want to re-arrange the data (Header and Detail) in multiple pipe delimited text files, in the order specified in a reference master file and create a single output file, using shell script.

The order of the columns will be different in different input files. Data could be empty for the columns. There could be columns missing or new columns in the input files, when compared to the Reference master file. The order in the Reference master file could change in future and columns could be added to or deleted from any position.

Sample Input file A:


Sample Input file B:


Reference Master File:


Output File: