separated most main parts into functions