might be nice to factor this deeply-nested case out into a few functions.