Nit: this is a little dense here. From a code clarity perspective, it might be good to break this up with some inline docs.