Refactors listening code