The function receives 10 arguments and I have counted more than 12 local variables with pretty limited scopes. I still think that most of those sections that have long explanatory comments and a `$variable_name` and `$variable_name_keys` patterns should become separated functions, so that what this one does becomes more obvious.