This is doing a lot in a tight space. Consider adding a comment explaining what it is going on here and using different internal variable names for self-documentation.