This logic could use a comment as it's not straightforward what it's doing.