/****************************************************************************
 * This file is part of the project AqDiagram.
 * AqDiagram (c) by 2025 Martin Preuss, all rights reserved.
 *
 * The license for this file can be found in the file COPYING which you
 * should have received along with this file.
 ****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "./floatingavg.h"


static double _averageOverArray(const double *lastValues, int num);



AQDG_GRAPH_DATAPAIR_LIST *AQDG_Data_FloatingAverage(const AQDG_GRAPH_DATAPAIR_LIST *dpList, int num)
{
  if (dpList && AQDG_Graph_DataPair_List_GetCount(dpList)) {
    AQDG_GRAPH_DATAPAIR_LIST *newList;
    const AQDG_GRAPH_DATAPAIR *dp;
    double lastValues[num];
    int cnt=0;
    int idx=0;

    newList=AQDG_Graph_DataPair_List_new();
    dp=AQDG_Graph_DataPair_List_First(dpList);
    while(dp) {
      AQDG_GRAPH_DATAPAIR *newDp;
      double v;

      v=AQDG_Graph_DataPair_GetValueY(dp);
      idx%=num;
      lastValues[idx++]=v;
      cnt++;

      if (cnt<num) {
        /* buffer not full, average over the values we already have */
        v=_averageOverArray(lastValues, cnt);
      }
      else {
        /* buffer full, average over full buffer */
        v=_averageOverArray(lastValues, num);
      }

      newDp=AQDG_Graph_DataPair_dup(dp);
      AQDG_Graph_DataPair_SetValueY(newDp, v);
      AQDG_Graph_DataPair_List_Add(newDp, newList);

      dp=AQDG_Graph_DataPair_List_Next(dp);
    }
    return newList;
  }
  return NULL;
}



double _averageOverArray(const double *lastValues, int num)
{
  double v=0.0;

  if (num) {
    double totalSum=0.0;
    int i;

    /* average over full buffer */
    for (i=0; i<num; i++) {
      totalSum+=lastValues[i];
    }
    v=totalSum/((double)num);
  }
  return v;
}




