Refactor out common parts for while loops

Signed-off-by: Stefan Marr <git@stefan-marr.de>