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

  Copyright (C) 2006 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:

      Runpctl    runpctl         Running percentiles
*/

#include <cdi.h>

#include "functs.h"
#include "process_int.h"
#include "param_conversion.h"
#include "percentiles.h"
#include "datetime.h"

void *
Runpctl(void *process)
{
  const TimeStat timestat_date = TimeStat::MEAN;
  size_t nmiss;

  cdoInitialize(process);

  cdoOperatorAdd("runpctl", func_pctl, 0, nullptr);

  operatorInputArg("percentile number, number of timesteps");
  operatorCheckArgc(2);
  const auto pn = parameter2double(cdoOperatorArgv(0));
  const auto ndates = parameter2int(cdoOperatorArgv(1));

  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);
  taxisWithBounds(taxisID2);
  vlistDefTaxis(vlistID2, taxisID2);

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

  const auto nvars = vlistNvars(vlistID1);

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

  DateTimeList dtlist;
  dtlist.setStat(timestat_date);
  dtlist.setCalendar(taxisInqCalendar(taxisID1));

  FieldVector3D vars1(ndates + 1);
  Varray<double> array(ndates);

  for (int its = 0; its < ndates; its++) fieldsFromVlist(vlistID1, vars1[its], FIELD_VEC);

  VarList varList1;
  varListInit(varList1, vlistID1);

  int tsID;
  for (tsID = 0; tsID < ndates; tsID++)
    {
      auto nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) cdoAbort("File has less than %d timesteps!", ndates);

      dtlist.taxisInqTimestep(taxisID1, tsID);

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

          cdoReadRecord(streamID1, vars1[tsID][varID][levelID].vec_d.data(), &nmiss);
          vars1[tsID][varID][levelID].nmiss = nmiss;
        }
    }

  int otsID = 0;
  while (true)
    {
      for (int varID = 0; varID < nvars; varID++)
        {
          if (varList1[varID].timetype == TIME_CONSTANT) continue;

          const auto gridsize = varList1[varID].gridsize;
          const auto nlevels = varList1[varID].nlevels;
          const auto missval = varList1[varID].missval;

          for (int levelID = 0; levelID < nlevels; levelID++)
            {
              auto &rvars1_0 = vars1[0][varID][levelID];
              nmiss = 0;
              for (size_t i = 0; i < gridsize; i++)
                {
                  int j = 0;
                  for (int inp = 0; inp < ndates; inp++)
                    {
                      const auto val = vars1[inp][varID][levelID].vec_d[i];
                      if (!DBL_IS_EQUAL(val, missval)) array[j++] = val;
                    }

                  if (j > 0)
                    {
                      rvars1_0.vec_d[i] = percentile(array.data(), j, pn);
                    }
                  else
                    {
                      rvars1_0.vec_d[i] = missval;
                      nmiss++;
                    }
                }
              rvars1_0.nmiss = nmiss;
            }
        }

      dtlist.statTaxisDefTimestep(taxisID2, ndates);
      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[0][varID][levelID].vec_d.data(), vars1[0][varID][levelID].nmiss);
        }

      otsID++;

      dtlist.shift();

      vars1[ndates] = vars1[0];
      for (int inp = 0; inp < ndates; inp++) vars1[inp] = vars1[inp + 1];

      const auto nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) break;

      dtlist.taxisInqTimestep(taxisID1, ndates - 1);

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, vars1[ndates - 1][varID][levelID].vec_d.data(), &nmiss);
          vars1[ndates - 1][varID][levelID].nmiss = nmiss;
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
