Combine nested while loops into one loop