This should be a separate function. Logically, it's pretty dense.