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

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Intntime   intntime        Time interpolation
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "param_conversion.h"
#include "datetime.h"
#include "printinfo.h"

size_t inttime(double fac1, double fac2, size_t gridsize, const double *single1, const double *single2, Varray<double> &array,
               bool withMissval, double missval1, double missval2);

void *
Intntime(void *process)
{
  cdo_initialize(process);

  operator_input_arg("number of timesteps between 2 timesteps");
  if (cdo_operator_argc() < 1) cdo_abort("Too few arguments!");

  const auto numts = parameter_to_int(cdo_operator_argv(0));
  if (numts < 2) cdo_abort("parameter must be greater than 1!");

  const auto streamID1 = cdo_open_read(0);

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

  VarList varList1, varList2;
  varListInit(varList1, vlistID1);
  varListInit(varList2, vlistID2);

  const auto nvars = vlistNvars(vlistID1);

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

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array(gridsizemax);

  Varray3D<size_t> nmiss(2);
  nmiss[0].resize(nvars);
  nmiss[1].resize(nvars);
  Varray3D<double> vardata(2);
  vardata[0].resize(nvars);
  vardata[1].resize(nvars);

  for (int varID = 0; varID < nvars; varID++)
    {
      const auto gridsize = varList1[varID].gridsize;
      const auto nlevel = varList1[varID].nlevels;
      nmiss[0][varID].resize(nlevel);
      nmiss[1][varID].resize(nlevel);
      vardata[0][varID].resize(gridsize * nlevel);
      vardata[1][varID].resize(gridsize * nlevel);
    }

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

  const auto streamID2 = cdo_open_write(1);

  cdo_def_vlist(streamID2, vlistID2);

  const auto calendar = taxisInqCalendar(taxisID1);

  int curFirst = 0, curSecond = 1;

  int tsID = 0;
  int tsIDo = 0;
  auto nrecs = cdo_stream_inq_timestep(streamID1, tsID++);
  const auto vdate1 = taxisInqVdate(taxisID1);
  const auto vtime1 = taxisInqVtime(taxisID1);
  auto juldate1 = juldate_encode(calendar, vdate1, vtime1);

  cdo_taxis_copy_timestep(taxisID2, taxisID1);
  cdo_def_timestep(streamID2, tsIDo++);
  for (int recID = 0; recID < nrecs; recID++)
    {
      int varID, levelID;
      cdo_inq_record(streamID1, &varID, &levelID);
      const auto offset = varList1[varID].gridsize * levelID;
      auto single1 = &vardata[curFirst][varID][offset];
      cdo_read_record(streamID1, single1, &nmiss[curFirst][varID][levelID]);

      cdo_def_record(streamID2, varID, levelID);
      cdo_write_record(streamID2, single1, nmiss[curFirst][varID][levelID]);
    }

  while (true)
    {
      nrecs = cdo_stream_inq_timestep(streamID1, tsID++);
      if (nrecs == 0) break;

      const auto vdate2 = taxisInqVdate(taxisID1);
      const auto vtime2 = taxisInqVtime(taxisID1);
      const auto juldate2 = juldate_encode(calendar, vdate2, vtime2);

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

          recList[recID].varID = varID;
          recList[recID].levelID = levelID;

          const auto offset = varList1[varID].gridsize * levelID;
          auto single2 = &vardata[curSecond][varID][offset];
          cdo_read_record(streamID1, single2, &nmiss[curSecond][varID][levelID]);
        }

      for (int it = 1; it < numts; it++)
        {
          const auto seconds = it * juldate_to_seconds(juldate_sub(juldate2, juldate1)) / numts;
          const auto juldate = juldate_add_seconds(lround(seconds), juldate1);

          int64_t vdate;
          int vtime;
          juldate_decode(calendar, juldate, vdate, vtime);

          if (Options::cdoVerbose) cdo_print("%s %s", date_to_string(vdate).c_str(), time_to_string(vtime).c_str());

          taxisDefVdate(taxisID2, vdate);
          taxisDefVtime(taxisID2, vtime);
          cdo_def_timestep(streamID2, tsIDo++);

          const auto diff = juldate_to_seconds(juldate_sub(juldate2, juldate1));
          const auto fac1 = juldate_to_seconds(juldate_sub(juldate2, juldate)) / diff;
          const auto fac2 = juldate_to_seconds(juldate_sub(juldate, juldate1)) / diff;

          for (int recID = 0; recID < nrecs; recID++)
            {
              const auto varID = recList[recID].varID;
              const auto levelID = recList[recID].levelID;
              const auto gridsize = varList1[varID].gridsize;
              const auto offset = gridsize * levelID;
              const auto single1 = &vardata[curFirst][varID][offset];
              const auto single2 = &vardata[curSecond][varID][offset];

              const auto withMissval = (nmiss[curFirst][varID][levelID] || nmiss[curSecond][varID][levelID]);
              const auto nmiss3 = inttime(fac1, fac2, gridsize, single1, single2, array, withMissval, varList1[varID].missval,
                                          varList2[varID].missval);

              cdo_def_record(streamID2, varID, levelID);
              cdo_write_record(streamID2, array.data(), nmiss3);
            }
        }

      taxisDefVdate(taxisID2, vdate2);
      taxisDefVtime(taxisID2, vtime2);
      cdo_def_timestep(streamID2, tsIDo++);
      for (int recID = 0; recID < nrecs; recID++)
        {
          const auto varID = recList[recID].varID;
          const auto levelID = recList[recID].levelID;
          const auto offset = varList2[varID].gridsize * levelID;
          auto single2 = &vardata[curSecond][varID][offset];

          cdo_def_record(streamID2, varID, levelID);
          cdo_write_record(streamID2, single2, nmiss[curSecond][varID][levelID]);
        }

      juldate1 = juldate2;
      std::swap(curFirst, curSecond);
    }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
