It would be better to de-duplicate the branches of this loop (and the next) to show what actually differs in the various cases.