optimisation: changed some for() loops to do-while() to give the compiler