large refactoring, moved code into functions