Redmine/6553: Fix implicit looping over multiple lists

Pull request for initial review of the changes to the code. Planning to add more test coverage to the acceptance test before merging.
There really should be some comments on vars and var_states, to give the poor innocent reader some warning of the fact that this is an iterator over a cartesian product of many iterables.