No problem ... I'm glad it helped. It based on the work of smarter people than me.
Essentially it came down to a gaps and islands problem. This article by Jeff Moden was the one was thinking of when I put it together, but there are other articles out there that also cover it.