Refactored while-loop into a separate method to reduce complexity