Fix message encoding both ways and refactor.