I wish this whole function were a bit more readable but I don't have an immediate suggestion. It does look like there are some implicit conventions around the meaning of empty sets, etc, and maybe if those were made more explicit? Maybe just a couple comments would be enough if there isn't an obvious code change.