Thank you all again.
I know some of the suggestions such as removing all API calls make sense to you, but I think that's even above my skillset!
The intloop count returned 2 which is correct as in test I'm just trying to create and send one invoice.
The file rename does happen before the error...