Factorize some code into functions, had this in my tree and will be