refactor listening code
move utility functions to separate file