Split out messy code from  into functions