This is probably the most complex part of the PR. It took me a bunch of iterations to get it right.