Refactor handling of messages