Factorize some common code with convenient api. Fix do-while loops