I haven’t looked at your code in great detail, but I can tell you that delay does not work in a loop.
You’ll need to make the loop ‘manually’, like this: