Keep count and don't fall out of bounds

Ticket: #5720