As a preparation to make the script easier to understand, we extract some of the sub tasks into functions.