moved duplicated code into functions