This is getting a bit dense. Maybe try to refactor this into a function or two? Same for the `else` block.