refactor pieces into functions