In your code you set up a counter: every time an R vote is cast, add 1 to it. When the counter hits 5, change the next R vote to D and write that to the database. Then reset counter to zero.
Problem is the code is also writing to the display/screen what it’s doing, that’s the bug that enabled this fraud to be detected.
I haven’t read the details on how those cheated are finally able to cast an R vote that ‘takes’, if they go to another machine, or a precinct captain has to somehow force the machine to accept the R vote. How they’re fixing it will tell us what is broken.