Changed for-loop to while to fix pop index error bug