Funny, I would have approached this by removing the while loop and the if else parts of the BEGIN clause, leveraging the stock file reading and line iteration along with AWK pattern matching (terminated with a next statement to skip to the next row), and then shoved the rest in the END clause.
It’s always been a “thing” with me of not liking to put everything into BEGIN. Kind of a “if I’m doing that, why am I using awk” thing.
Just how I approach problems with awk.