anchor.diff:  -module(stats_archiver).
   
   -include_lib("eunit/include/eunit.hrl").
  --include_lib("stdlib/include/qlc.hrl").
   
   -include("ns_common.hrl").
   -include("ns_stats.hrl").
  
positive.code: %% @doc Truncate a timestamp to the nearest multiple of N seconds.
  trunc_ts(TS, N) ->
      TS - (TS rem (N*1000)).
  
negative.code: 
  
  %% @doc Resample the stats in a table. Only reads the necessary number of rows.
  resample(Tab, Step, N) ->
      {atomic, Result} = mnesia:transaction(
                           fun () ->
                                   TS = mnesia:last(Tab),
                                   T = case TS of
                                           '$end_of_table' -> '$end_of_table';
                                           _ -> trunc_ts(TS, Step)
                                       end,
                                   resample(Tab, Step, TS, T, [], [], N)
                           end, ?RETRIES),
      Result.
  
  
  resample(_, _, TS, _, Acc, [], N) when TS == '$end_of_table'; N == 0 ->
      Acc;
  resample(_, _, _, _, Acc, _, 0)  ->
      Acc;
  resample(_, _, '$end_of_table', T, Acc, Chunk, _) ->
      [avg(T, Chunk)|Acc];
  resample(Tab, Step, TS, T, Acc, Chunk, N) ->
      T1 = trunc_ts(TS, Step),
      [Rec] = mnesia:read(Tab, TS),
      Prev = mnesia:prev(Tab, TS),
      case T of
          T1 ->
              resample(Tab, Step, Prev, T1, Acc, [Rec|Chunk], N);
          _ ->
              resample(Tab, Step, Prev, T1, [avg(T, Chunk)|Acc], [], N-1)
      end.
  
  
  