anchor.diff:           terminate/2]).
   
   -define(NUM_MESSAGES, 3). % Number of the most recent messages to log on crash
  +-define(MAX_MESSAGES, 10). % Max messages per interval
  +-define(INTERVAL, 1000). % Interval over which to throttle
   
   -define(UNEXPECTED, 1).
   
   -include_lib("eunit/include/eunit.hrl").
   
   %% Server state
  --record(state, {port, name, messages}).
  +-record(state, {port, name, messages, log_tref, log_buffer=[], dropped=0}).
   
   
   %% API
  
positive.code:                 messages = ringbuffer:new(?NUM_MESSAGES)}}.
  
  handle_info({_Port, {data, {_, Msg}}}, State) ->
      {Msgs, Dropped} = fetch_messages(99, 1000),
      L = [Msg|Msgs],
      %% Store the last messages in case of a crash
      Messages = lists:foldl(fun ringbuffer:add/2, State#state.messages, L),
      error_logger:info_msg(format_lines(State#state.name, L)),
      if Dropped > 0 ->
              ?log_warning("Dropped ~p log lines from ~p",
                           [Dropped, State#state.name]);
         true ->
              ok
      end,
      {noreply, State#state{messages=Messages}};
  handle_info({_Port, {exit_status, 0}}, State) ->
      {stop, normal, State};
  handle_info({_Port, {exit_status, Status}}, State) ->
  
negative.code: %% received up to Timeout. The goal is to remove messages from the
  %% queue as fast as possible if the port is spamming, avoiding
  %% spamming the log server.
  format_lines(Name, Lines) ->
      Prefix = io_lib:format("~p~p: ", [Name, self()]),
      [[Prefix, Line, $\n] || Line <- Lines].
  
  
  log(State) ->
      case State#state.log_buffer of
          [] ->
              ok;
          Buf ->
              error_logger:info_msg(format_lines(State#state.name,
                                                 lists:reverse(Buf))),
              case State#state.dropped of
                  0 ->
                      ok;
                  Dropped ->
                      ?log_warning("Dropped ~p log lines from ~p",
                                   [Dropped, State#state.name])
              end
      end,
      State#state{log_tref=undefined, log_buffer=[], dropped=0}.
  
  
  open_port({_Name, Cmd, Args, OptsIn}) ->
      %% Incoming options override existing ones (specified in proplists docs)
  