I've simplified this section of the test script considerably. Previously, before I started using webPageTest scripts as my preferred method of operation, results data were collected at this stage. Results are presented in the final response of this call (once 'status' is set to 'ok'. But I found, when a script is used, the results provided here are chosen by webPageTest and are not good enough for our purposes. We want to average over all test cycles for example. And you will see later that I skip failed test run as far as timings are concerned (but still flag them up as a failure).
So now the while loop is straight forward. All we need to check is that the webPageTest test cycle has finished and we need to get the url for finding the full results on the webPageTest server. The complete code is now one small page: