I extracted some of the logic elsewhere, hopefully making this a bit nicer.