You were plenty clear; I'm just very conscientious when I think I might be misunderstanding a question. My posted code should meet your spec. I left your code intact so it would be easier for you to see my changes and thus understand the algorithm.
ikegami has some
lovely suggestions for how simplify/improve your code.