I don't know how much possible this is: can the code be factorized so that some of the logic here ends up in a configuration file?
or is the whole thing too much convoluted with the rest of the code,  to the point that is not really straightforward?