Changed do-while loops to for-loops for safer looping