extracted everything into single function