changed loops into while loops