rewriting this to accommodate FLAG_END_SEGMENT and use loop logic for the non base cases.