Some refactoring of code into functions