these two nested while loops look dangerous to me (and hard to read)
Could you replace this with something less scary? Like for loops? :D