Would be nice to reduce the excessive branching in this block.