I think I figured out what this does after a couple of minutes, but a comment or simplification would help. Can it be done more declaratively with list comprehensions?