in reply to Please debug this code

Please eliminate aspects which are not relevant to your question. There's no reason for you to need more than 10 lines of data to demonstrate your problem.

While I didn't look into your problem, I couldn't help but notice two issues when I scrolled down.

So start by fixing the strictures, the warnings and the if (/.../g) constructs, then give us a manageable demonstration of your problem if it still exists.