mainloop(ProxyPid, Ref, M, State) -> ProxyPid ! Ref, NewState = receive Messages -> lists:foldl( fun (Msg, S) -> M:handle_message(Msg, S) end, State, lists:reverse(Messages)) end, ?MODULE:mainloop(ProxyPid, Ref, M, NewState).