refactor into functions
Initial work on performance improvements