Clean working version by moving some code to separate function.