This code here from L916-921 is really compact - a lot is being done in a few lines. I think it might be better to split this out into its own function and provide some good comments for each line explaining the logic that's being done.