Update: I realize that the line that generates $index is a potential point of failure via false positives (matching "10" when $bad = 1, for example). However, I've discussed this with the OP and he says it's not an issue, due to the fact that the values are all 4-digit numbers.