/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2020 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

/*
   This module contains the following operators:

      Timcumsum    timcumsum         Cumulative sum over time
*/

#include <cdi.h>

#include "process_int.h"

void *
Timcumsum(void *process)
{
  int varID, levelID;

  cdoInitialize(process);

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID2, taxisID2);

  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  auto gridsizemax = vlistGridsizeMax(vlistID1);
  if (vlistNumber(vlistID1) != CDI_REAL) gridsizemax *= 2;

  Field field;
  field.resize(gridsizemax);

  FieldVector2D vars1;
  fieldsFromVlist(vlistID1, vars1, FIELD_VEC);

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) break;

      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);

          auto &rvars1 = vars1[varID][levelID];

          const auto fieldsize = rvars1.size;

          if (tsID == 0)
            {
              cdoReadRecord(streamID1, rvars1.vec_d.data(), &rvars1.nmiss);
              if (rvars1.nmiss)
                for (size_t i = 0; i < fieldsize; ++i)
                  if (DBL_IS_EQUAL(rvars1.vec_d[i], rvars1.missval)) rvars1.vec_d[i] = 0;
            }
          else
            {
              cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);
              field.size = fieldsize;
              field.grid = rvars1.grid;
              field.missval = rvars1.missval;

              if (field.nmiss)
                for (size_t i = 0; i < fieldsize; ++i)
                  if (DBL_IS_EQUAL(field.vec_d[i], rvars1.missval)) field.vec_d[i] = 0;

              vfarsum(rvars1, field);
            }

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, rvars1.vec_d.data(), rvars1.nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
