You should not nest the WHILE loops, instead you can combine the three loops to have a single loop alone.