Messages: refactor message handling