refactor code out into 'lib' directory