Not sure I got it completely correct, there was some more extensive logic in here, but at least the tests seem to work.
It would probably be good to get some feedback from @tadej, @zmarshal, @jburr or @khoo who seem to have written the original configuration.