The code in this block is rather complex. I'd suggest refactoring it into smaller chunk methods with speaking names.