/*
  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:

      Tstepcount  tstepcount  Count number of timesteps
*/

#include <cdi.h>

#include "process_int.h"
#include "param_conversion.h"
#include "cdo_options.h"
#include "cimdOmp.h"


template <typename T>
static T
tstepcount(long nts, T missval, const Varray<T> &v, T refval)
{
  if (DBL_IS_EQUAL(refval, missval)) return missval;

  long j;
  long n = 0;
  for (j = 0; j < nts; j++)
    {
      n++;
      if (DBL_IS_EQUAL(v[j], refval)) break;
    }

  return (j == nts) ? missval : (T) n;
}

void *
Tstepcount(void *process)
{
  int nrecs;
  int varID, levelID;
  int64_t vdate = 0;
  int vtime = 0;

  cdoInitialize(process);

  auto refval = (operatorArgc() == 1) ? parameter2double(cdoOperatorArgv(0)) : 0.0;

  const auto streamID1 = cdoOpenRead(0);

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

  vlistDefNtsteps(vlistID2, 1);

  const auto nvars = vlistNvars(vlistID1);
  for (varID = 0; varID < nvars; varID++) cdiDefKeyString(vlistID2, varID, CDI_KEY_UNITS, "steps");

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

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

  VarList varList1;
  varListInit(varList1, vlistID1);

  FieldVector3D vars;

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      constexpr size_t NALLOC_INC = 1024;
      if ((size_t) tsID >= vars.size()) vars.resize(vars.size() + NALLOC_INC);

      vdate = taxisInqVdate(taxisID1);
      vtime = taxisInqVtime(taxisID1);

      fieldsFromVlist(vlistID1, vars[tsID]);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          auto &field = vars[tsID][varID][levelID];
          field.init(varList1[varID]);
          cdoReadRecord(streamID1, field);
        }

      tsID++;
    }

  int nts = tsID;

  std::vector<Field> fields(Threading::ompNumThreads);

  for (varID = 0; varID < nvars; varID++)
    {
      auto memType = varList1[varID].memType;
      auto missval = varList1[varID].missval;
      auto gridsize = varList1[varID].gridsize;
      for (levelID = 0; levelID < varList1[varID].nlevels; levelID++)
        {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(memType, gridsize, nts, refval, fields, vars, varID, levelID, missval) schedule(dynamic, 1)
#endif
          for (size_t i = 0; i < gridsize; i++)
            {
              const auto ompthID = cdo_omp_get_thread_num();

              if (memType == MemType::Float)
                {
                  auto &v = fields[ompthID].vec_f;
                  v.resize(nts);
                  for (int t = 0; t < nts; t++) v[t] = vars[t][varID][levelID].vec_f[i];

                  const auto count = tstepcount(nts, (float)missval, v, (float)refval);

                  vars[0][varID][levelID].vec_f[i] = count;
                }
              else
                {
                  auto &v = fields[ompthID].vec_d;
                  v.resize(nts);
                  for (int t = 0; t < nts; t++) v[t] = vars[t][varID][levelID].vec_d[i];

                  const auto count = tstepcount(nts, missval, v, refval);

                  vars[0][varID][levelID].vec_d[i] = count;
                }
            }
        }
    }

  taxisDefVdate(taxisID2, vdate);
  taxisDefVtime(taxisID2, vtime);
  cdoDefTimestep(streamID2, 0);

  for (varID = 0; varID < nvars; varID++)
    {
      for (levelID = 0; levelID < varList1[varID].nlevels; levelID++)
        {
          cdoDefRecord(streamID2, varID, levelID);
          auto &field1 = vars[0][varID][levelID];
          fieldNumMV(field1);
          cdoWriteRecord(streamID2, field1);
        }
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
