1.
You have a variable j. Is it declared as int or long_int? 8 bit, 16 bit, or 32 bit? It's compared to 2000000 which is more than 16 bits for a decimal figure.
2.
Your WHILE statements appear to be a compound expression. I'm not saying it's incorrect but it might help if you were to evaluate each expression on a separate line, and set a different flag variable for each, to make it easier to watch how many times the loop executes, and what makes it exit. (Does the WHILE loop require a WEND statement at the end?)
3.
Add verbose reporting of values so you can watch that the program is executing properly. That loops execute the proper number of times. That loops exit when they should. Etc.