Refactor Erlang message processing and add graceful exit