extracted some logic into functions