It’s generally good practice to define all your global variables and functions at the top of the script.
Another possible issue may be that if that while loop never terminates, the code below it would never be reached. Which is another reason to handle declarations at the beginning of the script.
When you call the function, it hasn’t been defined yet, hence the error. Define functions before you use them. Also please try to use local declarations for functions.