Move code into functions for easier reading