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

  Copyright (C) 2007 Brockmann Consult
  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:

      Seascount   seascount         Seasonal counts
*/

#include <cdi.h>

#include "cdo_season.h"
#include "datetime.h"
#include "process_int.h"

void *
Seascount(void *process)
{
  int64_t vdate0 = 0;
  int vtime0 = 0;
  int nrecs;
  int seas0 = 0;
  int oldmon = 0;

  cdoInitialize(process);

  cdoOperatorAdd("seascount", 0, 0, nullptr);

  operatorCheckArgc(0);

  const auto season_start = getSeasonStart();

  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);

  const auto maxrecs = vlistNrecs(vlistID1);
  std::vector<RecordInfo> recList(maxrecs);

  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;
  int otsID = 0;
  while (true)
    {
      int nsets = 0;
      bool newseas = false;
      while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
        {
          const auto vdate = taxisInqVdate(taxisID1);
          const auto vtime = taxisInqVtime(taxisID1);

          const auto month = decodeMonth(vdate);
          auto newmon = month;
          if (season_start == START_DEC && newmon == 12) newmon = 0;

          const auto seas = monthToSeason(month);

          if (nsets == 0)
            {
              seas0 = seas;
              oldmon = newmon;
            }

          if (newmon < oldmon) newseas = true;

          if ((seas != seas0) || newseas) break;

          oldmon = newmon;

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

              if (tsID == 0)
                {
                  recList[recID].varID = varID;
                  recList[recID].levelID = levelID;
                  recList[recID].lconst = vlistInqVarTimetype(vlistID1, varID) == TIME_CONSTANT;
                }

              const size_t fieldsize = vars1[varID][levelID].size;

              if (nsets == 0)
                {
                  for (size_t i = 0; i < fieldsize; i++) vars1[varID][levelID].vec_d[i] = vars1[varID][levelID].missval;
                  vars1[varID][levelID].nmiss = fieldsize;
                }

              cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);
              field.size = vars1[varID][levelID].size;
              field.grid = vars1[varID][levelID].grid;
              field.missval = vars1[varID][levelID].missval;

              vfarcount(vars1[varID][levelID], field);
            }

          vdate0 = vdate;
          vtime0 = vtime;
          nsets++;
          tsID++;
        }

      if (nrecs == 0 && nsets == 0) break;

      taxisDefVdate(taxisID2, vdate0);
      taxisDefVtime(taxisID2, vtime0);
      cdoDefTimestep(streamID2, otsID);

      for (int recID = 0; recID < maxrecs; recID++)
        {
          if (otsID && recList[recID].lconst) continue;

          const auto varID = recList[recID].varID;
          const auto levelID = recList[recID].levelID;
          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, vars1[varID][levelID].vec_d.data(), vars1[varID][levelID].nmiss);
        }

      if (nrecs == 0) break;
      otsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
